Example #1
0
  // fix for 4720897
  // if the jar file resides in a war file, download it to a temp dir
  // so it can be used to generate jardiff
  private String getRealPath(String path) throws IOException {

    URL fileURL = _servletContext.getResource(path);

    File tempDir = (File) _servletContext.getAttribute("javax.servlet.context.tempdir");

    // download file into temp dir
    if (fileURL != null) {
      File newFile = File.createTempFile("temp", ".jar", tempDir);
      if (download(fileURL, newFile)) {
        String filePath = newFile.getPath();
        return filePath;
      }
    }
    return null;
  }
Example #2
0
  private void servletEnv() {
    if (!log.isDebugEnabled()) return;

    try {
      java.net.URL url = servletContext.getResource("/");
      log.trace("Joseki base directory: " + url);
    } catch (Exception ex) {
    }

    if (servletConfig != null) {
      String tmp = servletConfig.getServletName();
      log.trace("Servlet = " + (tmp != null ? tmp : "<null>"));
      @SuppressWarnings("unchecked")
      Enumeration<String> en = servletConfig.getInitParameterNames();

      for (; en.hasMoreElements(); ) {
        String s = en.nextElement();
        log.trace("Servlet parameter: " + s + " = " + servletConfig.getInitParameter(s));
      }
    }
    if (servletContext != null) {
      // Name of webapp
      String tmp = servletContext.getServletContextName();
      // msg(Level.FINE, "Webapp = " + (tmp != null ? tmp : "<null>"));
      log.debug("Webapp = " + (tmp != null ? tmp : "<null>"));

      // NB This servlet may not have been loaded as part of a web app
      @SuppressWarnings("unchecked")
      Enumeration<String> en = servletContext.getInitParameterNames();
      for (; en.hasMoreElements(); ) {
        String s = en.nextElement();
        log.debug("Webapp parameter: " + s + " = " + servletContext.getInitParameter(s));
      }
    }
    /*
    for ( Enumeration enum = servletContext.getAttributeNames() ;  enum.hasMoreElements() ; )
    {
        String s = (String)enum.nextElement() ;
        logger.log(LEVEL, "Webapp attribute: "+s+" = "+context.getAttribute(s)) ;
    }
     */
  }
 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);
     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);
 }
Example #4
0
  public static void showServletInfo(HttpServlet servlet, PrintStream out) {
    out.println("Servlet Info");
    out.println(" getServletName(): " + servlet.getServletName());
    out.println(" getRootPath(): " + getRootPath());
    out.println(" Init Parameters:");
    Enumeration params = servlet.getInitParameterNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      out.println("  " + name + ": " + servlet.getInitParameter(name));
    }
    out.println();

    ServletContext context = servlet.getServletContext();
    out.println("Context Info");

    try {
      out.println(" context.getResource('/'): " + context.getResource("/"));
    } catch (java.net.MalformedURLException e) {
    } // cant happen
    out.println(" context.getServerInfo(): " + context.getServerInfo());
    out.println("  name: " + getServerInfoName(context.getServerInfo()));
    out.println("  version: " + getServerInfoVersion(context.getServerInfo()));

    out.println(" context.getInitParameterNames():");
    params = context.getInitParameterNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      out.println("  " + name + ": " + context.getInitParameter(name));
    }

    out.println(" context.getAttributeNames():");
    params = context.getAttributeNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      out.println("  context.getAttribute(\"" + name + "\"): " + context.getAttribute(name));
    }

    out.println();
  }
 /** 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 void doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    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 {
      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
        HttpSession 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");
      // encode the url to prevent spaces from being passed along
      if (urlParams != null) {
        urlParams = urlParams.replace(' ', '+');
      }

      try {
        if (services.has(serviceKey)) {
          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
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          String apikey = "";
          if (service.has("username")) userName = service.getString("username");
          if (service.has("password")) password = service.getString("password");
          if (service.has("apikey")) apikey = service.getString("apikey");
          urlString = serviceURL + apikey;
          if (urlParams != null) urlString += "&" + urlParams;
          if (service.has("xslStyleSheet")) {
            xslURLString = service.getString("xslStyleSheet");
          }
        }
        // code for passing the url directly through instead of using configuration file
        else if (req.getParameter("url") != null) {
          String serviceURL = req.getParameter("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          urlString = serviceURL;
          if (urlParams != null) urlString += urlParams;
        } 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);
      }

      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;
      }
      // 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);
          try {
            out.write(message.getBytes());
            out.flush();
            return;
          } catch (java.io.IOException iox) {
          }
        }
      }
      if (!isPost) {
        xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
      } else {
        if (bodyContent == null)
          getLogger()
              .info(
                  "XmlHttpProxyServlet attempting to post to url "
                      + urlString
                      + " with no body content");
        xhp.doPost(
            urlString,
            out,
            xslInputStream,
            paramsMap,
            bodyContent.toString(),
            req.getContentType(),
            userName,
            password);
      }
    } catch (Exception iox) {
      iox.printStackTrace();
      getLogger().severe("XmlHttpProxyServlet: caught " + iox);
      try {
        writer = res.getWriter();
        writer.write(iox.toString());
        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) {
      }
    }
  }