Solved

Is there a way to convert instances  of type inputstream , outputstream to ServletRequest and ServletResponse types ?

Posted on 2007-03-21
17
1,073 Views
Last Modified: 2007-12-19
Hi,
Actually I have objects of type inputstream, outputstream  as shown in code below:
OutputStream raw = new BufferedOutputStream(connection.getOutputStream( ));        
 Writer out = new OutputStreamWriter(raw);
Reader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream( )),"ASCII");

Now I want to convert these to ServletRequest and ServletResponse types so as to pass it to a dynamically invoked servlet class like:
servlet1 = (Servlet) myServletClass.newInstance();
servlet1.service(?,?);

However I am not sure how I do such conversion ? A simple typecast to ServletRequest and ServletResponse doesn't works.

Any suggestions .
0
Comment
Question by:bjuneja_2000
  • 4
  • 4
  • 3
  • +2
17 Comments
 
LVL 92

Expert Comment

by:objects
ID: 18767833
I don't think you can (easily) a ServletRequest and ServletResponse are more than just a couple of streams.
Plus they are just interfaces, you'll need an actual implementation of them to use.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 18767839
What are you attempting to achieve by this?
0
 

Author Comment

by:bjuneja_2000
ID: 18767983
Hmm,
OK , Don't think I am crazy but I am trying to build my own naive servlet container, just to get some good hands on java .
So  to begin with I create a  connection  object of type Socket.  Then following:
OutputStream raw = new BufferedOutputStream(connection.getOutputStream( ) );
 Writer out = new OutputStreamWriter(raw);
Reader in = new InputStreamReader(new BufferedInputStream( connection.getInputStream( ) ),"ASCII");

Then I check the content type of client's request by examing the request header:
StringBuffer requestLine = new StringBuffer( );
        int c;
        while (true) {
          c = in.read( );
          if (c == '\r' || c == '\n') break;
          requestLine.append((char) c);
        }
                       String get = requestLine.toString( );
        System.out.println(get);
Now I use a StringToeknizer to figure out file extension . If its .class I know I need to invoke the servlet of the same name , so I call following piece of code:
String pathname ="C:\\mmoo\\";
File file = new File(pathname);
              try {
               
                  URL url = file.toURL();      
                URL[] urls = new URL[]{url};
                ClassLoader cl = new URLClassLoader(urls);
               
                Class cls = cl.loadClass("NewServlet.class");
                String boo= cls.getCanonicalName();
                System.out.println(boo);
                Servlet servlet1 = null;
                servlet1 = (Servlet) cls.newInstance();
                System.out.println("closer................");
               servlet1.service((?,?);
              } catch (Exception e) {
            }                    
     
Check out the third line from below      servlet1.service((?,?);  To this I need to pass servletRequest , servletResponse , however I am unable to understand how can I convert        out and in  instances created in beginning to required types ....[ I think I need some sort of request and response handle to my browser where the servlet can dump the execution result back ] ...

                   
0
 
LVL 92

Expert Comment

by:objects
ID: 18767995
Then you need to create your own ServletRequest and ServletResponse implementations.
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 168 total points
ID: 18768011
You probably should start with a simple web server and then integrate an existing servlet engine (which will be challenging enough)
0
 

Author Comment

by:bjuneja_2000
ID: 18768054
hmm ,
   do u know any specific method that I will need to override in implementing ServletRequest and ServletResponse  apart from implementing all the methods of ServletRequest and response.. ..

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 18768080
You need to implement all the methods and read the spec
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 92

Assisted Solution

by:objects
objects earned 166 total points
ID: 18768082
no, you just need to implement the interface methods
though you might want to implement HttpServletRequest instead of just ServletRequest (similiarly for response)
0
 

Author Comment

by:bjuneja_2000
ID: 18768234
OK ,
While u were writing , I tried to quickly write a Request class that implements ServletRequest interface and ServletResponse interface.I have appended the classs below. However here is the problem  block :
try {
               
                  URL url = file.toURL();      
                URL[] urls = new URL[]{url};
                ClassLoader cl = new URLClassLoader(urls);
               
                Class cls = cl.loadClass("NewServlet.class");
                String boo= cls.getCanonicalName();
                System.out.println(boo);
                Servlet servlet1 = null;
                servlet1 = (Servlet) cls.newInstance();
                System.out.println("closer................");
                Request in1 = new Request(in);
                Response ou1 = new Response(out);
                servlet1.service((ServletRequest)in1,(ServletResponse)ou1);
                System.out.println(servlet1.getServletInfo());
               
              } catch (Exception e) {
            }
This hangs right on the call to ClassLoader cl = new URLClassLoader(urls);  
Not sure why ? Any clues .....  So I am now stuck bit above the line where I would test if my servlet is getting invoked correctly or not ..: -( ..


Anyway here's my ServletRequest and Response implementation:
import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import java.io.*;


public class Request implements ServletRequest {

  private Reader input;
  private String uri;

  public Request(Reader input){
    this.input = input;
  }

    /* implementation of ServletRequest */
  public Object getAttribute(String attribute) {
    return null;
  }
  public Enumeration getAttributeNames() {
    return null;
  }
  public String getRealPath(String path) {
    return null;
  }
  public RequestDispatcher getRequestDispatcher(String path) {
    return null;
  }
  public boolean isSecure() {
    return false;
  }
  public String getCharacterEncoding() {
    return null;
  }
  public int getContentLength() {
    return 0;
  }

  public String getContentType() {
    return null;
  }
  public ServletInputStream getInputStream() throws IOException {
    return null;
  }
  public Locale getLocale() {
    return null;
  }
  public Enumeration getLocales() {
    return null;
  }
  public String getParameter(String name) {
    return null;
  }
  public Map getParameterMap() {
    return null;
  }
  public Enumeration getParameterNames() {
    return null;
  }
  public String[] getParameterValues(String parameter) {
    return null;
  }
  public String getProtocol() {
    return null;
  }
  public BufferedReader getReader() throws IOException {
    return null;
  }
  public String getRemoteAddr() {
    return null;
  }
  public String getRemoteHost() {
    return null;
  }
  public String getScheme() {
    return null;
  }
  public String getServerName() {
    return null;
  }
  public int getServerPort() {
    return 0;
  }
  public int getLocalPort() {
    return 0;
   
  }
  public String getLocalAddr() {
    return null;
   
  }
  public String getLocalName() {
    return null;
   
  }
  public int getRemotePort() {
    return 0;
   
  }
 
  public String getRemoteName() {
    return null;
   
  }
  public void removeAttribute(String attribute) {  }
  public void setAttribute(String key, Object value) {  }
  public void setCharacterEncoding(String encoding)
    throws UnsupportedEncodingException {  }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletResponse;
import javax.servlet.ServletOutputStream;
import java.io.*;

public class Response implements ServletResponse {

  private static final int BUFFER_SIZE = 1024;
  Request request;
  Writer output;
  PrintWriter writer;

  public Response(Writer  output) {
    this.output = output;
  }

  public void setRequest(Request request) {
    this.request = request;
  }




  /** implementation of ServletResponse  */
  public void flushBuffer() throws IOException {  }
  public int getBufferSize() {
    return 0;
  }
  public String getCharacterEncoding() {
    return null;
  }
  public Locale getLocale() {
    return null;
  }
  public ServletOutputStream getOutputStream() throws IOException {
    return null;
  }
  public PrintWriter getWriter() throws IOException {
    // autoflush is true, println() will flush,
    // but print() will not.
    writer = new PrintWriter(output, true);
    return writer;
  }
  public boolean isCommitted() {
    return false;
  }
  public void setCharacterEncoding(String str) { }
  public String getContentType(){
      return null;
  }
  public void reset() {  }
  public void resetBuffer() {  }
  public void setBufferSize(int size) {  }
  public void setContentLength(int length) {  }
  public void setContentType(String type) {  }
  public void setLocale(Locale locale) {  }
 
}

 


0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 18769184
What is the class loader supposed to do there?

BTW look at the source code of some existing open-source servlet containers:

http://tomcat.apache.org
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 18769195
>> Class cls = cl.loadClass("NewServlet.class");

Try without .class as:

Class cls = cl.loadClass ( "NewServlet: ) ;
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 18769196
I meant "NewServlet" ;-)
0
 

Author Comment

by:bjuneja_2000
ID: 18807928
That doesn't works either ..
0
 
LVL 30

Assisted Solution

by:mayankeagle
mayankeagle earned 166 total points
ID: 18813400
then the file path or name is incorrect
0
 
LVL 1

Expert Comment

by:Computer101
ID: 20143918
Forced accept.

Computer101
EE Admin
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now