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

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 .
bjuneja_2000Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mick BarryJava DeveloperCommented:
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
CEHJCommented:
What are you attempting to achieve by this?
0
bjuneja_2000Author Commented:
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
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Mick BarryJava DeveloperCommented:
Then you need to create your own ServletRequest and ServletResponse implementations.
0
CEHJCommented:
You probably should start with a simple web server and then integrate an existing servlet engine (which will be challenging enough)
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
bjuneja_2000Author Commented:
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
CEHJCommented:
You need to implement all the methods and read the spec
0
Mick BarryJava DeveloperCommented:
no, you just need to implement the interface methods
though you might want to implement HttpServletRequest instead of just ServletRequest (similiarly for response)
0
bjuneja_2000Author Commented:
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
Mayank SAssociate Director - Product EngineeringCommented:
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
Mayank SAssociate Director - Product EngineeringCommented:
>> Class cls = cl.loadClass("NewServlet.class");

Try without .class as:

Class cls = cl.loadClass ( "NewServlet: ) ;
0
Mayank SAssociate Director - Product EngineeringCommented:
I meant "NewServlet" ;-)
0
bjuneja_2000Author Commented:
That doesn't works either ..
0
Mayank SAssociate Director - Product EngineeringCommented:
then the file path or name is incorrect
0
Computer101Commented:
Forced accept.

Computer101
EE Admin
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.