Solved

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

Posted on 2007-03-21
17
1,079 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Automating Terraform w Jenkins & AWS CodeCommit

How to configure Jenkins and CodeCommit to allow users to easily create and destroy infrastructure using Terraform code.

 
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
 
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:Mayank S
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:Mayank S
ID: 18769195
>> Class cls = cl.loadClass("NewServlet.class");

Try without .class as:

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

Expert Comment

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

Author Comment

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

Assisted Solution

by:Mayank S
Mayank S 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

Stack Overflow Podcast - Frustrating Miracles

In this podcast, Stack Overflow interviewed Linux Academy CEO/Founder, Anthony James, and got his developer story!

"Follow your passion, be prepared to work hard and sacrifice, and, above all, don't let anyone limit your dreams."  - Donovan Bailey

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses

622 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