⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 getgreetingcardservlet.java

📁 greetingcard是手机贺卡的制作软件。小程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package com.igm.ig3.greetingcard.servlet;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apic.ig3.common.CommonResponse;
import com.apic.ig3.common.DataConnect;
import com.apic.ig3.common.ErrorCode;
import com.apic.ig3.common.InitialCheck;
import com.apic.ig3.common.MobileFormat;
import com.apic.ig3.common.OutboundSMS;
import com.apic.ig3.common.SessionID;
import com.apic.ig3.common.TransactionLog;
import com.apic.ig3.db.Ig3DB_sp;
import com.apic.ig3.util.ApicUtil;
import com.apic.ig3.util.Ig3Config;
import com.igm.common.image.ImageEditor;
import com.igm.ig3.greetingcard.common.IGCConfig;
import com.igm.mdps.client.ProfilerClient;
import com.igm.mdps.profile.ColoriconProfile;
import com.igm.mdps.util.MdpsConst;

/**
 * A Main HTTP servlet that handle
 * Download of Greeting Cards
 *
 * @author	Tung
 *
 * @version 1.0.0
 */
public class GetGreetingCardServlet extends HttpServlet {
	
	
	/**
	 * String represent the class name
	 */
	private final static String CLASSNAME = "GetGreetingCardServlet";
	
	private static Ig3DB_sp ig3db_sp = null;
	
	public void init(ServletConfig config) 
	{
		try 
		{
			super.init(config);
			ig3db_sp = new Ig3DB_sp();
			ig3db_sp.Connect();
		} catch(Exception e) 
		{}
	}
	
	
    /**
     * Handles the HTTP GET requests from the client phone. 
     *
     * @param  request             Provides request information for HTTP 
     *                             servlets.
     * @param  response            Provides HTTP-specific functionality in 
     *                             sending a response.
     *
     * @throws ServletException    Defines a general exception a servlet can 
     *                             throw when it encounters difficulty.
     */	
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException 
	{
	    String session = "";
	    String rmtAddr = "";
	    String userAgent = "";
	    String mt = "";
	    
	    String id = "";
	    String jad = "";
	    String jar = "";
	    String hit = "";
	    
		try
		{
		    CommonResponse httpResponse = new CommonResponse(response, "text/vnd.wap.wml");

		    session = request.getParameter("S");
		    rmtAddr = request.getRemoteAddr();
		    userAgent = request.getHeader("User-Agent");
		    mt = "";

		    Hashtable table = null;
		    if((table = readSession(session, userAgent)) == null) 
		    {
		    	doLog("[GetGreetingCardServlet] - ["+session+"-"+rmtAddr+"-"+userAgent+"-"+mt+"] - No session");
		    	httpResponse.response(wmlResponse("Unable to locate your content."));
		    	return;
		    }

		    /**
		     * check mobile phone user agent and allowed wap ip
		     */
		    mt = (String)table.get("mt");
		    MobileFormat mobileFormat = new MobileFormat(mt);
		    if(!mobileFormat.validateUA(userAgent)) 
		    {
		    	httpResponse.response(wmlResponse("System error(99): please contact our customer service personal."));
		    	doLog("[GetGreetingCardServlet] - ["+session+"-"+rmtAddr+"-"+userAgent+"-"+mt+"] - invalid ua");
		    	return;
		    }
		    
		    if(!mobileFormat.validateWapIP(rmtAddr)) 
		    {
		    	httpResponse.response(wmlResponse("System error(999): please contact our customer service personal."));
		    	doLog("[GetGreetingCardServlet] - ["+session+"-"+rmtAddr+"-"+userAgent+"-"+mt+"] - invalid ip");
		    	return;
		    }

		    /**
		     * read the content type we should get for this phone
		     */
		    String igcType = getIGCType(userAgent);
		    if(igcType == null) 
		    {
		    	httpResponse.response(wmlResponse("System error(01): please contact our customer service personal."));
		    	doLog("[GetGreetingCardServlet] - ["+session+"-"+rmtAddr+"-"+userAgent+"-"+mt+"] - no igc type");
		    	return;
		    }
		    
		    /**
		     * init all jar/jad for different kar type
		     */
		    id = (String)table.get("uid");
		    if(igcType.equals("GCARD40")) 
		    {
		    	jad = IGCConfig.gcard40JadHome + igcType + ".jad";
		    	jar = IGCConfig.gcard40JarHome + igcType + ".jar";
		    } 
		    else if(igcType.equals("GCARD60")) 
		    {
		    	jad = IGCConfig.gcard60JadHome + igcType + ".jad";
		    	jar = IGCConfig.gcard60JarHome + igcType + ".jar";
		    } 
		    else 
		    {
		    	jad = IGCConfig.gcardJadHome + igcType + ".jad";
		    	jar = IGCConfig.gcardJarHome + igcType + ".jar";
		    }

		    /**
		     * deploy the correct jar/jad to download path
		     */
		    String deployedKey = null;
		    if((deployedKey = deployJar(table, session, jad, jar, userAgent)) == null) 
		    {
		    	httpResponse.response(wmlResponse("System error(02): please contact our customer service personal."));
		    	doLog("[GetGreetingCardServlet] - ["+session+"-"+rmtAddr+"-"+userAgent+"-"+mt+"] - jar failed to deploy:" + jar);
		    	return;
		    }

		    /**
		     * check how many time this link is hit, if it is
		     * the first time, we shd issue callback to caller
		     * and dedcut nick credit and do txn log
		     */
		    hit = (String)table.get("hit");
		    if(Integer.parseInt(hit) == 0) 
		    {
		    	if(!doCallback(table)) 
		    	{
		    		httpResponse.response(wmlResponse("System error(03): please contact our customer service personal."));
		    		clearOutput(deployedKey);
		    		doLog("[GetGreetingCardServlet] - ["+session+"-"+rmtAddr+"-"+userAgent+"-"+mt+"] - unable to docallback");
		    		return;
		    	}
		    	
		    	if(!logAction(table, id, igcType)) 
		    	{
		    		httpResponse.response(wmlResponse("System error(04): please contact our customer service personal."));
		    		clearOutput(deployedKey);
		    		doLog("[GetGreetingCardServlet] - ["+session+"-"+rmtAddr+"-"+userAgent+"-"+mt+"] - unable to log txn");
		    		return;
		    	}
		    }
		    
		    doLog("[GetGreetingCardServlet] - Update Hit");
		    updateHit(session, userAgent, deployedKey);
		    doLog("[GetGreetingCardServlet] - Update Hit Done");

		    doLog("[GetGreetingCardServlet]- ["+session+"-"+rmtAddr+"-"+userAgent+"-"+mt+"] - key:" + deployedKey);
		    doLog("[GetGreetingCardServlet] - Jad = n:/tmpupload/"+deployedKey+".jad");
		    
		    httpResponse.setMode("text/vnd.sun.j2me.app-descriptor");
		    httpResponse.response(readJad("n:/tmpupload/"+deployedKey+".jad"));
		}
		catch (Exception exception) 
		{
			StackTraceElement[] trace = exception.getStackTrace(); 

			for (int i=0; i < trace.length; i++) 
			{
				doLog(trace[i].toString());
			}  
		}
		
	}

	
    /**
     * Handles the HTTP POST requests from install-notification. 
     *
     * @param  request             Provides request information for HTTP 
     *                             servlets.
     * @param  response            Provides HTTP-specific functionality in 
     *                             sending a response.
     *
     * @throws ServletException    Defines a general exception a servlet can 
     *                             throw when it encounters difficulty.
     */	
	public void doPost(HttpServletRequest request,
                   HttpServletResponse response) throws ServletException 
    {
	    BufferedReader reader = null;
	    String result = "";
		String session = "";
		String rmtAddr = "";
		String userAgent = "";
		
		try
		{
		    session = request.getParameter("S");
		    rmtAddr = request.getRemoteAddr();
		    userAgent = request.getHeader("User-Agent");

		    Hashtable table = null;
		    if((table = readSession(session, userAgent)) == null)
		      return;

		    try 
		    {
		      reader = request.getReader();
		      result = reader.readLine();
		      reader.close();
		    } 
		    catch(Exception e) 
		    {}

		    doLog("[GetGreetingCardServlet]- ["+session+"-"+rmtAddr+"-"+userAgent+"-"+(String)table.get("mt")+"] - status:" + result);
		    
		    // if install successfully, remove all temporary file
		    if(result.startsWith("900")) 
		    {
		    	clearAll(table, session);
		    	doLog("[GetGreetingCardServlet]- ["+session+"-"+rmtAddr+"-"+userAgent+"-"+(String)table.get("mt")+"] - Delete Done");
		    }
		}
		catch (Exception exception)
		{
		}
    }
	
	/**
	 * Read previous created session file and put into hashtable
	 * @param session
	 * @param ua
	 * @return
	 */
	private Hashtable readSession(String session, String ua) 
	{
		FileInputStream fis = null;
		String fname = "";
		String previousUA = "";
		Properties p = null;
		Hashtable table = null;

		try 
		{
			fname = IGCConfig.tmpHome + session + IGCConfig.sessionExt;
		    fis = new FileInputStream(fname);
		    p = new Properties();
		    p.load(fis);
		    table = new Hashtable();
		    Enumeration e = p.propertyNames();
		    while(e.hasMoreElements()) 
		    {
		    	String key = (String)e.nextElement();
		    	String value = p.getProperty(key);
		    	table.put(key, value);
		    }
		    previousUA = (String)table.get("ua");
		    if(previousUA != null && !previousUA.equals(ua))
		    {
		    	return null;
		    }
		    return table;
		} 
		catch(Exception e) 
		{} 
		finally 
		{
			try { fis.close(); } catch(Exception e) {}
		}
		return null;
	}
	
	
	/**
	 * Return string of wml response message
	 * @param msg
	 * @return
	 */
	public static String wmlResponse(String msg) 
	{
		String str = 
			 "<?xml version=\"1.0\"?>" +
			 "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">" +
			 "<wml>" +
			 "<card id=\"iguana\" title=\"Message\">" +
			 "<p align=\"center\">" +
			 msg +
			 "</p>" +
			 "</card>" +
			 "</wml>";
		return str;
	}
	  

	/**
	 * Get type of greetingcard to be download based on UA
	 * @param userAgent
	 * @return
	 */  
	public static String getIGCType(String userAgent) 
	{
		FileInputStream fis = null;
		Properties p = null;
		String gcard40 = "";
		String gcard60 = "";
		String type = null;
		
		try 
		{
			fis = new FileInputStream(IGCConfig.gcardUAFile);
		    p = new Properties();
		    p.load(fis);
		    gcard40 = p.getProperty("GCARD40");
		    gcard60 = p.getProperty("GCARD60");
		    fis.close();
		    userAgent = userAgent.toLowerCase();
		    if(userAgent.matches(gcard40.toLowerCase()))
		    {
		    	type = "GCARD40";
		    }
		    else if(userAgent.matches(gcard60.toLowerCase()))
		    {
		    	type = "GCARD60";
		    }
		    else
		    {
		    	type = "GCARD";
		    }
		} 
		catch(Exception e) 
		{
		}
		return type;
	}

	  
	/**
	 * Get midi path based on midi ID
	 * @param sID
	 * @return
	 */
	private String getMidi(String sID)
	{
		String midiPath = null;
		String sHome = "";
		String ext = "";
		int poly_count = 4;
		int max_size = 0;
		
		try
		{
			sHome = Ig3Config.GetValue("SPMIDI_HOME");
			ext = ".mid";
			midiPath = sHome + "/" + sID + ext;
		}
		catch (Exception e) 
		{}
		return midiPath;
	}
	  
	
	/**
	 * Get img path based on id and UA
	 * @param sID
	 * @param sUA
	 * @param index
	 * @return
	 */
	private String getImage(String sID, String sUA, String index)
	{
		String outputFile = null;
		File profilerConfig = null;
		ProfilerClient pc = null;
		ColoriconProfile cp = null;
		
		String sHome = "";
		String ext = "";
		String icon_type = "application/octet-stream";
		
		int icon_height = 0;
		int icon_width = 0;
		int max_size = 0;
		double fRatio = 1l;
		double ratio_variation = 0;
		
		boolean isMRCIMG = true;
		
		try
		{
			//init the ProfilerClient
			doLog("[GetGreetingCardServlet] - Create Profiler Client");
			profilerConfig = new File (Ig3Config.GetValue("MDPS_CONFIG_FILE") );
			if (!profilerConfig.exists() || !profilerConfig.isFile() )
			{
				doLog("[GetGreetingCardServlet] - MDPS File Not Found");
				return null;
			}
			
			pc = new ProfilerClient(profilerConfig);
			doLog("[GetGreetingCardServlet] - Profiler Client Created");
			 	
			sHome = Ig3Config.GetValue("MRCIMG_HOME") + "/";
			ext = "." + ig3db_sp.getMRColorIconExt(Integer.parseInt(sID));
			doLog("[GetGreetingCardServlet] - Get ext : "+ext);	
			
			// if file not found on MRC, look on old COLIMG
			if (!new File(sHome+sID+ext).exists()) 
			{
				isMRCIMG = false;
				doLog("[GetGreetingCardServlet] - Detect id belong to normal colg");
				sHome = Ig3Config.GetValue("COLIMG_HOME") + "/";
				ext = ".gif";
			}
				
			doLog("[GetGreetingCardServlet] - Create ColoriconProfile");
			cp = (ColoriconProfile)pc.getColoriconProfile(sUA, MdpsConst.QUERY_UAGT);
			doLog("[GetGreetingCardServlet] - ColoriconProfile Created");
			
			if (ext.equals(".gif"))
			{
				icon_type = "image/gif";
			}
			else if (ext.equals(".jpg"))
			{
				icon_type = "image/jpeg";
			}
			else if (ext.equals(".png"))
			{
				icon_type = "image/png";
			}
				
			ratio_variation = Float.parseFloat(Ig3Config.GetValue("RATIO_VARIATION"));
			if (cp == null) 
			{
				doLog("[GetGreetingCardServlet] - Normal Size 128x128");
				icon_height = 128;
				icon_width = 128;
				max_size = 0;
			} 
			else 
			{
				icon_height = cp.getHeight();
				icon_width = cp.getWidth();
				max_size = cp.getMaxSize();
				doLog("[GetGreetingCardServlet] - CP Size "+icon_height+"x"+icon_width+".");
				
				doLog("[GetGreetingCardServlet] - Get nearest ratio");
				// get the nearest ratio
				double[] fRatios = ig3db_sp.getMRColorIconRatios(Integer.parseInt(sID));
				boolean bVarFound = false;
				for (int i =0; i < fRatios.length; i++) 
				{
					fRatio = fRatios[i];
					double variation = Math.abs(((double) icon_width / icon_height) - fRatios[i]);
					if (variation <= ratio_variation) 
					{
						bVarFound = true;
						break;
					}
				}
				
				if (!bVarFound) 
				{
					doLog("[GetGreetingCardServlet] - Ratio Not found. So back to 128x128");
					fRatio = 1f;
					icon_width = 128;
					icon_height = 128;
				}
			}
				
			// get crop points and width and height (x, y, w, h)
			doLog("[GetGreetingCardServlet] - Get Crop Info");
			int[] CropInfo = ig3db_sp.getMRColorIconCropInfo(Integer.parseInt(sID), fRatio-ratio_variation, fRatio+ratio_variation);
			if (CropInfo[2] == 0) 
			{
				CropInfo[2] = 128;
			}
			if (CropInfo[3] == 0)
			{
				CropInfo[3] = 128;
			}
			
			doLog("[GetGreetingCardServlet] - Start to Crop Image");

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -