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



分享到:
评论

相关推荐

    毕业设计选题 -未来生鲜运输车设计.pptx

    毕业设计选题 -未来生鲜运输车设计.pptx

    基于樽海鞘算法优化的极限学习机回归预测及其与BP、GRNN、ELM的性能对比研究

    内容概要:本文详细探讨了基于樽海鞘算法(SSA)优化的极限学习机(ELM)在回归预测任务中的应用,并与传统的BP神经网络、广义回归神经网络(GRNN)以及未优化的ELM进行了性能对比。首先介绍了ELM的基本原理,即通过随机生成输入层与隐藏层之间的连接权重及阈值,仅需计算输出权重即可快速完成训练。接着阐述了SSA的工作机制,利用樽海鞘群体觅食行为优化ELM的输入权重和隐藏层阈值,从而提高模型性能。随后分别给出了BP、GRNN、ELM和SSA-ELM的具体实现代码,并通过波士顿房价数据集和其他工业数据集验证了各模型的表现。结果显示,SSA-ELM在预测精度方面显著优于其他三种方法,尽管其训练时间较长,但在实际应用中仍具有明显优势。 适合人群:对机器学习尤其是回归预测感兴趣的科研人员和技术开发者,特别是那些希望深入了解ELM及其优化方法的人。 使用场景及目标:适用于需要高效、高精度回归预测的应用场景,如金融建模、工业数据分析等。主要目标是提供一种更为有效的回归预测解决方案,尤其是在处理大规模数据集时能够保持较高的预测精度。 其他说明:文中提供了详细的代码示例和性能对比图表,帮助读者更好地理解和复现实验结果。同时提醒使用者注意SSA参数的选择对模型性能的影响,建议进行参数敏感性分析以获得最佳效果。

    2025年中国生成式AI大会PPT(4-1)

    2025年中国生成式AI大会PPT(4-1)

    无刷直流电机双闭环调速系统的Simulink建模与参数优化

    内容概要:本文详细介绍了基于Simulink平台构建无刷直流电机(BLDC)双闭环调速系统的全过程。首先阐述了双闭环控制系统的基本架构,即外层速度环和内层电流环的工作原理及其相互关系。接着深入探讨了PWM生成模块的设计,特别是占空比计算方法的选择以及三角波频率的设定。文中还提供了详细的电机参数设置指导,如转动惯量、电感、电阻等,并强调了参数选择对系统性能的影响。此外,针对PI控制器的参数整定给出了具体的公式和经验值,同时分享了一些实用的调试技巧,如避免转速超调、处理启动抖动等问题的方法。最后,通过仿真实验展示了系统的稳定性和鲁棒性,验证了所提出方法的有效性。 适用人群:从事电机控制研究的技术人员、自动化工程领域的研究生及科研工作者。 使用场景及目标:适用于需要深入了解和掌握无刷直流电机双闭环调速系统设计与优化的人群。主要目标是帮助读者学会利用Simulink进行BLDC电机控制系统的建模、仿真和参数优化,从而提高系统的稳定性和响应速度。 其他说明:文章不仅提供了理论知识,还包括了许多实践经验和技术细节,有助于读者更好地理解和应用相关技术。

    西门子S7-1200 PLC与施耐德变频器Modbus通讯实现及调试技巧

    内容概要:本文详细介绍了西门子S7-1200 PLC与施耐德ATV310/312变频器通过Modbus RTU进行通讯的具体实现步骤和调试技巧。主要内容涵盖硬件接线、通讯参数配置、控制启停、设定频率、读取运行参数的方法以及常见的调试问题及其解决方案。文中提供了具体的代码示例,帮助读者理解和实施通讯程序。此外,还强调了注意事项,如地址偏移量、数据格式转换和超时匹配等。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是那些需要将西门子PLC与施耐德变频器进行集成的工作人员。 使用场景及目标:适用于需要通过Modbus RTU协议实现PLC与变频器通讯的工程项目。目标是确保通讯稳定可靠,掌握解决常见问题的方法,提高调试效率。 其他说明:文中提到的实际案例和调试经验有助于读者避免常见错误,快速定位并解决问题。建议读者在实践中结合提供的代码示例和调试工具进行操作。

    基于FPGA的Verilog实现IIC主从机驱动及其应用

    内容概要:本文详细介绍了如何使用Verilog在FPGA上实现IIC(Inter-Integrated Circuit)主从机驱动。主要内容包括从机和主机的设计,特别是状态机的实现、寄存器读取、时钟分频策略、SDA线的三态控制等关键技术。文中还提供了详细的代码片段,展示了从机地址匹配逻辑、主机时钟生成逻辑、顶层模块的连接方法以及仿真实验的具体步骤。此外,文章讨论了一些常见的调试问题,如总线竞争、时序不匹配等,并给出了相应的解决方案。 适合人群:具备一定FPGA开发基础的技术人员,尤其是对IIC协议感兴趣的嵌入式系统开发者。 使用场景及目标:适用于需要在FPGA平台上实现高效、可靠的IIC通信的应用场景。主要目标是帮助读者掌握IIC协议的工作原理,能够独立完成IIC主从机系统的开发和调试。 其他说明:文章不仅提供了理论讲解,还包括了大量的实战经验和代码实例,有助于读者更好地理解和应用所学知识。同时,文章还提供了一个思考题,引导读者进一步探索多主设备仲裁机制的设计思路。

    C#开发的拖拽式Halcon可视化抓边抓圆控件,提升机器视觉测量效率

    内容概要:本文介绍了一款基于C#开发的拖拽式Halcon可视化抓边、抓圆控件,旨在简化机器视觉项目中的测量任务。该控件通过拖拽操作即可快速生成测量区域,自动完成边缘坐标提取,并提供实时反馈。文中详细描述了控件的工作原理和技术细节,如坐标系转换、卡尺生成、边缘检测算法封装以及动态参数调试等功能。此外,还讨论了一些常见问题及其解决方案,如坐标系差异、内存管理等。 适合人群:从事机器视觉开发的技术人员,尤其是熟悉C#和Halcon的开发者。 使用场景及目标:适用于需要频繁进行边缘和圆形特征测量的工业自动化项目,能够显著提高测量效率并减少编码工作量。主要目标是将复杂的测量任务转化为简单的拖拽操作,使非专业人员也能轻松完成测量配置。 其他说明:该控件已开源发布在GitHub上,提供了完整的源代码和详细的使用指南。未来计划扩展更多高级功能,如自动路径规划和亚像素级齿轮齿距检测等。

    西门子200Smart与维纶触摸屏在疫苗车间控制系统的应用:配液、发酵、纯化及CIP清洗工艺详解

    内容概要:本文详细介绍了西门子200Smart PLC与维纶触摸屏在某疫苗车间控制系统的具体应用,涵盖配液、发酵、纯化及CIP清洗四个主要工艺环节。文中不仅展示了具体的编程代码和技术细节,还分享了许多实战经验和调试技巧。例如,在配液罐中,通过模拟量处理确保温度和液位的精确控制;发酵罐部分,着重讨论了PID参数整定和USS通讯控制变频器的方法;纯化过程中,强调了双PID串级控制的应用;CIP清洗环节,则涉及复杂的定时器逻辑和阀门联锁机制。此外,文章还提到了一些常见的陷阱及其解决方案,如通讯干扰、状态机切换等问题。 适合人群:具有一定PLC编程基础的技术人员,尤其是从事工业自动化领域的工程师。 使用场景及目标:适用于需要深入了解PLC与触摸屏集成控制系统的工程师,帮助他们在实际项目中更好地理解和应用相关技术和方法,提高系统的稳定性和可靠性。 其他说明:文章提供了大量实战经验和代码片段,有助于读者快速掌握关键技术点,并避免常见错误。同时,文中提到的一些优化措施和调试技巧对提升系统性能非常有帮助。

    计算机网络结课设计:通过思科Cisco进行中小型校园网搭建

    计算机网络课程的结课设计是使用思科模拟器搭建一个中小型校园网,当时花了几天时间查阅相关博客总算是做出来了,现在免费上传CSDN,希望小伙伴们能给博客一套三连支持

    芋道(yudao)开发技术文档

    《芋道开发指南文档-2023-10-27更新》是针对软件开发者和IT专业人士的一份详尽的资源集合,旨在提供最新的开发实践、范例代码和最佳策略。这份2023年10月27日更新的文档集,包含了丰富的模板和素材,帮助开发者在日常工作中提高效率,保证项目的顺利进行。 让我们深入探讨这份文档的可能内容。"芋道"可能是一个开源项目或一个专业的技术社区,其开发指南涵盖了多个方面,例如: 1. **编程语言指南**:可能包括Java、Python、JavaScript、C++等主流语言的编码规范、最佳实践以及常见问题的解决方案。 2. **框架与库的应用**:可能会讲解React、Vue、Angular等前端框架,以及Django、Spring Boot等后端框架的使用技巧和常见应用场景。 3. **数据库管理**:涵盖了SQL语言的基本操作,数据库设计原则,以及如何高效使用MySQL、PostgreSQL、MongoDB等数据库系统。 4. **版本控制**:详细介绍了Git的工作流程,分支管理策略,以及与其他开发工具(如Visual Studio Code、IntelliJ IDEA)的集成。 5. **持续集成与持续部署(CI/CD)**:包括Jenkins、Travis CI、GitHub Actions等工具的配置和使用,以实现自动化测试和部署。 6. **云服务与容器化**:可能涉及AWS、Azure、Google Cloud Platform等云计算平台的使用,以及Docker和Kubernetes的容器化部署实践。 7. **API设计与测试**:讲解RESTful API的设计原则,Swagger的使用,以及Postman等工具进行API测试的方法。 8. **安全性与隐私保护**:涵盖OAuth、JWT认证机制,HTTPS安全通信,以及防止SQL注入、

    基于信息间隙决策的综合能源系统优化调度模型及其应用

    内容概要:本文介绍了一种先进的综合能源系统优化调度模型,该模型将风电、光伏、光热发电等新能源与燃气轮机、燃气锅炉等传统能源设备相结合,利用信息间隙决策(IGDT)处理不确定性。模型中引入了P2G(电转气)装置和碳捕集技术,实现了碳经济闭环。通过多能转换和储能系统的协同调度,提高了系统的灵活性和鲁棒性。文中详细介绍了模型的关键组件和技术实现,包括IGDT的鲁棒性参数设置、P2G与碳捕集的协同控制、储能系统的三维协同调度等。此外,模型展示了在极端天气和负荷波动下的优异表现,显著降低了碳排放成本并提高了能源利用效率。 适合人群:从事能源系统优化、电力调度、碳交易等相关领域的研究人员和工程师。 使用场景及目标:适用于需要处理多种能源形式和不确定性的综合能源系统调度场景。主要目标是提高系统的灵活性、鲁棒性和经济效益,减少碳排放。 其他说明:模型具有良好的扩展性,可以通过修改配置文件轻松集成新的能源设备。代码中包含了详细的注释和公式推导,便于理解和进一步改进。

    毕业设计的论文撰写、终期答辩相关的资源.m

    毕业设计的论文撰写、终期答辩相关的资源

    机器学习(预测模型):专注于 2024 年出现的漏洞(CVE)信息数据集

    该是一个在 Kaggle 上发布的数据集,专注于 2024 年出现的漏洞(CVE)信息。以下是关于该数据集的详细介绍:该数据集收集了 2024 年记录在案的各类漏洞信息,涵盖了漏洞的利用方式(Exploits)、通用漏洞评分系统(CVSS)评分以及受影响的操作系统(OS)。通过整合这些信息,研究人员和安全专家可以全面了解每个漏洞的潜在威胁、影响范围以及可能的攻击途径。数据主要来源于权威的漏洞信息平台,如美国国家漏洞数据库(NVD)等。这些数据经过整理和筛选后被纳入数据集,确保了信息的准确性和可靠性。数据集特点:全面性:涵盖了多种操作系统(如 Windows、Linux、Android 等)的漏洞信息,反映了不同平台的安全状况。实用性:CVSS 评分提供了漏洞严重程度的量化指标,帮助用户快速评估漏洞的优先级。同时,漏洞利用信息(Exploits)为安全研究人员提供了攻击者可能的攻击手段,有助于提前制定防御策略。时效性:专注于 2024 年的漏洞数据,反映了当前网络安全领域面临的新挑战和新趋势。该数据集可用于多种研究和实践场景: 安全研究:研究人员可以利用该数据集分析漏洞的分布规律、攻击趋势以及不同操作系统之间的安全差异,为网络安全防护提供理论支持。 机器学习与数据分析:数据集中的结构化信息适合用于机器学习模型的训练,例如预测漏洞的 CVSS 评分、识别潜在的高危漏洞等。 企业安全评估:企业安全团队可以参考该数据集中的漏洞信息,结合自身系统的实际情况,进行安全评估和漏洞修复计划的制定。

    建模大赛入门指南:从零基础到实战应用.pdf

    内容概要:本文档作为建模大赛的入门指南,详细介绍了建模大赛的概念、类型、竞赛流程、核心步骤与技巧,并提供实战案例解析。文档首先概述了建模大赛,指出其以数学、计算机技术为核心,主要分为数学建模、3D建模和AI大模型竞赛三类。接着深入解析了数学建模竞赛,涵盖组队策略(如三人分别负责建模、编程、论文写作)、时间安排(72小时内完成全流程)以及问题分析、模型建立、编程实现和论文撰写的要点。文中还提供了物流路径优化的实战案例,展示了如何将实际问题转化为图论问题并采用Dijkstra或蚁群算法求解。最后,文档推荐了不同类型建模的学习资源与工具,并给出了新手避坑建议,如避免过度复杂化模型、重视可视化呈现等。; 适合人群:对建模大赛感兴趣的初学者,特别是高校学生及希望参与数学建模竞赛的新手。; 使用场景及目标:①了解建模大赛的基本概念和分类;②掌握数学建模竞赛的具体流程与分工;③学习如何将实际问题转化为数学模型并求解;④获取实战经验和常见错误规避方法。; 其他说明:文档不仅提供了理论知识,还结合具体实例和代码片段帮助读者更好地理解和实践建模过程。建议新手从中小型赛事开始积累经验,逐步提升技能水平。

    protobuf-6.30.1-cp310-abi3-win32.whl

    该资源为protobuf-6.30.1-cp310-abi3-win32.whl,欢迎下载使用哦!

    大数据环境构建:从虚拟机创建到Ambari集群部署的技术指南

    内容概要:本文档详细介绍了基于Linux系统的大数据环境搭建流程,涵盖从虚拟机创建到集群建立的全过程。首先,通过一系列步骤创建并配置虚拟机,包括设置IP地址、安装MySQL数据库等操作。接着,重点讲解了Ambari的安装与配置,涉及关闭防火墙、设置免密登录、安装时间同步服务(ntp)、HTTP服务以及配置YUM源等关键环节。最后,完成了Ambari数据库的创建、JDK的安装、Ambari server和agent的部署,并指导用户创建集群。整个过程中还提供了针对可能出现的问题及其解决方案,确保各组件顺利安装与配置。 适合人群:具有Linux基础操作技能的数据工程师或运维人员,尤其是那些需要构建和管理大数据平台的专业人士。 使用场景及目标:适用于希望快速搭建稳定可靠的大数据平台的企业或个人开发者。通过本指南可以掌握如何利用Ambari工具自动化部署Hadoop生态系统中的各个组件,从而提高工作效率,降低维护成本。 其他说明:文档中包含了大量具体的命令行指令和配置细节,建议读者按照顺序逐步操作,并注意记录下重要的参数值以便后续参考。此外,在遇到问题时可参照提供的解决方案进行排查,必要时查阅官方文档获取更多信息。

    MATLAB中基于LMS算法的一维时间序列信号降噪技术及其实现

    内容概要:本文详细介绍了如何在MATLAB R2018A中使用最小均方(LMS)自适应滤波算法对一维时间序列信号进行降噪处理,特别是针对心电图(ECG)信号的应用。首先,通过生成模拟的ECG信号并加入随机噪声,创建了一个带有噪声的时间序列。然后,实现了LMS算法的核心部分,包括滤波器阶数、步长参数的选择以及权重更新规则的设计。文中还提供了详细的代码示例,展示了如何构建和训练自适应滤波器,并通过图形化方式比较了原始信号、加噪信号与经过LMS处理后的降噪信号之间的差异。此外,作者分享了一些实用的经验和技术要点,如参数选择的影响、误差曲线的解读等。 适用人群:适用于具有一定MATLAB编程基础并对信号处理感兴趣的科研人员、工程师或学生。 使用场景及目标:本教程旨在帮助读者掌握LMS算法的基本原理及其在实际项目中的应用方法,特别是在生物医学工程、机械故障诊断等领域中处理含噪信号的任务。同时,也为进一步探索其他类型的自适应滤波技术和扩展到不同的信号处理任务奠定了基础。 其他说明:尽管LMS算法在处理平稳噪声方面表现出色,但在面对突发性的强干扰时仍存在一定局限性。因此,在某些特殊场合下,可能需要与其他滤波技术相结合以获得更好的效果。

    基于TMS320F2812的光伏并网逆变器设计与MATLAB仿真及DSP代码实现

    内容概要:本文详细介绍了基于TMS320F2812 DSP芯片的光伏并网逆变器设计方案,涵盖了主电路架构、控制算法、锁相环实现、环流抑制等多个关键技术点。首先,文中阐述了双级式结构的主电路设计,前级Boost升压将光伏板输出电压提升至约600V,后级采用三电平NPC拓扑的IGBT桥进行逆变。接着,深入探讨了核心控制算法,如电流PI调节器、锁相环(SOFGI)、环流抑制等,并提供了详细的MATLAB仿真模型和DSP代码实现。此外,还特别强调了PWM死区时间配置、ADC采样时序等问题的实际解决方案。最终,通过实验验证,该方案实现了THD小于3%,MPPT效率达98.7%,并有效降低了并联环流。 适合人群:从事光伏并网逆变器开发的电力电子工程师和技术研究人员。 使用场景及目标:适用于光伏并网逆变器的研发阶段,帮助工程师理解和实现高效稳定的逆变器控制系统,提高系统的性能指标,减少开发过程中常见的错误。 其他说明:文中提供的MATLAB仿真模型和DSP代码可以作为实际项目开发的重要参考资料,有助于缩短开发周期,提高成功率。

    三菱FX3U PLC在六轴自动包装机中的伺服控制与定位程序解析

    内容概要:本文详细解析了三菱FX3U PLC在六轴自动包装机中的应用,涵盖硬件配置、程序框架、伺服定位控制、手自动切换逻辑、功能块应用以及报警处理等方面。硬件方面,采用FX3U-48MT主模块自带三轴脉冲输出,配合三个FX3UG-1PG模块扩展定位功能,使用六个MR-JE-20A伺服驱动器和16点输入扩展模块进行传感器采集。程序框架主要由初始化、模式切换、六轴控制和异常处理组成。伺服定位使用DRVA指令实现双速定位模式,手自动切换逻辑通过功能块封装,确保模式切换顺畅。报警处理模块则利用矩阵扫描方式压缩报警信号,提高IO利用率。此外,程序还包括状态监控设计和原点回归等功能。 适合人群:具备一定PLC编程基础,从事自动化控制领域的工程师和技术人员。 使用场景及目标:适用于六轴自动包装机的设计与调试,帮助工程师理解和掌握三菱FX3U PLC在包装机械中的具体应用,提升系统的可靠性和效率。 其他说明:文中提供了详细的代码示例和注意事项,有助于新手避免常见错误并优化程序性能。

Global site tag (gtag.js) - Google Analytics