Blog - JServlet.com

To content | To menu | To search

web project

Entries feed - Comments feed

Wednesday 25 February 2009

Object MultiForm parse a multipart http request

Another parser for multipart http request that handle multipart/form-data request, object MutiForm accept multiple files and parameters in http request, fully compatible rfc1867, rfc2388 and API Servlet 2.4.

Object MultiForm is fast, robust and elegant to use :

- Use getMaxSize() method to set maximum size of http request

- Use getTempDirectory() method to set directory for temporary file

Example in servlet, upload a simple gif image :

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jservlet.servlet.multiform.MultiForm;
import com.jservlet.servlet.tool.BServlet;

public class UploadImage extends BServlet
{
 
     /**
      * Méthode appelée lorsque la requête est de type ENCTYPE="multipart/form-data" ...
      */
      public void doMultiForm(MultiForm _request, HttpServletResponse _res)
      throws ServletException, IOException
      {
           // do multiform...
          
        PrintWriter out = _res.getWriter();
   
        // errors...
        String err = "Upload OK !!!";
       
        // get data
        String nom = _request.getParameter("nom");
        String prenom = _request.getParameter("prenom");
       
        int age = -1;
        try { age = (new Integer(_request.getParameter("age")).intValue());}
        catch(Exception e) {}
       
        String photo = _request.getParameter("photo");
        photo = (photo==null) ? "" : photo;
   
        // get photo gif ...
        if (!photo.equals("") && _request.isFile("photo"))
        {
            MultiForm.File a_mf = _request.getFile("photo");
           
            // Test file size
            if (!a_mf.getName().equals("") && a_mf.length()>0)
            {
                if (a_mf.length()<=102400) // 1024 x 100 octets
                {
                    if (a_mf.isGif())  // test type file
                    {
                        // save image on disk           
                        try { a_mf.save("/tmp/photo.gif"); }
                        catch(Exception e) { out.println(e.toString()); }
                       
                    } else err = "Image is not Gif format!";
                } else err = "Image is too big! (100 ko max)";
            } else err = "Image is empty!";
        }
      

        //...
        out.write(err);

    }

   /**
    * Méthode pour indiquer quel répertoire utiliser pour les fichiers temporaires...
    */
    public String getTempDirectory() { return "/tmp/"; }

   /**
    * Méthode pour indiquer quelle est la taille maximale que peut avoir une requête.
    */
    public int getMaxSize() { return 5242880; } // 5 Mo maxi!
     
    /**
     * Méthode appelée lorsque la requête est de type Get.
     */
    public void doGet(HttpServletRequest _request, HttpServletResponse _res)
    throws ServletException, IOException
    {
        // do get...
    }
   
    /**
     * Méthode appelée lorsque la requète est de type Post.
     */
    public void doPost(HttpServletRequest _request, HttpServletResponse _res)
    throws ServletException, IOException
    {
        // do post...
    }
} // end of class


In JSP :

<%@ page import="java.util.*, com.jservlet.servlet.multiform.*" language="java"%>
<%

    // test request if appropriate...  
    MultiForm a_mf = null;
    if (MultiForm.isMultiForm(request))
    {
      String a_dir = "c:\\temp\\";     // dir temp...
      int a_maxSize = 5242880;         // max http request size...
     
      if (a_dir!=null) a_mf = (a_maxSize<0) ? new MultiForm(request,a_dir) : new MultiForm(request,a_dir,a_maxSize);    
      else a_mf = (a_maxSize<0) ? new MultiForm(request) : new MultiForm(request,a_maxSize);
    }

    // error ?
    String err = "Upload OK !!!";
       
    String photo = a_mf.getParameter("photo");
    photo = (photo==null) ? "" : photo;

    // get photo gif ...
    if (!photo.equals("") && a_mf.isFile("photo"))
    {
        MultiForm.File a_f = a_mf.getFile("photo");
       
        // Teste file
        if (!a_f.getName().equals("") && a_f.length()>0)
        {
            if (a_f.length()<=102400) // 1024 x 100 octets
            {
                if (a_f.isGif())  // gif format ?
                {
                    // ok save image on disk       
                    try { a_f.save("C:\\temp\\photo.gif"); }
                    catch(Exception e) { out.println(e.toString()); }
                   
                } else err = "Image is not Gif format!";
            } else err = "Image is too big! (100 ko max)";
        } else err = "Image is empty!";
    }
   

    //...
    out.write(err);
%>


Source : MultiForm.java

Sunday 14 October 2007

Mapping session servlet

Mapping & tracking session servlet :



Create abstract servlet BServletSession, all your servlet need to extend BServletSession for mapping specific component servlet session :

package com.jservlet.servlet.monitor;
[...]
public abstract class BServletSession extends HttpServlet
{

   /**
    * Override
method service for monitored object Session of specific User
    *
    * @exception ServletException  If a exception
    * @exception IOException       If a I/O exception
    */
    protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        // session
        HttpSession session = req.getSession();

        if (session !=null)
        {
            String ip_client = session.getAttribute("USER") + "@" + req.getRemoteHost() + " (" + req.getRemoteAddr() + ")";
            session.setAttribute("CLIENT_IDENTIFICATION", ip_client);

            // object singleton monitor session...
            MonitorSession.getInstance().monitorSession((String) session.getId(), session);

        }
      
        // call super service
        super.service(req, res);
    }
} //  end BServletSession...

Now you can see all objects in session (complet ip client come from User identification client, extends this servlet...), make introspection of specific object in session of servlet engine is now easy. See servlet monitor session and object monitor session for more details :

ServletMonitorSession.java
MonitorSession.java


Sunday 23 September 2007

Glue Java web engine servlet

Glue servlet engine, what is a glue web ?

Glue is a master servlet front end service that glue in parallel all resources coming from server group in cluster architecture.

Glue allow you to make fast and easily dynamic web site (in jsp/servlet, php, cgi or all that can be call by url), cobranding existing web application, make a bridge to web application or create simply your web portal, all that with the robustness of cluster architecture.

Glue accept http or https, interaction with Html form and cookie.

Use external Api HTTPClient Version 0.3-3 under LGPL V2.1
http://www.innovation.ch/java/HTTPClient/

See cluster architecture with Glue :

Call easily a component servlet engine in JSP :


<%@ page language="java" session="false" autoFlush="false" buffer="96kb" contentType="text/html;charset=iso-8859-1"%>
<%@ page extends="com.jservlet.servlet.JspUtils"%>
<%-- call internal method in jsp... --%>
<%@ include file="portefeuille_m.jsp" %>

<%-- Bean porperties, config client --%>
<jsp:useBean id="client_URL_PAGES" class="java.util.Properties" scope="application" />

<%
    // prepare to call component URL
    getCompPortefeuille(request, response, out, client_URL_PAGES, true, false);
%>

<div id="service">
    <script src="js/ptf.js"></script>
    <%=getCompPortefeuille(request, response, out, client_URL_PAGES, false, false)%>
</div>


Call method to servlet engine component URL (include jsp) :


<%@ page import="java.util.*"%>
<%@ page import="com.jservlet.stream.server.ComponentCallAsync" %>

<%!

    // Method getCompPortefeuille
    private String getCompPortefeuille(HttpServletRequest request, HttpServletResponse response, JspWriter out, Properties property, boolean bCallOnly, boolean bDebug)
    {
        // uri
        String urlAction = "?pageid=portefeuille";
       
        // url call ?
        String urlcall = (String) request.getParameter("urlcall");
        urlcall = (urlcall == null) ? "" : urlcall;
       
        String url            = property.getProperty("jportefeuille_client");           
        String urlServeur     = property.getProperty("jportefeuille");
       

        // hash others parameters
        Hashtable hash_param = getParametresStandard(request);
        hash_param.put("urlAction", urlAction);
        hash_param.put("urlcall", urlcall);
       
        // build final url
        String call_service = buildUrl(url, urlServeur, urlAction, hash_param);
       
        System.out.println("call_service : "+call_service);
        System.out.println("parametres : "+getParametresStandard(request));
              
        // objet call component           
        ComponentCallAsync comp = new ComponentCallAsync( call_service, "", request, response, out , false, false, true );
       
        // debug mode ?
        try { comp.setDebug(bDebug); }
        catch (Exception e) { }
       
        // get html
        if (!bCallOnly) return comp.getHTML();
        else return "";
    }
   
%>


Build easily web information system in JSP (master.jsp, menu.jsp, header.jsp, footer.jsp)  :


<%@ page language="java" %>
<%@ page session="false"%>
<%@ page import="java.util.*"%>
<%@ page autoFlush ="false" %>
<%@ page buffer = "96kb" %>

<%
    // détermine le type de sortie.
    response.setContentType("text/html;charset=iso-8859-1");

    // option pas de cache !
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
   
    // page jsp appelée
    String jspPage = (String) request.getAttribute("jspPage");
    jspPage = (jspPage == null) ? "main" : jspPage;
   
%>

<html>
<head>
    <title>My web portal</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <link rel="stylesheet" href="styles/client.css" type="text/css">
</head>

<body>

<table width="100%" border="1">
  <tr>
    <td colspan="2"><jsp:include page="header.jsp" /></td>
  </tr>
  <tr>
    <td width="10%" valign="top">
        <jsp:include page="menu.jsp" flush="false">
              <jsp:param name="jspPage" value="<%=jspPage%>"/>
        </jsp:include>
    </td>
    <td width="90%">
        <jsp:include page="<%= jspPage+".jsp" %>" flush="false">
            <jsp:param name="jspPage" value="<%=jspPage%>"/>
        </jsp:include>
    </td>
  </tr>
  <tr>
    <td colspan="2"><jsp:include page="footer.jsp" /></td>
  </tr>
</table>

</body>
</html>

Config client :

#
# Fichier global de description de la configuration du client
#

http_root=http://client.jservlet.com/

# url java & graph
java_url=http://blaster.jservlet.grp:83/
graph_url=http://blaster.jservlet.grp:84/

# local service
java_root=http://localhost:83/
graph_root=http://localhost:84/

# nom du client
service_client=client

# url portefeuille
jportefeuille=http://blaster.jservlet.grp:83/portefeuille
jportefeuille_client=http://blaster.jservlet.grp:83/portefeuille/PortefeuilleClient


Interested by my java Glue write me a comment...