`
hanyi366
  • 浏览: 291535 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

XmlHttpProxy

    博客分类:
  • Java
 
阅读更多
XmlHttpProxy


/* Copyright 2007 You may not modify, use, reproduce, or distribute this software except in compliance with the terms of the License at:
 http://developer.sun.com/berkeley_license.html
 $Id: XmlHttpProxy.java 2660 2008-10-29 14:40:28Z heiko.braun@jboss.com $
*/
package jmaki.xhp;

/* Copyright 2007 You may not modify, use, reproduce, or distribute this software except in compliance with the terms of the License at:
 http://developer.sun.com/berkeley_license.html
 $Id: XmlHttpProxy.java 2660 2008-10-29 14:40:28Z heiko.braun@jboss.com $
*/

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.logging.*;

import javax.xml.transform.*;
import javax.xml.transform.stream.*;

import org.json.*;

public class XmlHttpProxy {

   public static String GET = "GET";
   public static String POST = "POST";
   public static String DELETE = "DELETE";
   public static String PUT = "PUT";

   private String userName = null;
   private String password = null;
   private static Logger logger;
   private String proxyHost = "";
   int proxyPort = -1;
   private JSONObject config;
   private static String USAGE = "Usage:  -url service_URL  -id service_key [-url or -id required] -xslurl xsl_url [optional] -format json|xml [optional] -callback[optional] -config [optional] -resources base_directory_containing XSL stylesheets [optional]";

   public XmlHttpProxy() {}

   public XmlHttpProxy(String proxyHost, int proxyPort) {
      this.proxyHost = proxyHost;
      this.proxyPort = proxyPort;
   }

   public XmlHttpProxy(String proxyHost, int proxyPort,
                       String userName, String password) {
      this.proxyHost = proxyHost;
      this.proxyPort = proxyPort;
      this.userName = userName;
      this.password = password;
   }

   /**
    * This method will go out and make the call and it will apply an XSLT Transformation with the
    * set of parameters provided.
    *
    * @param urlString - The URL which you are looking up
    * @param out - The OutputStream to which the resulting document is written
    * @param xslInputStream - An input Stream to an XSL style sheet that is provided to the XSLT processor. If set to null there will be no transformation
    * @param  paramsMap - A Map of parameters that are feed to the XSLT Processor. These params may be used when generating content. This may be set to null if no parameters are necessary.
    * @param method - The HTTP method used.
    *
    */
   public void processRequest(String urlString,
                              OutputStream out,
                              InputStream xslInputStream,
                              Map paramsMap,
                              Map headers,
                              String method,
                              String userName,
                              String password) throws IOException, MalformedURLException {
      doProcess(urlString, out, xslInputStream, paramsMap, headers,method, null,null, userName,password);
   }
   /**
    * This method will go out and make the call and it will apply an XSLT Transformation with the
    * set of parameters provided.
    *
    * @param urlString - The URL which you are looking up
    * @param out - The OutputStream to which the resulting document is written
    *
    */
   public void doPost(String urlString,
                      OutputStream out,
                      InputStream xslInputStream,
                      Map paramsMap,
                      Map headers,
                      String postData,
                      String postContentType,
                      String userName,
                      String password) throws IOException, MalformedURLException {
      doProcess(urlString, out, xslInputStream, paramsMap, headers, XmlHttpProxy.POST, postData, postContentType, userName, password);
   }

   /**
    * This method will go out and make the call and it will apply an XSLT Transformation with the
    * set of parameters provided.
    *
    * @param urlString - The URL which you are looking up
    * @param out - The OutputStream to which the resulting document is written
    * @param xslInputStream - An input Stream to an XSL style sheet that is provided to the XSLT processor. If set to null there will be no transformation
    * @param paramsMap - A Map of parameters that are feed to the XSLT Processor. These params may be used when generating content. This may be set to null if no parameters are necessary.
    * @param method - the HTTP method used.
    * @param postData - A String of the bodyContent to be posted. A doPost will be used if this is parameter is not null.
    * @param postContentType - The request contentType used when posting data. Will not be set if this parameter is null.
    * @param userName - userName used for basic authorization
    * @param password - password used for basic authorization
    */
   public void doProcess(String urlString,
                         OutputStream out,
                         InputStream xslInputStream,
                         Map paramsMap,
                         Map headers,
                         String method,
                         String postData,
                         String postContentType,
                         String userName,
                         String password) throws IOException, MalformedURLException {
      
      if (paramsMap == null) {
         paramsMap = new HashMap();
      }

      String format = (String)paramsMap.get("format");
      if (format == null) {
         format = "xml";
      }

      InputStream in = null;
      BufferedOutputStream os = null;

      HttpClient httpclient = null;

      if (userName != null && password != null)
      {
         httpclient = new HttpClient(proxyHost, proxyPort, urlString, headers, method, userName, password);
      }
      else
      {
         httpclient = new HttpClient(proxyHost, proxyPort, urlString, headers, method);
      }

      // post data determines whether we are going to do a get or a post
      if (postData == null) {
         in = httpclient.getInputStream();
      } else {
         in = httpclient.doPost(postData, postContentType);
      }

      if(null==in)
      {
         throw new IOException("Failed to open input stream");   
      }

      // read the encoding from the incoming document and default to UTF-8
      // if an encoding is not provided
      String ce = httpclient.getContentEncoding();
      if (ce == null) {
         String ct = httpclient.getContentType();
         if (ct != null) {
            int idx = ct.lastIndexOf("charset=");
            if (idx >= 0) {
               ce = ct.substring(idx+8);
            } else {
               ce = "UTF-8";
            }
         } else {
            ce = "UTF-8";
         }
      }
      // get the content type
      String cType = null;
      // write out the content type
      //http://www.ietf.org/rfc/rfc4627.txt
      if (format.equals("json")) {
         cType = "application/json;charset="+ce;
      } else {
         cType = "text/xml;charset="+ce;
      }
      try {
         byte[] buffer = new byte[1024];
         int read = 0;
         if (xslInputStream == null) {
            while (true) {
               read = in.read(buffer);
               if (read <= 0) break;
               out.write(buffer, 0, read );
            }
         } else {
            transform(in, xslInputStream, paramsMap, out, ce);
         }
      } catch (Exception e) {
         getLogger().severe("XmlHttpProxy transformation error: " + e);
      } finally {
         try {
            if (in != null) {
               in.close();
            }
            if (out != null) {
               out.flush();
               out.close();
            }
         } catch (Exception e) {
            // do nothing
         }
      }
   }

   /**
    * Do the XSLT transformation
    */
   public void transform( InputStream xmlIS,
                          InputStream xslIS,
                          Map params,
                          OutputStream result,
                          String encoding) {
      try {
         TransformerFactory trFac = TransformerFactory.newInstance();
         Transformer transformer = trFac.newTransformer(new StreamSource(xslIS));
         Iterator it = params.keySet().iterator();
         while (it.hasNext()) {
            String key = (String)it.next();
            transformer.setParameter(key, (String)params.get(key));
         }
         transformer.setOutputProperty("encoding", encoding);
         transformer.transform(new StreamSource(xmlIS), new StreamResult(result));
      } catch (Exception e) {
         getLogger().severe("XmlHttpProxy: Exception with xslt " + e);
      }
   }

   /**
    *
    * CLI to the XmlHttpProxy
    */
   public static void main(String[] args)
     throws IOException, MalformedURLException {

      getLogger().info("XmlHttpProxy 1.8");
      XmlHttpProxy xhp = new XmlHttpProxy();

      if (args.length == 0) {
         System.out.println(USAGE);
      }

      String method = XmlHttpProxy.GET;
      InputStream xslInputStream = null;
      String serviceKey = null;
      String urlString = null;
      String xslURLString = null;
      String format = "xml";
      String callback = null;
      String urlParams = null;
      String configURLString = "xhp.json";
      String resourceBase = "file:src/conf/META-INF/resources/xsl/";
      String username = null;
      String password = null;

      // read in the arguments
      int index = 0;
      while (index < args.length) {
         if (args[index].toLowerCase().equals("-url") && index + 1 < args.length) {
            urlString = args[++index];
         } else if (args[index].toLowerCase().equals("-key") && index + 1 < args.length) {
            serviceKey = args[++index];
         } else if (args[index].toLowerCase().equals("-id") && index + 1 < args.length) {
            serviceKey = args[++index];
         } else if (args[index].toLowerCase().equals("-callback") && index + 1 < args.length) {
            callback = args[++index];
         }  else if (args[index].toLowerCase().equals("-xslurl") && index + 1 < args.length) {
            xslURLString = args[++index];
         } else if (args[index].toLowerCase().equals("-method") && index + 1 < args.length) {
            method = args[++index];
         } else if (args[index].toLowerCase().equals("-username") && index + 1 < args.length) {
            username = args[++index];
         } else if (args[index].toLowerCase().equals("-password") && index + 1 < args.length) {
            password = args[++index];
         } else if (args[index].toLowerCase().equals("-urlparams") && index + 1 < args.length) {
            urlParams = args[++index];
         } else if (args[index].toLowerCase().equals("-config") && index + 1 < args.length) {
            configURLString = args[++index];
         } else if (args[index].toLowerCase().equals("-resources") && index + 1 < args.length) {
            resourceBase = args[++index];
         }
         index++;
      }

      if (serviceKey != null) {
         try {
            InputStream is = (new URL(configURLString)).openStream();
            JSONObject services = loadServices(is);
            JSONObject service = services.getJSONObject(serviceKey);
            // default to the service default if no url parameters are specified
            if (urlParams == null && service.has("defaultURLParams")) {
               urlParams = service.getString("defaultURLParams");
            }
            String serviceURL = service.getString("url");
            // build the URL properly
            if (urlParams != null && serviceURL.indexOf("?") == -1){
               serviceURL += "?";
            } else if (urlParams != null){
               serviceURL += "&";
            }
            String apiKey = "";
            if (service.has("apikey")) apiKey = service.getString("apikey");
            urlString = serviceURL + apiKey +  "&" + urlParams;
            if (service.has("xslStyleSheet")) {
               xslURLString = service.getString("xslStyleSheet");
               // check if the url is correct of if to load from the classpath

            }
         } catch (Exception ex) {
            getLogger().severe("XmlHttpProxy Error loading service: " + ex);
            System.exit(1);
         }
      } else if (urlString == null) {
         System.out.println(USAGE);
         System.exit(1);
      }
      // The parameters are feed to the XSL Stylsheet during transformation.
      // These parameters can provided data or conditional information.
      Map paramsMap = new HashMap();
      if (format != null) {
         paramsMap.put("format", format);
      }
      if (callback != null) {
         paramsMap.put("callback", callback);
      }

      if (xslURLString != null) {
         URL xslURL = new URL(xslURLString);
         if (xslURL != null) {
            xslInputStream  = xslURL.openStream();
         } else {
            getLogger().severe("Error: Unable to locate XSL at URL " + xslURLString);
         }
      }
      xhp.processRequest(urlString, System.out, xslInputStream, paramsMap, null, method, username, password);
   }

   public static Logger getLogger() {
      if (logger == null) {
         logger = Logger.getLogger("jmaki.xhp.Log");
      }
      return logger;
   }

   public static JSONObject loadServices(InputStream is)
   {
      JSONObject config = null;
      JSONObject services = new JSONObject();
      try
      {
         config = loadJSONObject(is).getJSONObject("xhp");
         JSONArray sA = config.getJSONArray("services");
         for (int l=0; l < sA.length(); l++) {
            JSONObject value = sA.getJSONObject(l);
            String key = value.getString("id");
            services.put(key,value);
         }
      }
      catch (Exception ex)
      {
         getLogger().severe("XmlHttpProxy error loading services." + ex);
      }
      return services;
   }

   public static JSONObject loadJSONObject(InputStream in) {
      ByteArrayOutputStream out = null;
      try {
         byte[] buffer = new byte[1024];
         int read = 0;
         out = new ByteArrayOutputStream();
         while (true) {
            read = in.read(buffer);
            if (read <= 0) break;
            out.write(buffer, 0, read );
         }
         return new JSONObject(out.toString());
      } catch (Exception e) {
         getLogger().severe("XmlHttpProxy error reading in json "  + e);
      } finally {
         try {
            if (in != null) {
               in.close();
            }
            if (out != null) {
               out.flush();
               out.close();
            }
         } catch (Exception e) {
         }
      }
      return null;
   }
}





XmlHttpProxyServlet



/* Copyright 2007 You may not modify, use, reproduce, or distribute this software except in compliance with the terms of the License at:
 http://developer.sun.com/berkeley_license.html
 $Id: XmlHttpProxyServlet.java 2660 2008-10-29 14:40:28Z heiko.braun@jboss.com $
*/
package jmaki.xhp;

import java.io.*;
import java.util.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.json.*;

/**  XmlHttpProxyServlet
 *   @author Greg Murray
 */
public class XmlHttpProxyServlet extends HttpServlet
{

   public static String REMOTE_USER = "REMOTE_USER";

   private static String XHP_LAST_MODIFIED = "xhp_last_modified_key";
   private static String XHP_CONFIG = "xhp.json";

   private static boolean allowXDomain = false;
   private static boolean requireSession = false;
   private static boolean createSession = false;
   private static String responseContentType = "application/json;charset=UTF-8";
   private static boolean rDebug = false;
   private Logger logger = null;
   private XmlHttpProxy xhp = null;
   private ServletContext ctx;
   private JSONObject services = null;
   private String resourcesDir = "/resources/";
   private String classpathResourcesDir = "/META-INF/resources/";
   private String headerToken = "jmaki-";
   private String testToken = "xtest-";
   
   public XmlHttpProxyServlet() {
      if (rDebug) {
         logger = getLogger();
      }
   }

   public void init(ServletConfig config) throws ServletException {
      super.init(config);
      ctx = config.getServletContext();
      // set the response content type
      if (ctx.getInitParameter("responseContentType") != null) {
         responseContentType = ctx.getInitParameter("responseContentType");
      }
      // allow for resources dir over-ride at the xhp level otherwise allow
      // for the jmaki level resources
      if (ctx.getInitParameter("jmaki-xhp-resources") != null) {
         resourcesDir = ctx.getInitParameter("jmaki-xhp-resources");
      } else if (ctx.getInitParameter("jmaki-resources") != null) {
         resourcesDir = ctx.getInitParameter("jmaki-resources");
      }
      // allow for resources dir over-ride
      if (ctx.getInitParameter("jmaki-classpath-resources") != null) {
         classpathResourcesDir = ctx.getInitParameter("jmaki-classpath-resources");
      }
      String requireSessionString = ctx.getInitParameter("requireSession");
      if (requireSessionString == null) requireSessionString = ctx.getInitParameter("jmaki-requireSession");
      if (requireSessionString != null) {
         if ("false".equals(requireSessionString)) {
            requireSession = false;
            getLogger().severe("XmlHttpProxyServlet: intialization. Session requirement disabled.");
         } else if ("true".equals(requireSessionString)) {
            requireSession = true;
            getLogger().severe("XmlHttpProxyServlet: intialization. Session requirement enabled.");
         }
      }
      String xdomainString = ctx.getInitParameter("allowXDomain");
      if (xdomainString == null) xdomainString = ctx.getInitParameter("jmaki-allowXDomain");
      if (xdomainString != null) {
         if ("true".equals(xdomainString)) {
            allowXDomain = true;
            getLogger().severe("XmlHttpProxyServlet: intialization. xDomain access is enabled.");
         } else if ("false".equals(xdomainString)) {
            allowXDomain = false;
            getLogger().severe("XmlHttpProxyServlet: intialization. xDomain access is disabled.");
         }
      }
      String createSessionString = ctx.getInitParameter("jmaki-createSession");
      if (createSessionString != null) {
         if ("true".equals(createSessionString)) {
            createSession = true;
            getLogger().severe("XmlHttpProxyServlet: intialization. create session is enabled.");
         } else if ("false".equals(xdomainString)) {
            createSession = false;
            getLogger().severe("XmlHttpProxyServlet: intialization. create session is disabled.");
         }
      }
      // if there is a proxyHost and proxyPort specified create an HttpClient with the proxy
      String proxyHost = ctx.getInitParameter("proxyHost");
      String proxyPortString = ctx.getInitParameter("proxyPort");
      if (proxyHost != null && proxyPortString != null) {
         int proxyPort = 8080;
         try {
            proxyPort= new Integer(proxyPortString).intValue();
            xhp = new XmlHttpProxy(proxyHost, proxyPort);
         } catch (NumberFormatException nfe) {
            getLogger().severe("XmlHttpProxyServlet: intialization error. The proxyPort must be a number");
            throw new ServletException("XmlHttpProxyServlet: intialization error. The proxyPort must be a number");
         }
      } else {
         xhp = new XmlHttpProxy();
      }
   }

   private void getServices(HttpServletResponse res)
   {
      InputStream is = null;
      try
      {
         URL url = ctx.getResource(resourcesDir + XHP_CONFIG);
         // use classpath if not found locally.
         //if (url == null) url = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + XHP_CONFIG);
         if (url == null) url = XmlHttpProxyServlet.class.getResource(XHP_CONFIG);  // same package
         is = url.openStream();
      }
      catch (Exception ex)
      {
         try
         {
            getLogger().severe("XmlHttpProxyServlet error loading xhp.json : " + ex);
            PrintWriter writer = res.getWriter();
            writer.write("XmlHttpProxyServlet Error: Error loading xhp.json. Make sure it is available in the /resources directory of your applicaton.");
            writer.flush();
         }
         catch (Exception iox) {}
      }
      services = xhp.loadServices(is);
   }

   public void doDelete(HttpServletRequest req, HttpServletResponse res) {
      doProcess(req,res, XmlHttpProxy.DELETE);
   }

   public void doGet(HttpServletRequest req, HttpServletResponse res) {
      doProcess(req,res, XmlHttpProxy.GET);
   }

   public void doPost(HttpServletRequest req, HttpServletResponse res) {
      doProcess(req,res, XmlHttpProxy.POST);
   }

   public void doPut(HttpServletRequest req, HttpServletResponse res) {
      doProcess(req,res, XmlHttpProxy.PUT);
   }

   public void doProcess(HttpServletRequest req, HttpServletResponse res, String method)
   {

      boolean isPost = XmlHttpProxy.POST.equals(method);
      StringBuffer bodyContent = null;
      OutputStream out = null;
      PrintWriter writer = null;
      String serviceKey = null;
      try {
        BufferedReader in = req.getReader();
        String line = null;
        while ((line = in.readLine()) != null) {
           if (bodyContent == null) bodyContent = new StringBuffer();
           bodyContent.append(line);
        }
     } catch (Exception e) {
     } 

      try
      {
         HttpSession session = null;
         // it really does not make sense to use create session with require session as
         // the create session will always result in a session created and the requireSession
         // will always succeed. Leaving the logic for now.
         if (createSession) {
            session = req.getSession(true);
         }
         if (requireSession) {
            // check to see if there was a session created for this request
            // if not assume it was from another domain and blow up
            // Wrap this to prevent Portlet exeptions
            session = req.getSession(false);
            if (session == null) {
               res.setStatus(HttpServletResponse.SC_FORBIDDEN);
               return;
            }
         }
         serviceKey = req.getParameter("id");
         // only to preven regressions - Remove before 1.0
         if (serviceKey == null) serviceKey = req.getParameter("key");
         // check if the services have been loaded or if they need to be reloaded
         if (services == null || configUpdated()) {
            getServices(res);
         }
         String urlString = null;
         String xslURLString = null;
         String userName = null;
         String password = null;
         String format = "json";
         String callback = req.getParameter("callback");
         String urlParams = req.getParameter("urlparams");
         String countString = req.getParameter("count");
         boolean passthrough = false;
         // encode the url to prevent spaces from being passed along
         if (urlParams != null) {
            urlParams = urlParams.replace(' ', '+');
         }
         // get the headers to pass through
         Map headers = null;
         // Forward all request headers starting with the header token jmaki-
         // and chop off the jmaki-
         Enumeration hnum = req.getHeaderNames();

         // test hack

         while (hnum.hasMoreElements()) {
            String name = (String)hnum.nextElement();
            if (name.startsWith(headerToken))
            {
               if (headers == null) headers = new HashMap();

               String value = "";
               // handle multi-value headers
               Enumeration vnum = req.getHeaders(name);
               while (vnum.hasMoreElements()) {
                  value += (String)vnum.nextElement();
                  if (vnum.hasMoreElements()) value += ";";
               }
               String sname = name.substring(headerToken.length(), name.length());
               headers.put(sname,value);
            }
            else if(name.startsWith(testToken))
            {
               // hack test capabilities for authentication
               if("xtest-user".equals(name)) userName = req.getHeader("xtest-user");
               if("xtest-pass".equals(name)) password = req.getHeader("xtest-pass");
            }
         }
         try
         {
            String actualServiceKey = serviceKey != null ? serviceKey : "default";
            if (services.has(actualServiceKey))
            {
               JSONObject service = services.getJSONObject(actualServiceKey);
               String serviceURL = service.getString("url");
               if(null==serviceURL)
                  throw new IllegalArgumentException("xhp.json: service url is mising");

               if (service.has("passthrough")) passthrough =
                     Boolean.valueOf(service.getString("passthrough"));

               if (service.has("username")) userName = service.getString("username");
               if (service.has("password")) password = service.getString("password");

               String apikey = "";
               if (service.has("apikey")) apikey = service.getString("apikey");
               if (service.has("xslStyleSheet")) xslURLString = service.getString("xslStyleSheet");

               // default to the service default if no url parameters are specified
               if(!passthrough)
               {
                  if (urlParams == null && service.has("defaultURLParams")) {
                     urlParams = service.getString("defaultURLParams");
                  }

                  // build the URL
                  if (urlParams != null && serviceURL.indexOf("?") == -1){
                     serviceURL += "?";
                  } else  if (urlParams != null) {
                     serviceURL += "&";
                  }

                  urlString = serviceURL + apikey;
                  if (urlParams != null) urlString += "&" + urlParams;
               }

               if(passthrough)
               {
                  // override service url and url params
                  String path = req.getPathInfo();
                  path = path.substring(path.indexOf("xhp/")+3, path.length());

                  urlString = serviceURL + path + "?" + req.getQueryString();
               }
            }
            else
            {
               writer = res.getWriter();
               if (serviceKey == null) writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
               else writer.write("XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
               writer.flush();
               return;
            }
         }
         catch (Exception ex)
         {
            getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
            res.setStatus(500);
         }

         Map paramsMap = new HashMap();
         paramsMap.put("format", format);
         // do not allow for xdomain unless the context level setting is enabled.
         if (callback != null && allowXDomain) {
            paramsMap.put("callback", callback);
         }
         if (countString != null) {
            paramsMap.put("count", countString);
         }

         InputStream xslInputStream = null;

         if (urlString == null) {
            writer = res.getWriter();
            writer.write("XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
            writer.flush();
            return;
         }
         // support for session properties and also authentication name
         if (urlString.indexOf("${") != -1) {
            urlString = processURL(urlString, req, res);
         }
         // default to JSON
         res.setContentType(responseContentType);
         out = res.getOutputStream();
         // get the stream for the xsl stylesheet
         if (xslURLString != null) {
            // check the web root for the resource
            URL xslURL = null;
            xslURL = ctx.getResource(resourcesDir + "xsl/"+ xslURLString);
            // if not in the web root check the classpath
            if (xslURL == null) {
               xslURL = XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
            }
            if (xslURL != null) {
               xslInputStream  = xslURL.openStream();
            } else {
               String message = "Could not locate the XSL stylesheet provided for service id " +  serviceKey + ". Please check the XMLHttpProxy configuration.";
               getLogger().severe(message);
               res.setStatus(500);
               try {
                  out.write(message.getBytes());
                  out.flush();
                  return;
               } catch (java.io.IOException iox){
               }
            }
         }

         if (!isPost)
         {
            xhp.processRequest(urlString, out, xslInputStream, paramsMap, headers, method, userName, password);
         }
         else
         {
            final String content = bodyContent != null ? bodyContent.toString() : "";
            if (bodyContent == null)
               getLogger().info("XmlHttpProxyServlet attempting to post to url " + urlString + " with no body content");
            xhp.doPost(urlString, out, xslInputStream, paramsMap, headers, content, req.getContentType(), userName, password);
         }
      }
      catch (Exception iox)
      {
         iox.printStackTrace();
         getLogger().severe("XmlHttpProxyServlet: caught " + iox);
         res.setStatus(500);
         /*try {
            writer = res.getWriter();
            writer.write("XmlHttpProxyServlet error loading service for " + serviceKey + " . Please notify the administrator.");
            writer.flush();
         } catch (java.io.IOException ix) {
            ix.printStackTrace();
         }*/
         return;
      }
      finally
      {
         try
         {
            if (out != null) out.close();
            if (writer != null) writer.close();
         } catch (java.io.IOException iox){}
      }
   }

   /* Allow for a EL style replacements in the serviceURL
    *
    * The constant REMOTE_USER will replace the contents of ${REMOTE_USER}
    * with the return value of request.getRemoteUserver() if it is not null
    * otherwise the ${REMOTE_USER} is replaced with a blank.
    *
    * If you use ${session.somekey} the ${session.somekey} will be replaced with
    * the String value of the session varialble somekey or blank if the session key
    * does not exist.
    *
   */
   private String processURL(String url, HttpServletRequest req, HttpServletResponse res) {
      String serviceURL = url;
      int start = url.indexOf("${");
      int end = url.indexOf("}", start);
      if (end != -1) {
         String prop = url.substring(start + 2, end).trim();
         // no matter what we will remove the ${}
         // default to blank like the JSP EL
         String replace = "";
         if (REMOTE_USER.equals(prop)) {
            if (req.getRemoteUser() != null) replace = req.getRemoteUser();
         }
         if (prop.toLowerCase().startsWith("session.")) {
            String sessionKey = prop.substring("session.".length(), prop.length());
            if (req.getSession().getAttribute(sessionKey) != null) {
               // force to a string
               replace = req.getSession().getAttribute(sessionKey).toString();
            }
         }
         serviceURL = serviceURL.substring(0, start) +
               replace +
               serviceURL.substring(end + 1, serviceURL.length());
      }
      // call recursively to process more than one instance of a ${ in the serviceURL
      if (serviceURL.indexOf("${") != -1) serviceURL = processURL(serviceURL, req, res);
      return serviceURL;
   }

   /**
    * Check to see if the configuration file has been updated so that it may be reloaded.
    */
   private boolean configUpdated() {
      try {
         URL url = ctx.getResource(resourcesDir + XHP_CONFIG);
         URLConnection con;
         if (url == null) return false ;
         con = url.openConnection();
         long lastModified = con.getLastModified();
         long XHP_LAST_MODIFIEDModified = 0;
         if (ctx.getAttribute(XHP_LAST_MODIFIED) != null) {
            XHP_LAST_MODIFIEDModified = ((Long)ctx.getAttribute(XHP_LAST_MODIFIED)).longValue();
         } else {
            ctx.setAttribute(XHP_LAST_MODIFIED, new Long(lastModified));
            return false;
         }
         if (XHP_LAST_MODIFIEDModified < lastModified) {
            ctx.setAttribute(XHP_LAST_MODIFIED, new Long(lastModified));
            return true;
         }
      } catch (Exception ex) {
         getLogger().severe("XmlHttpProxyServlet error checking configuration: " + ex);
      }
      return false;
   }

   public Logger getLogger() {
      if (logger == null) {
         logger = Logger.getLogger("jmaki.services.xhp.Log");
      }
      return logger;
   }

   private void logMessage(String message) {
      if (rDebug) {
         getLogger().info(message);
      }
   }
}




HttpClient


/* Copyright 2006-2008 Sun Microsystems, Inc.  All rights reserved.  You may not modify, use, reproduce, or distribute this software except in compliance with the terms of the License at:
 http://developer.sun.com/berkeley_license.html
 $Id: HttpClient.java 2631 2008-10-27 17:25:05Z heiko.braun@jboss.com $
*/package jmaki.xhp;

import java.io.*;
import java.util.Map;
import java.util.Iterator;
import java.net.*;
import java.util.logging.*;
import java.security.Security;

/**
 * @author Yutaka Yoshida, Greg Murray
 *
 * Minimum set of HTTPclient supporting both http and https.
 * It's aslo capable of POST, but it doesn't provide doGet because
 * the caller can just read the inputstream.
 */
public class HttpClient {

   private static Logger logger;
   private String proxyHost = null;
   private int proxyPort = -1;
   private boolean isHttps = false;
   private boolean isProxy = false;
   private HttpURLConnection urlConnection = null;
   private Map headers;

   /**
    * @param phost PROXY host name
    * @param pport PROXY port string
    * @param url URL string
    * @param headers Map
    */
   public HttpClient(
         String phost,
         int pport,
         String url,
         Map headers,
         String method)
         throws MalformedURLException
   {
      if (phost != null && pport != -1)
      {
         this.isProxy = true;
      }

      this.proxyHost = phost;
      this.proxyPort = pport;

      if (url.trim().startsWith("https:")) {
         isHttps = true;
      }

      this.urlConnection = getURLConnection(url);
      try {
         this.urlConnection.setRequestMethod(method);
      } catch (java.net.ProtocolException pe) {
         HttpClient.getLogger().severe("Unable protocol method to " + method + " : " + pe);
      }
      this.headers = headers;
      // seat headers
      if (headers != null) {
         Iterator it = headers.keySet().iterator();
         if (it != null) {
            while (it.hasNext()) {
               String key = (String)it.next();
               String value = (String)headers.get(key);
               this.urlConnection.setRequestProperty (key, value);
            }
         }
      }
   }

   /**
    * @param phost PROXY host name
    * @param pport PROXY port string
    * @param url URL string
    * @param headers Map
    * @param userName string
    * @param password string
    */
   public HttpClient(String phost,
                     int pport,
                     String url,
                     Map headers,
                     String method,
                     String userName,
                     String password)
         throws MalformedURLException {
      try
      {
         if (phost != null && pport != -1) {
            this.isProxy = true;
         }

         this.proxyHost = phost;
         this.proxyPort = pport;
         if (url.trim().startsWith("https:")) {
            isHttps = true;
         }
         this.urlConnection = getURLConnection(url);
         try {
            this.urlConnection.setRequestMethod(method);
         } catch (java.net.ProtocolException pe) {
            HttpClient.getLogger().severe("Unable protocol method to " + method + " : " + pe);
         }
         // set basic authentication information
         String auth = userName + ":" +  password;
         String encoded = new sun.misc.BASE64Encoder().encode (auth.getBytes());
         // set basic authorization
         this.urlConnection.setRequestProperty ("Authorization", "Basic " + encoded);
         this.headers = headers;
         // seat headers
         if (headers != null) {
            Iterator it = headers.entrySet().iterator();
            if (it != null) {
               while (it.hasNext()) {
                  String key = (String)it.next();
                  String value = (String)headers.get(key);
                  this.urlConnection.setRequestProperty (key, value);
               }
            }
         }
      } catch (Exception ex) {
         HttpClient.getLogger().severe("Unable to set basic authorization for " + userName  + " : " +ex);
      }
   }

   /**
    * private method to get the URLConnection
    * @param str URL string
    */
   private HttpURLConnection getURLConnection(String str)
         throws MalformedURLException {
      try {

         if (isHttps) {
            /* when communicating with the server which has unsigned or invalid
            * certificate (https), SSLException or IOException is thrown.
            * the following line is a hack to avoid that
            */
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
            if (isProxy) {
               System.setProperty("https.proxyHost", proxyHost);
               System.setProperty("https.proxyPort", proxyPort + "");
            }
         }
         else
         {
            if (isProxy)
            {
               System.setProperty("http.proxyHost", proxyHost);
               System.setProperty("http.proxyPort", proxyPort  + "");
            }
         }

         URL url = new URL(str);
         HttpURLConnection uc = (HttpURLConnection)url.openConnection();
         // if this header has not been set by a request set the user agent.
         if (headers == null ||
               (headers != null &&  headers.get("user-agent") == null)) {
            // set user agent to mimic a common browser
            String ua="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)";
            uc.setRequestProperty("user-agent", ua);
         }
         return uc;
      }
      catch (MalformedURLException me)
      {
         throw new MalformedURLException(str + " is not a valid URL");
      }
      catch (Exception e)
      {
         throw new RuntimeException("Unknown error creating UrlConnection: " + e);
      }
   }

   /**
    * returns the inputstream from URLConnection
    * @return InputStream
    */
   public InputStream getInputStream() {
      try
      {
         // logger doesnt work, because it writes to stderr,
         // which causes GwtTest to interpret it as failure
         System.out.println(
               this.urlConnection.getRequestMethod()+ " " +
                     this.urlConnection.getURL() +": "+
                     this.urlConnection.getResponseCode()
         );
         return (this.urlConnection.getInputStream());
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      }
   }

   /**
    * return the OutputStream from URLConnection
    * @return OutputStream
    */
   public OutputStream getOutputStream() {

      try {
         return (this.urlConnection.getOutputStream());
      } catch (Exception e) {
         e.printStackTrace();
         return null;
      }
   }

   /**
    * posts data to the inputstream and returns the InputStream.
    * @param postData data to be posted. must be url-encoded already.
    * @param contentType allows you to set the contentType of the request.
    * @return InputStream input stream from URLConnection
    */
   public InputStream doPost(String postData, String contentType) {
      this.urlConnection.setDoOutput(true);
      if (contentType != null) this.urlConnection.setRequestProperty( "Content-type", contentType );

      OutputStream os = this.getOutputStream();
      PrintStream ps = new PrintStream(os);
      ps.print(postData);
      ps.close();
      return (this.getInputStream());
   }

   public String getContentEncoding() {
      if (this.urlConnection == null) return null;
      return (this.urlConnection.getContentEncoding());
   }
   public int getContentLength() {
      if (this.urlConnection == null) return -1;
      return (this.urlConnection.getContentLength());
   }
   public String getContentType() {
      if (this.urlConnection == null) return null;
      return (this.urlConnection.getContentType());
   }
   public long getDate() {
      if (this.urlConnection == null) return -1;
      return (this.urlConnection.getDate());
   }
   public String getHeader(String name) {
      if (this.urlConnection == null) return null;
      return (this.urlConnection.getHeaderField(name));
   }
   public long getIfModifiedSince() {
      if (this.urlConnection == null) return -1;
      return (this.urlConnection.getIfModifiedSince());
   }

   public static Logger getLogger() {
      if (logger == null) {
         logger = Logger.getLogger("jmaki.xhp.Log");
      }
      return logger;
   }
}



分享到:
评论

相关推荐

    2025最新空调与制冷作业(运行操作)考试题库及答案.docx

    2025最新空调与制冷作业(运行操作)考试题库及答案.docx

    无监督视频对象分割领域的跨模态与帧间注意力机制研究及其应用

    内容概要:本文提出了一种新的无监督视频对象分割(unsupervised VOS)方法——双原型注意力机制(Dual Prototype Attention),即IMA(跨模态注意模块)和IFA(帧间注意模块)。这些机制分别解决了现有多模态融合和时间聚集方法中存在的鲁棒性和计算效率等问题,显著提高了在多个公开基准数据集上的表现。此外,论文还探讨了原型嵌入对性能的影响并对其进行了验证。 适合人群:对视频处理特别是无监督视频对象分割领域感兴趣的计算机视觉研究员和技术开发者。 使用场景及目标:适用于各种需要进行高质量自动图像或视频内容分析的应用环境,如智能监控、增强现实、自动驾驶等领域。具体的目标是提高模型识别最突出物体时的精度以及稳定性,即使遇到遮挡或者复杂背景也能有效运作。 阅读建议:本篇文献提供了详尽的技术细节和支持性实验结果来展示所提出的DPA方法优越之处。因此,在理解和评估该研究成果的基础上可以深入了解如何利用注意力机制提升深度学习模型的效果,尤其是对于涉及时间和空间维度的数据处理任务非常有价值。

    Gartner发布2025年网络治理、风险与合规战略路线图

    新型网络风险和合规义务,日益成为网络治理、风险与合规实践面临的问题。安全和风险管理领导者可以参考本文,实现从被动、专注于合规的方法到主动、进一步自动化方法的转型。 主要发现 不断变化的监管环境和不断扩大的攻击面,使企业机构难以实现网络治理、风险与合规(GRC)与其整体风险管理战略的协调,因此必须推动GRC进行战略性转变。然而,许多安全和风险管理(SRM)领导者难以适应这些变化。 重心在满足监管要求的话,通常会导致被动的网络风险管理和评估方式。因此,网络安全团队与业务部门之间的接触和协作通常较低。 许多网络GRC管理流程缺乏充分且相关的技术自动化,导致资源紧张和控制测试疲劳。

    基于java+ssm+mysql的数据库系统原理课程平台 源码+数据库+论文(高分毕设项目).zip

    项目已获导师指导并通过的高分毕业设计项目,可作为课程设计和期末大作业,下载即用无需修改,项目完整确保可以运行。 包含:项目源码、数据库脚本、软件工具等,该项目可以作为毕设、课程设计使用,前后端代码都在里面。 该系统功能完善、界面美观、操作简单、功能齐全、管理便捷,具有很高的实际应用价值。 项目都经过严格调试,确保可以运行!可以放心下载 技术组成 语言:java 开发环境:idea 数据库:MySql8.0 部署环境:Tomcat(建议用 7.x 或者 8.x 版本),maven 数据库工具:navicat

    基于FATFS系统的STM32F407 SD卡升级Bootloader程序:自动检测与升级流程,stm32f407 SD卡升级 bootloader程序 基于sdio fatfs系统的stm32 b

    基于FATFS系统的STM32F407 SD卡升级Bootloader程序:自动检测与升级流程,stm32f407 SD卡升级 bootloader程序 基于sdio fatfs系统的stm32 bootloader程序 功能简介: 本程序使用fatfs系统读取bin文件。 开机后会自动检测sd卡,检测到sd卡后,再读取固定名称的bin文件,之后会对bin文件进行首包校验,判断该升级包的起始地址是否正确,正确的话,就循环读取bin文件并写入到flash中。 完成升级。 详细流程请看流程图 ,stm32f407; SD卡升级; bootloader程序; fatfs系统读取bin文件; 检测SD卡; 首包校验; 循环写入flash。,STM32F407 SD卡升级Bootloader程序:基于SDIO FATFS系统实现自动升级功能

    激光设备上位机源码解析:基于欧姆龙NJplc通讯协议与多种激光器控制实现,激光设备上位机源码+基于欧姆龙NJplc上位机+各种常见激光器通讯控制 ,核心关键词:激光设备上位机源码; 欧姆龙NJpl

    激光设备上位机源码解析:基于欧姆龙NJplc通讯协议与多种激光器控制实现,激光设备上位机源码+基于欧姆龙NJplc上位机+各种常见激光器通讯控制。 ,核心关键词:激光设备上位机源码; 欧姆龙NJplc上位机; 常见激光器通讯控制; PLC控制。,"欧姆龙NJplc驱动的激光设备上位机控制源码:通用激光器通讯管理"

    高效数字电源方案:图腾柱无桥pfc技术,两相交错设计,5G一体化电源批量出货,宽电压输入与高效输出,功率覆盖至kW级别,高效数字电源方案,图腾柱无桥pfc,两相交错,5g一体化电电源上已批量出,输入1

    高效数字电源方案:图腾柱无桥pfc技术,两相交错设计,5G一体化电源批量出货,宽电压输入与高效输出,功率覆盖至kW级别,高效数字电源方案,图腾柱无桥pfc,两相交错,5g一体化电电源上已批量出,输入175-265V,输出42-58V;输出效率97%,2kW 3kW都有 ,高效数字电源方案; 图腾柱无桥pfc; 两相交错; 5g一体化电电源; 批量出货; 宽输入电压范围; 高输出效率; 2kW和3kW功率。,"高效图腾柱无桥PFC电源方案,两相交错5G电平已大批量生产,宽输入范围输出高效率"

    COMSOL三维采空区通风条件下的氧气与瓦斯浓度分布研究,comsol三维采空区通风条件下,氧气,瓦斯浓度分布 ,核心关键词:comsol; 三维采空区; 通风条件; 氧气浓度分布; 瓦斯浓度分布

    COMSOL三维采空区通风条件下的氧气与瓦斯浓度分布研究,comsol三维采空区通风条件下,氧气,瓦斯浓度分布。 ,核心关键词:comsol; 三维采空区; 通风条件; 氧气浓度分布; 瓦斯浓度分布;,"三维采空区通风模拟:氧气与瓦斯浓度分布研究"

    基于java+ssm+mysql的餐馆点餐系统 源码+数据库+论文(高分毕设项目).zip

    项目已获导师指导并通过的高分毕业设计项目,可作为课程设计和期末大作业,下载即用无需修改,项目完整确保可以运行。 包含:项目源码、数据库脚本、软件工具等,该项目可以作为毕设、课程设计使用,前后端代码都在里面。 该系统功能完善、界面美观、操作简单、功能齐全、管理便捷,具有很高的实际应用价值。 项目都经过严格调试,确保可以运行!可以放心下载 技术组成 语言:java 开发环境:idea 数据库:MySql8.0 部署环境:Tomcat(建议用 7.x 或者 8.x 版本),maven 数据库工具:navicat

    Python自动化办公源码-07一键往Word文档的表格中填写数据

    Python自动化办公源码-07一键往Word文档的表格中填写数据

    2025最新初级保育员理论知识考试题库及答案.doc

    2025最新初级保育员理论知识考试题库及答案.doc

    基于Tent混沌映射改进的麻雀算法SSA优化BP神经网络(Tent-SSA-BP)回归预测MATLAB代码教程:电厂数据预测(含优化对比),基于Tent混沌映射改进的麻雀算法SSA优化BP神经网络(T

    基于Tent混沌映射改进的麻雀算法SSA优化BP神经网络(Tent-SSA-BP)回归预测MATLAB代码教程:电厂数据预测(含优化对比),基于Tent混沌映射改进的麻雀算法SSA优化BP神经网络(Tent-SSA-BP)回归预测MATLAB代码(有优化前后的对比) 代码注释清楚。 main为运行主程序,可以读取本地EXCEL数据。 很方便,容易上手。 (以电厂运行数据为例) 温馨提示:联系请考虑是否需要,程序代码,一经出,概不 。 ,Tent-SSA; BP神经网络; 回归预测; MATLAB代码; 优化对比; 代码注释; 主程序; EXCEL数据读取; 电厂运行数据。,基于Tent混沌映射与SSA优化的BP神经网络回归预测MATLAB代码(含前后对比及清晰注释)

    西门子1200 PLC轴运动控制程序模板-涵盖伺服控制、电缸、通讯及报警功能,适用于装路由器壳子的机器,具备电路图与触摸屏程序,供学习与借鉴 ,SIEMENS 西门子西门子1200plc轴运动控制程

    西门子1200 PLC轴运动控制程序模板——涵盖伺服控制、电缸、通讯及报警功能,适用于装路由器壳子的机器,具备电路图与触摸屏程序,供学习与借鉴。,SIEMENS 西门子西门子1200plc轴运动控制程序模板 介绍:此程序是之前给海康威视做的一台装路由器壳子的机器。 程序有以下: 1):调用轴控制块做的控制3个伺服, 2):1个电缸, 3):用PUT GET块与上下游plc通讯, 4):轴控制块 5):气缸报警块 6):完整的电路图 7):威纶通触摸屏程序 8):IO表 程序块已经在很多个项目上成熟应用,可以直接调用,对于做西门子1200轴控制等有很好的学习借鉴意义。 好好看一遍,有很大的提高作用。 ,SIEMENS; 1200plc; 轴运动控制; 程序模板; 伺服控制; 电缸控制; PLC通讯; 威纶通触摸屏程序; 电路图; IO表,西门子1200 PLC轴运动控制模板:海康威视项目成熟应用示例

    《2023年未来就业报告》:人工智能对未来就业市场的影响及应对措施

    内容概要:本文详细探讨了人工智能(AI)对就业市场的深远影响及其发展趋势。首先介绍了到2027年,44%的工人核心技能将受技术变革尤其是AI影响的事实,并提及自动化可能取代部分工作的现象。其次指出虽然某些职位面临风险,但也带来了全新的职业机遇与现有角色改进的可能性,关键在于人类要学会借助AI释放自身潜力并培养软实力,以适应快速发展的科技需求。再者,强调终身学习理念下企业和教育培训须革新教学手段与评估机制,以便紧跟AI进化速率,为个体和社会持续注入新动力。最后提到了教育机构应当加快调整步伐以匹配技术变革的速度,并利用AI实现个性化的教育,进而提升学习者的适应能力和解决问题的能力。 适用人群:政策制定者、企业管理层、在职人员及教育工作者,还有广大学生群体均能从中获得启示。 使用场景及目标:面向关注未来职场动向及教育发展方向的专业人士,提供前瞻性思考角度,助力各界积极规划职业生涯路径或调整教育资源分配策略。 其他说明:本文综合多位行业领袖的观点展开讨论,旨在唤起社会各界共同思考AI带来的变革及对策,而非单方面渲染危机感。

    谷歌 Adsense 合同(中文)

    谷歌 Adsense 在线服务条款,首次办理接收谷歌 Adsense 付款时需要提交的一份证明材料(合同/协议),需要提交中文版,已经翻译成中文了。

    Python自动化办公源码-14用Python按时间分割txt文件中的数据

    Python自动化办公源码-14用Python按时间分割txt文件中的数据

    Native SQLite Manager for Mac v1.29.2

    Native SQLite Manager for Mac是一款极简的SQLite数据库管理工具,专为Mac用户设计。它支持多种SQLite版本、SQLCipher加密和SQLite扩展,提供自动补全、语法高亮和SQL格式化功能。用户可以通过简洁直观的界面轻松创建、编辑、删除和备份数据库文件。软件还支持数据导入导出(如CSV、JSON、XML格式),方便数据迁移和备份。其多数据库管理功能允许同时打开多个数据库文件,提升工作效率。Native SQLite Manager适合开发者、数据分析师和学生使用,是高效管理SQLite数据库的理想选择。

    西门子SMART 200电机控制子程序V1.6:智能管理多达7个电机,灵活设置运行参数,故障自动切换备用电机,版本升级持续优化 ,西门子SMART 200 电机控制子程序V1.6,可生成库 可控制1

    西门子SMART 200电机控制子程序V1.6:智能管理多达7个电机,灵活设置运行参数,故障自动切换备用电机,版本升级持续优化。,西门子SMART 200 电机控制子程序V1.6,可生成库 可控制1-7个电机 可设置同时运行的最大电机数量 可设置每个电机是否使用 可设置电机轮时间,当系统单次运行时间>轮时间,停止运行时间最长的电机,上累计运行时间最短的电机 可设置电机启动间隔 每次启动累计运行时间最短的电机 当有电机故障时,立即停止该电机,如果有备用电机自动切备用电机 7个电机内,可自由设置备用电机个数,使用的电机总数-最大电机数量=备用电机个数 附版本升级记录: V1.1优化:当使能被关闭后自动关闭对应电机 V1.2优化:运行中改变同时使用电机数量有效 V1.3更改:open信号上升沿直接启动1个电机(跳过启动间隔),第二个电机启动间隔才有效 轮时间改为秒,当系统单次运行时间>轮时间,停止运行时间最长的电机,上累计运行时间最短的电机 V1.4优化 V1.5满足可以运行的电机数量>同时使用电机数量 时 轮才有效,不满足时,轮计时清零 V1.6 优化某些情况下,无法正确延时 ,核心关键词

    2012-2023年劳务外包数据(劳务派遣或灵活就业等)(全新整理)

    1、资源内容地址:https://blog.csdn.net/2301_79696294/article/details/144634118 2、数据特点:今年全新,手工精心整理,放心引用,数据来自权威,且标注《数据来源》,相对于其他人的控制变量数据准确很多,适合写论文做实证用 ,不会出现数据造假问题 3、适用对象:大学生,本科生,研究生小白可用,容易上手!!! 4、课程引用: 经济学,地理学,城市规划与城市研究,公共政策与管理,社会学,商业与管理

Global site tag (gtag.js) - Google Analytics