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



分享到:
评论

相关推荐

    软件工程第三章实验报告.docx

    软件工程第三章实验报告.docx

    第三章-第八节通信礼仪.ppt

    第三章-第八节通信礼仪.ppt

    智能家居股份合作协议.docx

    智能家居股份合作协议.docx

    西门子S7-1200 PLC双轴定位控制在电池焊接中的应用与优化

    内容概要:本文详细介绍了基于西门子S7-1200 PLC的双轴定位控制系统在电池焊接项目中的应用。主要内容涵盖双轴定位算法的设计与实现,包括使用SCL语言编写的运动控制函数块,以及梯形图用于处理IO互锁和焊接时序控制。文中还讨论了威纶通触摸屏的界面设计,如动态元素映射、宏指令的应用,以及电气图纸的安全回路设计。此外,文章分享了多个调试技巧和注意事项,如加速度参数设置、伺服驱动器订货号核对、BOM清单管理等。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是熟悉PLC编程和触摸屏界面设计的专业人士。 使用场景及目标:适用于需要深入了解PLC编程、运动控制算法、触摸屏界面设计及电气图纸绘制的工程项目。目标是提高双轴定位控制系统的精度和稳定性,确保电池焊接的质量和安全性。 其他说明:文中提供了完整的工程文件包下载链接,并强调了在实际应用中需要注意的具体事项,如硬件配置检查、参数调整等。

    Simulink与Carsim联合仿真:基于PID与MPC的自适应巡航控制系统设计与实现

    内容概要:本文详细介绍了如何利用Simulink和Carsim进行联合仿真,实现基于PID(比例-积分-微分)和MPC(模型预测控制)的自适应巡航控制系统。首先阐述了Carsim参数设置的关键步骤,特别是cpar文件的配置,包括车辆基本参数、悬架系统参数和转向系统参数的设定。接着展示了Matlab S函数的编写方法,分别针对PID控制和MPC控制提供了详细的代码示例。随后讨论了Simulink中车辆动力学模型的搭建,强调了模块间的正确连接和参数设置的重要性。最后探讨了远程指导的方式,帮助解决仿真过程中可能出现的问题。 适合人群:从事汽车自动驾驶领域的研究人员和技术人员,尤其是对Simulink和Carsim有一定了解并希望深入学习联合仿真的从业者。 使用场景及目标:适用于需要验证和优化自适应巡航控制、定速巡航及紧急避撞等功能的研究和开发项目。目标是提高车辆行驶的安全性和舒适性,确保控制算法的有效性和可靠性。 其他说明:文中不仅提供了理论知识,还有大量实用的代码示例和避坑指南,有助于读者快速上手并应用于实际工作中。此外,还提到了远程调试技巧,进一步提升了仿真的成功率。

    基于MATLAB/Simulink的变压器励磁涌流仿真模型构建与应用

    内容概要:本文深入探讨了利用MATLAB/Simulink搭建变压器励磁涌流仿真模型的方法和技术。首先介绍了空载合闸励磁涌流仿真模型的搭建步骤,包括选择和配置电源模块、变压器模块以及设置相关参数。文中详细讲解了如何通过代码生成交流电压信号和设置变压器的变比,同时强调了铁芯饱和特性和合闸角控制的重要性。此外,还讨论了电源简化模型的应用及其优势,如使用受控电压源替代复杂电源模块。为了更好地理解和分析仿真结果,文章提供了绘制励磁涌流曲线的具体方法,并展示了如何提取和分析涌流特征量,如谐波含量和谐波畸变率。最后,文章指出通过调整电源和变压器参数,可以实现针对不同应用场景的定制化仿真,从而为实际工程应用提供理论支持和技术指导。 适合人群:从事电力系统研究、变压器设计及相关领域的科研人员、工程师和技术爱好者。 使用场景及目标:适用于希望深入了解变压器励磁涌流特性的研究人员,旨在帮助他们掌握MATLAB/Simulink仿真工具的使用技巧,提高对励磁涌流现象的理解和预测能力,进而优化继电保护系统的设计。 其他说明:文中不仅提供了详细的建模步骤和代码示例,还分享了一些实用的经验和技巧,如考虑磁滞效应对涌流的影响、避免理想断路器带来的误差等。这些内容有助于读者在实践中获得更加准确可靠的仿真结果。

    三菱FX3U PLC与Factory IO通讯仿真PID液位调节程序:低成本高效学习PID控制

    内容概要:本文详细介绍了利用三菱FX3U PLC与Factory IO通讯仿真进行PID液位调节的方法,旨在降低学习PID控制的成本和难度。文中首先指出了传统硬件学习PID控制面临的高昂成本和复杂接线问题,随后介绍了仿真程序的优势,包括PID配置参数、调节参数、自整定和手动整定的学习方法。接着阐述了所需的设备和软件环境,以及具体的代码示例和寄存器配置。最后,通过实例展示了如何通过仿真环境进行PID参数调整和测试,验证了该方案的有效性和实用性。 适合人群:初学者和有一定PLC基础的技术人员,特别是那些希望通过低成本方式学习PID控制的人群。 使用场景及目标:适用于希望在不购买昂贵硬件的情况下,快速掌握PID控制原理和技术的应用场景。目标是通过仿真环境,熟悉PID参数配置和调整,最终能够应用于实际工业控制系统中。 其他说明:本文不仅提供了理论指导,还给出了详细的实践步骤和代码示例,使读者能够在实践中更好地理解和掌握PID控制技术。同时,强调了仿真环境与实际项目的相似性,便于知识迁移。

    智慧城市树木二维码智能管理系统概述.docx

    智慧城市树木二维码智能管理系统概述.docx

    .NET框架下基于Oracle数据库的大型MES生产制造管理系统源码解析与应用

    内容概要:本文详细介绍了基于.NET框架和Oracle数据库构建的大型MES(制造执行系统)生产制造管理系统的源码结构及其技术特点。该系统采用了BS架构,适用于Web端和WPF客户端,涵盖了从数据库设计、业务逻辑处理到前端展示等多个方面。文中不仅提供了具体的代码示例,还深入剖析了系统的技术难点,如Oracle数据库的高效连接方式、多线程处理、实时数据推送以及高级特性(如分区表、压缩技术和批量操作)的应用。此外,作者还分享了一些关于系统部署和维护的经验。 适合人群:主要面向拥有五年以上.NET开发经验的专业人士,特别是那些对Oracle数据库有一定了解并且参与过大中型项目开发的技术人员。 使用场景及目标:①帮助开发者深入了解MES系统的工作原理和技术实现;②为现有的MES系统提供优化思路;③作为学习资料,用于掌握.NET框架与Oracle数据库的最佳实践。 其他说明:尽管缺少完整的安装说明和数据库备份文件,但凭借丰富的代码片段和技术细节,这套源码仍然是一个宝贵的学习资源。同时,文中提到的一些技术点也可以应用于其他类型的工业控制系统或企业管理信息系统。

    lesson6_点阵.zip

    lesson6_点阵.zip

    jicmp(OpenNMS所需重要组件)

    ‌OpenNMS 依赖组件 jicmp 的完整解析与安装指南‌ ‌一、jicmp 的核心作用‌ ‌ICMP 协议支持‌ jicmp(Java Interface for ICMP)是 OpenNMS 实现网络设备可达性检测(如 Ping)的关键组件,通过原生代码高效处理 ICMP 报文,替代纯 Java 实现的性能瓶颈17。 ‌依赖版本要求‌:OpenNMS 33.1.5 需 jicmp >= 3.0.0,以支持 IPv6 及多线程优化7。 ‌与 jicmp6 的协同‌ jicmp6 是 jicmp 的扩展组件,专用于 IPv6 网络环境检测,二者共同构成 OpenNMS 网络监控的底层通信基础78。 ‌二、jicmp 安装问题的根源‌ ‌仓库版本不匹配‌ OpenNMS 官方旧版仓库(如 opennms-repo-stable-rhel6)仅提供 jicmp-2.0.5 及更早版本,无法满足新版 OpenNMS 的依赖需求78。 ‌典型错误‌:Available: jicmp-2.0.5-1.el6.i386,但 Requires: jicmp >= 3.0.07。 ‌手动编译未注册到包管理器‌ 手动编译的 jicmp 未生成 RPM 包,导致 yum 无法识别已安装的依赖,仍尝试从仓库拉取旧版本57。 ‌三、解决方案:正确安装 jicmp 3.0‌ ‌通过源码编译生成 RPM 包‌ bash Copy Code # 安装编译工具链 yum install -y rpm-build checkinstall gcc-c++ autoconf automake libtool # 编译并生成 jicmp-3.0.0 RPM wget https://sourceforge.net/projects/opennms/files/JICMP/stable-3.x/j

    机械CAD零件图.ppt

    机械CAD零件图.ppt

    制冷站智能群控管理系统的技术实现与优化

    内容概要:本文详细介绍了制冷站智能群控管理系统的构成及其核心技术实现。首先阐述了系统的四大组成部分:环境感知模块、数据处理模块、决策控制模块以及设备控制模块。接着通过具体的Python代码示例展示了如何利用MQTT协议进行设备间的通信,实现了温度控制等功能。此外,文中还探讨了数据处理中的噪声过滤方法、设备控制中的状态锁定机制、以及采用强化学习进行能效优化的具体案例。最后展望了未来的发展方向,如引入能量管理和AI集成等。 适合人群:从事制冷站自动化控制领域的工程师和技术人员,尤其是对智能群控管理系统感兴趣的从业者。 使用场景及目标:适用于希望提升制冷站自动化水平的企业和个人。目标在于提高系统的稳定性和效率,减少人为干预,实现节能减排。 其他说明:文章不仅提供了理论性的介绍,还有大量的实战经验和代码片段分享,有助于读者更好地理解和应用相关技术。

    CNN卷积神经网络FPGA加速器实现:从软件到硬件的深度学习部署

    内容概要:本文详细介绍了将卷积神经网络(CNN)从软件到硬件的全过程部署,特别是在FPGA上的实现方法。首先,作者使用TensorFlow 2构建了一个简单的CNN模型,并通过Python代码实现了模型的训练和权值导出。接着,作者用Verilog手写了CNN加速器的硬件代码,展示了如何通过参数化配置优化加速效果。硬件部分采用了滑动窗口和流水线结构,确保高效执行卷积操作。此外,文中还讨论了硬件调试过程中遇到的问题及其解决方案,如ReLU激活函数的零值处理和权值存储顺序的对齐问题。最后,作者强调了参数化设计的重要性,使得硬件可以在速度和面积之间灵活调整。 适合人群:对深度学习和FPGA感兴趣的开发者,尤其是有一定编程基础和技术背景的研究人员。 使用场景及目标:适用于希望深入了解CNN算法硬件实现的人群,目标是掌握从软件到硬件的完整部署流程,以及如何通过FPGA加速深度学习任务。 其他说明:文中提供了详细的代码片段和调试经验,有助于读者更好地理解和实践。同时,项目代码可在GitHub上获取,方便进一步研究和改进。

    无人驾驶车辆高速MPC控制:基于MATLAB与CarSim的双移线场景复现

    内容概要:本文详细介绍了无人驾驶车辆高速MPC(模型预测控制)控制系统的复现过程,主要涉及MATLAB和CarSim软件工具的应用。作者通过调整caraim文件、构建Simulink控制逻辑以及优化MPC算法,将原有的直线跟车场景成功转换为双移线场景。文中不仅展示了具体的技术实现步骤,如路径点设置、权重矩阵调整、采样时间对齐等,还分享了调试过程中遇到的问题及其解决方案,如参数不匹配、模型不收敛等。最终实现了车辆在虚拟环境中按预定双移线轨迹行驶的目标。 适合人群:从事无人驾驶车辆研究和技术开发的专业人士,尤其是对MPC控制算法感兴趣的工程师。 使用场景及目标:适用于需要深入了解无人驾驶车辆控制系统的设计与实现的研究人员和技术开发者。目标是帮助读者掌握如何利用MATLAB和CarSim进行无人驾驶车辆的模拟实验,特别是在高速场景下的双移线控制。 其他说明:文章强调了MPC在高速场景下的挑战性和调参技巧,提供了宝贵的实践经验。同时提醒读者注意环境配置、控制器核心代码解析以及联合仿真可能出现的问题。

    监控场景下基于CLIP的细粒度目标检测方法.pdf

    监控场景下基于CLIP的细粒度目标检测方法.pdf

    MATLAB频谱与功率谱分析:从理论到实践的全面解析

    内容概要:本文详细介绍了如何使用MATLAB进行频谱和功率谱分析,涵盖了从基础概念到高级应用的各个方面。首先,通过生成人工信号并绘制时域图,帮助读者熟悉基本操作。接着,深入探讨了频谱分析的关键步骤,如快速傅里叶变换(FFT)、窗口函数的选择、频谱横坐标的正确转换等。对于功率谱分析,则介绍了Welch法及其具体实现。针对真实数据处理,讨论了如何读取外部数据、处理非均匀采样、去除趋势项等问题,并提供了多种实用技巧,如滑动平均、自动标注主要频率成分等。此外,还强调了一些常见的错误和注意事项,确保读者能够避免常见陷阱。 适用人群:适用于具有一定MATLAB基础的科研人员、工程师和技术爱好者,特别是那些从事信号处理、通信工程、机械振动分析等领域的人士。 使用场景及目标:① 学习如何使用MATLAB进行频谱和功率谱分析;② 掌握处理实际工程中复杂信号的方法;③ 提高对信号特征的理解能力,以便更好地应用于故障诊断、质量检测等实际工作中。 其他说明:文中提供的代码片段可以直接用于实践,读者可以根据自己的需求进行适当修改。通过跟随文中的步骤,读者不仅能够学会如何绘制频谱图和功率谱图,还能深入了解背后的数学原理和技术细节。 标签1,MATLAB,频谱分析,功率谱,Welch法,FFT

    基于FAST与MATLAB/Simulink的5MW风力发电机PID变桨控制联合仿真研究

    内容概要:本文详细介绍了基于FAST与MATLAB/Simulink联合仿真平台,对5MW非线性风力发电机进行统一变桨(CPC)和独立变桨(IPC)控制策略的研究。首先,通过将OpenFAST编译成Simulink可调用的S-Function模块,构建了联合仿真环境。接着,分别实现了统一变桨和独立变桨的PID控制器,并在三维湍流风场中进行了性能测试。结果显示,独立变桨在转速稳定性和载荷控制方面表现出色,能够显著降低叶根挥舞弯矩和偏航力矩,从而提高风机的可靠性和使用寿命。然而,独立变桨也带来了作动器磨损增加的问题。 适合人群:从事风电控制系统设计、仿真建模以及希望深入了解变桨控制策略的研发工程师和技术研究人员。 使用场景及目标:适用于需要评估不同变桨控制策略在复杂风场条件下的性能表现,优化风机运行效率和可靠性,以及探索新的控制算法的应用场景。 其他说明:文中提供了详细的模型搭建步骤、关键代码片段和仿真结果分析,并附有相关参考文献和GitHub资源链接,方便读者进一步深入研究。

    基于S7-200 PLC和组态王的Z35摇臂钻床控制系统设计与实现

    内容概要:本文详细介绍了如何利用S7-200 PLC和组态王软件对Z35摇臂钻床进行控制系统升级改造。主要内容涵盖IO分配、梯形图编程、接线图与原理图设计以及组态王的画面制作。通过合理的IO分配确保信号正确传递,梯形图编程实现了各种控制逻辑,如摇臂上升/下降、主轴启动/停止等,并加入了互锁机制保障安全性。接线图展示了PLC与外部设备的具体连接方式,而原理图则揭示了整个系统的运作机制。组态王创建的人机界面使得操作更加直观便捷。 适合人群:从事工业自动化领域的工程师和技术人员,特别是那些熟悉PLC编程和HMI开发的专业人士。 使用场景及目标:适用于需要对老旧机械设备进行现代化改造的企业或单位,旨在提高生产设备的安全性和工作效率,降低维护成本。 其他说明:文中提供了多个具体的实例和技巧,帮助读者更好地理解和应用相关技术和方法。此外,还分享了一些调试过程中遇到的问题及其解决方案,为实际项目的实施提供宝贵的参考经验。

Global site tag (gtag.js) - Google Analytics