`
hanyi366
  • 浏览: 289255 次
  • 性别: 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;
   }
}



分享到:
评论

相关推荐

    aiohttp-3.7.3-cp36-cp36m-win_amd64.whl.rar

    python whl离线安装包 pip安装失败可以尝试使用whl离线安装包安装 第一步 下载whl文件,注意需要与python版本配套 python版本号、32位64位、arm或amd64均有区别 第二步 使用pip install XXXXX.whl 命令安装,如果whl路径不在cmd窗口当前目录下,需要带上路径 WHL文件是以Wheel格式保存的Python安装包, Wheel是Python发行版的标准内置包格式。 在本质上是一个压缩包,WHL文件中包含了Python安装的py文件和元数据,以及经过编译的pyd文件, 这样就使得它可以在不具备编译环境的条件下,安装适合自己python版本的库文件。 如果要查看WHL文件的内容,可以把.whl后缀名改成.zip,使用解压软件(如WinRAR、WinZIP)解压打开即可查看。 为什么会用到whl文件来安装python库文件呢? 在python的使用过程中,我们免不了要经常通过pip来安装自己所需要的包, 大部分的包基本都能正常安装,但是总会遇到有那么一些包因为各种各样的问题导致安装不了的。 这时我们就可以通过尝试去Python安装包大全中(whl包下载)下载whl包来安装解决问题。

    基于Java中的swing类的图形化飞机游戏的开发练习.zip

    基于Java中的Swing类开发的图形化飞机游戏练习包,为初学者和进阶学习者提供了实践Java GUI编程的绝佳机会。通过本资源,开发者可以利用Java语言和Swing库构建一个用户交互式的2D游戏,深入理解图形用户界面(GUI)编程和事件处理机制。该游戏的核心包括玩家飞机的控制、敌机的生成与移动、子弹发射与碰撞检测以及游戏胜负判定等逻辑。玩家通过鼠标移动控制己方飞机,实现平滑的移动和连续的子弹发射;而敌方飞机则按照一定算法无规律出现,随着游戏进程难度逐渐增加。游戏中还引入了特殊NPC,增加了额外的挑战和乐趣。为了提高游戏体验,游戏还包含了开始背景、结束背景以及背景音乐等元素。当玩家击毁敌机时,会有相应的得分计算和展示;若被敌机击中,则游戏结束并显示最终得分。此外,游戏还提供了查看历史前十记录、帮助和退出等选项,方便玩家进行游戏设置和了解游戏玩法。本资源适用于计算机科学与技术、软件工程、信息管理及相关专业的课程设计、毕业设计等环节,为学生提供实践操作的机会,帮助他们巩固Java编程知识,提高动手能力和发散思维。同时,也为希望学习不同技术领域的学习者提供了一个优秀的入门项目。

    SQLite:SQLite数据库创建与管理.docx

    SQLite:SQLite数据库创建与管理

    【完整源码+数据库】SpringBoot 集成 Spring Security短信验证码登录

    Spring Security 默认是账号和密码登录,现在是对 Spring Security 进行扩展,来实现短信验证码方式登录。 SpringBoot 集成 Spring Security短信验证码登录【完整源码+数据库】

    去年和朋友一起做的java小游戏.游戏具体界面在readme中,游戏设计的uml图在design.pdf中.zip

    本资源是一个Java小游戏项目,由我和我的朋友在去年共同开发。这个项目不仅包含了完整的游戏代码,还有详细的设计文档和UML图,适合作为学习和参考的素材。游戏的界面设计简洁明了,玩法有趣且富有挑战性,能够让玩家在游戏中体验到乐趣。在readme文件中,你可以找到游戏的具体界面展示,让你对游戏的外观有一个直观的了解。而design.pdf中则包含了游戏的UML图,详细展示了游戏的设计结构和各个模块之间的关系,对于理解游戏的整体架构非常有帮助。这个Java小游戏项目是一个非常好的学习资源,无论是对于初学者还是有一定经验的开发者来说,都可以通过这个项目来提升自己的编程技能和游戏设计能力。通过阅读代码和设计文档,你可以了解到如何构建一个功能完整的游戏,并且可以根据自己的需要进行修改和扩展。总之,这个Java小游戏项目是一个值得学习和探索的资源,希望对你有所帮助!

    ad3-2.2.1-cp34-cp34m-win_amd64.whl.rar

    python whl离线安装包 pip安装失败可以尝试使用whl离线安装包安装 第一步 下载whl文件,注意需要与python版本配套 python版本号、32位64位、arm或amd64均有区别 第二步 使用pip install XXXXX.whl 命令安装,如果whl路径不在cmd窗口当前目录下,需要带上路径 WHL文件是以Wheel格式保存的Python安装包, Wheel是Python发行版的标准内置包格式。 在本质上是一个压缩包,WHL文件中包含了Python安装的py文件和元数据,以及经过编译的pyd文件, 这样就使得它可以在不具备编译环境的条件下,安装适合自己python版本的库文件。 如果要查看WHL文件的内容,可以把.whl后缀名改成.zip,使用解压软件(如WinRAR、WinZIP)解压打开即可查看。 为什么会用到whl文件来安装python库文件呢? 在python的使用过程中,我们免不了要经常通过pip来安装自己所需要的包, 大部分的包基本都能正常安装,但是总会遇到有那么一些包因为各种各样的问题导致安装不了的。 这时我们就可以通过尝试去Python安装包大全中(whl包下载)下载whl包来安装解决问题。

    arctic-1.67.1-cp36-cp36m-win32.whl.rar

    python whl离线安装包 pip安装失败可以尝试使用whl离线安装包安装 第一步 下载whl文件,注意需要与python版本配套 python版本号、32位64位、arm或amd64均有区别 第二步 使用pip install XXXXX.whl 命令安装,如果whl路径不在cmd窗口当前目录下,需要带上路径 WHL文件是以Wheel格式保存的Python安装包, Wheel是Python发行版的标准内置包格式。 在本质上是一个压缩包,WHL文件中包含了Python安装的py文件和元数据,以及经过编译的pyd文件, 这样就使得它可以在不具备编译环境的条件下,安装适合自己python版本的库文件。 如果要查看WHL文件的内容,可以把.whl后缀名改成.zip,使用解压软件(如WinRAR、WinZIP)解压打开即可查看。 为什么会用到whl文件来安装python库文件呢? 在python的使用过程中,我们免不了要经常通过pip来安装自己所需要的包, 大部分的包基本都能正常安装,但是总会遇到有那么一些包因为各种各样的问题导致安装不了的。 这时我们就可以通过尝试去Python安装包大全中(whl包下载)下载whl包来安装解决问题。

    基于Java实现的黄金矿工小游戏.zip

    本资源是一个基于Java实现的黄金矿工小游戏项目,旨在帮助初学者通过实践巩固Java编程知识。游戏包含多个功能模块,如窗口绘制、图片绘制、红线摇摆及抓取判定等,并采用双缓存技术解决画面闪动问题。此外,还实现了金块和石块的随机生成与抓取机制、积分设置、关卡设置以及商店购物等功能。本项目适合刚入门或有一定基础的Java学习者,通过完成这个项目,可以提升面向对象编程的理解和应用能力,同时增强对Java基础知识的掌握。

    课设毕设基于SpringBoot+Vue的大学生心理咨询平台源码可运行.zip

    本压缩包资源说明,你现在往下拉可以看到压缩包内容目录 我是批量上传的基于SpringBoot+Vue的项目,所以描述都一样;有源码有数据库脚本,系统都是测试过可运行的,看文件名即可区分项目~ |Java|SpringBoot|Vue|前后端分离| 开发语言:Java 框架:SpringBoot,Vue JDK版本:JDK1.8 数据库:MySQL 5.7+(推荐5.7,8.0也可以) 数据库工具:Navicat 开发软件: idea/eclipse(推荐idea) Maven包:Maven3.3.9+ 系统环境:Windows/Mac

    网络直播带货查询系统 SSM毕业设计 附带论文.zip

    网络直播带货查询系统 SSM毕业设计 附带论文 启动教程:https://www.bilibili.com/video/BV1GK1iYyE2B

    Assimulo-3.1-cp35-cp35m-win_amd64.whl.rar

    python whl离线安装包 pip安装失败可以尝试使用whl离线安装包安装 第一步 下载whl文件,注意需要与python版本配套 python版本号、32位64位、arm或amd64均有区别 第二步 使用pip install XXXXX.whl 命令安装,如果whl路径不在cmd窗口当前目录下,需要带上路径 WHL文件是以Wheel格式保存的Python安装包, Wheel是Python发行版的标准内置包格式。 在本质上是一个压缩包,WHL文件中包含了Python安装的py文件和元数据,以及经过编译的pyd文件, 这样就使得它可以在不具备编译环境的条件下,安装适合自己python版本的库文件。 如果要查看WHL文件的内容,可以把.whl后缀名改成.zip,使用解压软件(如WinRAR、WinZIP)解压打开即可查看。 为什么会用到whl文件来安装python库文件呢? 在python的使用过程中,我们免不了要经常通过pip来安装自己所需要的包, 大部分的包基本都能正常安装,但是总会遇到有那么一些包因为各种各样的问题导致安装不了的。 这时我们就可以通过尝试去Python安装包大全中(whl包下载)下载whl包来安装解决问题。

    abcview-1.0.8-py2-none-any.whl.rar

    python whl离线安装包 pip安装失败可以尝试使用whl离线安装包安装 第一步 下载whl文件,注意需要与python版本配套 python版本号、32位64位、arm或amd64均有区别 第二步 使用pip install XXXXX.whl 命令安装,如果whl路径不在cmd窗口当前目录下,需要带上路径 WHL文件是以Wheel格式保存的Python安装包, Wheel是Python发行版的标准内置包格式。 在本质上是一个压缩包,WHL文件中包含了Python安装的py文件和元数据,以及经过编译的pyd文件, 这样就使得它可以在不具备编译环境的条件下,安装适合自己python版本的库文件。 如果要查看WHL文件的内容,可以把.whl后缀名改成.zip,使用解压软件(如WinRAR、WinZIP)解压打开即可查看。 为什么会用到whl文件来安装python库文件呢? 在python的使用过程中,我们免不了要经常通过pip来安装自己所需要的包, 大部分的包基本都能正常安装,但是总会遇到有那么一些包因为各种各样的问题导致安装不了的。 这时我们就可以通过尝试去Python安装包大全中(whl包下载)下载whl包来安装解决问题。

    Teradata:TeradataSQL语言入门.docx

    Teradata:TeradataSQL语言入门.docx

    winlibs-x86-64-win32-seh-gcc-14.2.0-llvm-19.1.3-mingw-w64.zip

    winlibs-x86-64-win32-seh-gcc-14.2.0-llvm-19.1.3-mingw-w64.zip

    aicspylibczi-3.0.5-cp39-cp39-win_amd64.whl.rar

    python whl离线安装包 pip安装失败可以尝试使用whl离线安装包安装 第一步 下载whl文件,注意需要与python版本配套 python版本号、32位64位、arm或amd64均有区别 第二步 使用pip install XXXXX.whl 命令安装,如果whl路径不在cmd窗口当前目录下,需要带上路径 WHL文件是以Wheel格式保存的Python安装包, Wheel是Python发行版的标准内置包格式。 在本质上是一个压缩包,WHL文件中包含了Python安装的py文件和元数据,以及经过编译的pyd文件, 这样就使得它可以在不具备编译环境的条件下,安装适合自己python版本的库文件。 如果要查看WHL文件的内容,可以把.whl后缀名改成.zip,使用解压软件(如WinRAR、WinZIP)解压打开即可查看。 为什么会用到whl文件来安装python库文件呢? 在python的使用过程中,我们免不了要经常通过pip来安装自己所需要的包, 大部分的包基本都能正常安装,但是总会遇到有那么一些包因为各种各样的问题导致安装不了的。 这时我们就可以通过尝试去Python安装包大全中(whl包下载)下载whl包来安装解决问题。

    #-ssm-068-mysql-学生智能选课系统-.zip

    管理员用户: 1.管理员详情: 1.1查看个人信息; 1.2添加新的管理员;管理员的详细信息2.学生详情: 2.1 添加学生;学号,密码(与学号一样),姓名,性别,班级,联系电话,身份证号 2.2 查询所有学生;要有一个筛选的地方可以筛选学号,姓名,性别,班级,评论,(筛选的地方后面做一个查询的按钮); 下面做一个查询的页面,展示学号,姓名,性别,班级,密码,身份证号,成绩,后添加一个按钮(操作,可以删除该条学生记录,可以修改学生信息); 3.课程功能; 3.1 添加课程; 3.2 查询课程; 4.老师功能; 4.1添加老师; 4.2查询所有老师; 老师用户; 1.个人信息;2.打分功能; 做一个筛选(根据班级筛选,根据成绩排序)可以看到选了自己的课的学生信息, 3.任课信息; 3.学生功能; 1.查看个人信息 2.选课,展示跟自己专业相关课程的所有信息,最后做一个操作按钮 选课,也可以取消选课; 3.查看选课信息及成绩, 可以看到课程所有信息,和任课老师的姓名,电话, 以及打的平时成绩,考试成绩,最终成绩。。

    LabVIEW练习39,程序开始运行后要求用户输入密码

    程序开始运行后要求用户输入密码,密码正确时字符串显示控件显示 “欢迎进入”, 否则显示字符串“密码错误”,同时退出程序。

    使用java实现的简单飞机大战游戏.zip

    本资源提供了使用java实现的简单飞机大战游戏,是一款经典的2D射击游戏。玩家在游戏中控制一架飞机,通过键盘操作移动和发射子弹,击落敌机获得积分。当达到一定积分时,会出现Boss,增加游戏难度。游戏还包含碰撞检测、得分系统以及游戏状态管理等功能。该资源旨在帮助学习者掌握Java编程的各个方面,包括面向对象设计、图形界面编程等。通过这个项目,学习者可以深入理解如何使用Java语言实现一个具备基本功能的小游戏,并学会如何处理游戏中的交互、碰撞检测和动画效果等技术细节。本资源适合Java编程初学者及对游戏开发感兴趣的开发者学习和参考,是提升编程技能和项目经验的绝佳实践材料。

    基于java多线程的一款小游戏.zip

    本资源是一款基于Java多线程开发的小游戏,旨在通过实战项目帮助学习者深入理解多线程编程的概念和应用。游戏中涉及多个并发任务,如角色移动、碰撞检测和动画更新等,每个任务都由独立的线程处理,以实现更流畅的游戏体验。游戏设计简洁但不失趣味性,包括一个主窗体、游戏面板以及控制面板。玩家可以通过控制面板选择角色并开始游戏,角色将在游戏面板中进行奔跑或其他活动。游戏过程中,各线程协同工作,确保游戏的实时响应和高效运行。此外,该资源还提供了详细的代码注释和文档说明,方便学习者理解每一部分的功能和实现方式。通过本项目的学习,不仅可以掌握Java多线程编程的基本技能,还能提升对游戏开发流程的理解。本资源完全基于学习和研究目的,请勿用于商业用途。

Global site tag (gtag.js) - Google Analytics