Пример #1
2
  protected void initializeHandlerChain(PicketLinkType picketLinkType) throws Exception {
    SAML2HandlerChain handlerChain;

    // Get the chain from config
    if (isNullOrEmpty(samlHandlerChainClass)) {
      handlerChain = SAML2HandlerChainFactory.createChain();
    } else {
      try {
        handlerChain = SAML2HandlerChainFactory.createChain(this.samlHandlerChainClass);
      } catch (ProcessingException e1) {
        throw new RuntimeException(e1);
      }
    }

    Handlers handlers = picketLinkType.getHandlers();

    if (handlers == null) {
      // Get the handlers
      String handlerConfigFileName = GeneralConstants.HANDLER_CONFIG_FILE_LOCATION;
      handlers =
          ConfigurationUtil.getHandlers(servletContext.getResourceAsStream(handlerConfigFileName));
    }

    picketLinkType.setHandlers(handlers);

    handlerChain.addAll(HandlerUtil.getHandlers(handlers));

    populateChainConfig(picketLinkType);
    SAML2HandlerChainConfig handlerChainConfig =
        new DefaultSAML2HandlerChainConfig(chainConfigOptions);

    Set<SAML2Handler> samlHandlers = handlerChain.handlers();

    for (SAML2Handler handler : samlHandlers) {
      handler.initChainConfig(handlerChainConfig);
    }

    chain = handlerChain;
  }
Пример #2
0
  /**
   * @param context the Servlet context.
   * @deprecated Now handled in TdsContext.init().
   */
  public static void initContext(ServletContext context) {
    //    setContextPath(context);
    if (contextPath == null) {
      // Servlet 2.5 allows the following.
      // contextPath = servletContext.getContextPath();
      String tmpContextPath =
          context.getInitParameter("ContextPath"); // cannot be overridden in the ThreddsConfig file
      if (tmpContextPath == null) tmpContextPath = "thredds";
      contextPath = "/" + tmpContextPath;
    }
    //    setRootPath(context);
    if (rootPath == null) {
      rootPath = context.getRealPath("/");
      rootPath = rootPath.replace('\\', '/');
    }

    //    setContentPath();
    if (contentPath == null) {
      String tmpContentPath = "../../content" + getContextPath() + "/";
      File cf = new File(getRootPath(), tmpContentPath);
      try {
        contentPath = cf.getCanonicalPath() + "/";
        contentPath = contentPath.replace('\\', '/');
      } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
      }
    }

    //    initDebugging(context);
    initDebugging(context);
  }
Пример #3
0
 /** Run once when servlet loaded. */
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   context = config.getServletContext();
   theApp = (LockssApp) context.getAttribute(ServletManager.CONTEXT_ATTR_LOCKSS_APP);
   servletMgr = (ServletManager) context.getAttribute(ServletManager.CONTEXT_ATTR_SERVLET_MGR);
   if (theApp instanceof LockssDaemon) {
     acctMgr = getLockssDaemon().getAccountManager();
   }
 }
Пример #4
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html; charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;
      _jspx_resourceInjector =
          (org.apache.jasper.runtime.ResourceInjector)
              application.getAttribute("com.sun.appserv.jsp.resource.injector");

      out.write('\n');
      out.write('\n');
      out.write("\n<!DOCTYPE html>\n<html>\n<head>\n");
      JspHelper.createTitle(out, request, request.getParameter("filename"));
      out.write("\n</head>\n<body onload=\"document.goto.dir.focus()\">\n");

      Configuration conf = (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF);
      generateFileChunks(out, request, conf);

      out.write("\n<hr>\n");

      generateFileDetails(out, request, conf);

      out.write("\n\n<h2>Local logs</h2>\n<a href=\"/logs/\">Log</a> directory\n\n");

      out.println(ServletUtil.htmlFooter());

      out.write('\n');
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0) out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
Пример #5
0
    public void contextInitialized(ServletContextEvent sce) {
      final ServletContext app = sce.getServletContext();
      final Configuration conf = NutchConfiguration.get(app);

      LOG.info("creating new bean");
      NutchBean bean = null;
      try {
        bean = new NutchBean(conf);
        app.setAttribute(KEY, bean);
      } catch (final IOException ex) {
        LOG.error(StringUtils.stringifyException(ex));
      }
    }
Пример #6
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;
  }
	public File doAttachment(HttpServletRequest request)
			throws ServletException, IOException {
		File file = null;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<?> items = upload.parseRequest(request);
			Iterator<?> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					parameters
							.put(item.getFieldName(), item.getString("UTF-8"));
				} else {
					File tempFile = new File(item.getName());
					file = new File(sc.getRealPath("/") + savePath, tempFile
							.getName());
					item.write(file);
				}
			}
		} catch (Exception e) {
			Logger logger = Logger.getLogger(SendAttachmentMailServlet.class);
			logger.error("邮件发送出了异常", e);
		}
		return file;
	}
 /** Initializes H2 console. */
 private void initH2Console(ServletContext servletContext) {
   log.debug("Initialize H2 console");
   ServletRegistration.Dynamic h2ConsoleServlet =
       servletContext.addServlet("H2Console", new org.h2.server.web.WebServlet());
   h2ConsoleServlet.addMapping("/h2-console/*");
   h2ConsoleServlet.setInitParameter("-properties", "src/main/resources/");
   h2ConsoleServlet.setLoadOnStartup(1);
 }
Пример #9
0
  /** Initialize JarDiff handler */
  public JarDiffHandler(ServletContext servletContext, Logger log) {
    _jarDiffEntries = new HashMap();
    _servletContext = servletContext;
    _log = log;

    _jarDiffMimeType = _servletContext.getMimeType("xyz.jardiff");
    if (_jarDiffMimeType == null) _jarDiffMimeType = JARDIFF_MIMETYPE;
  }
Пример #10
0
 /**
  * Add javascript to page. Normally adds a link to the script file, but can be told to include the
  * script directly in the page, to accomodate unit testing of individual servlets, when other
  * fetches won't work.
  */
 protected void addJavaScript(Composite comp) {
   String include = (String) context.getAttribute(ATTR_INCLUDE_SCRIPT);
   if (StringUtil.isNullString(include)) {
     linkToJavaScript(comp);
   } else {
     includeJavaScript0(comp);
   }
 }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   String title = "Shared Info";
   out.println(
       "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
           + "Transitional//EN\">"
           + "<HTML>\n"
           + "<HEAD><TITLE>"
           + title
           + "</TITLE></HEAD>\n"
           + "<BODY BGCOLOR=\"#FDF5E6\">\n"
           + "<H1 ALIGN=\"CENTER\">"
           + title
           + "</H1>\n"
           + "<UL>\n"
           + "  <LI>Session:");
   HttpSession session = request.getSession(true);
   Enumeration attributes = session.getAttributeNames();
   out.println(getAttributeList(attributes));
   out.println("  <LI>Current Servlet Context:");
   ServletContext application = getServletContext();
   attributes = application.getAttributeNames();
   out.println(getAttributeList(attributes));
   out.println("  <LI>Servlet Context of /shareTest1:");
   application = application.getContext("/shareTest1");
   if (application == null) {
     out.println("Context sharing disabled");
   } else {
     attributes = application.getAttributeNames();
     out.println(getAttributeList(attributes));
   }
   out.println("  <LI>Cookies:<UL>");
   Cookie[] cookies = request.getCookies();
   if ((cookies == null) || (cookies.length == 0)) {
     out.println("    <LI>No cookies found.");
   } else {
     Cookie cookie;
     for (int i = 0; i < cookies.length; i++) {
       cookie = cookies[i];
       out.println("    <LI>" + cookie.getName());
     }
   }
   out.println("    </UL>\n" + "</UL>\n" + "</BODY></HTML>");
 }
Пример #12
0
  private Element getDescription(String task) {

    if (task != null) {

      if (task.equals("define")) return definer.getDescription();

      if (task.equals("compare")) return comparer.getDescription();

      if (task.equals("search")) return searcher.getDescription();

      if (task.equals("wikify")) return wikifier.getDescription();
    }

    Element description = doc.createElement("Description");

    description.appendChild(
        createElement(
            "Details",
            "<p>This servlet provides a range of services for mining information from Wikipedia. Further details depend on what you want to do.</p>"
                + "<p>You can <a href=\""
                + context.getInitParameter("service_name")
                + "?task=search&help\">search for pages</a>, <a href=\""
                + context.getInitParameter("service_name")
                + "?task=compare&help\">measure how terms or articles related to each other</a>, <a href=\""
                + context.getInitParameter("service_name")
                + "?task=define&help\">obtain short definitions from articles</a>, and <a href=\""
                + context.getInitParameter("service_name")
                + "?task=wikify&help\">detect topics in web pages</a>.</p>"));

    Element paramTask =
        createElement(
            "Parameter",
            "Specifies what you want to do: can be <em>search</em>, <em>compare</em>, <em>define</em>, or <em>wikify</em>");
    paramTask.setAttribute("name", "task");
    description.appendChild(paramTask);

    Element paramId = doc.createElement("Parameter");
    paramId.setAttribute("name", "help");
    paramId.appendChild(doc.createTextNode("Specifies that you want help about the service."));
    description.appendChild(paramId);

    return description;
  }
Пример #13
0
  /** Initializes the caching HTTP Headers Filter. */
  private void initCachingHttpHeadersFilter(
      ServletContext servletContext, EnumSet<DispatcherType> disps) {
    log.debug("Registering Caching HTTP Headers Filter");
    FilterRegistration.Dynamic cachingHttpHeadersFilter =
        servletContext.addFilter("cachingHttpHeadersFilter", new CachingHttpHeadersFilter(env));

    cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/dist/assets/*");
    cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/dist/scripts/*");
    cachingHttpHeadersFilter.setAsyncSupported(true);
  }
Пример #14
0
  public static void initDebugging(ServletContext webapp) {
    if (isDebugInit) return;
    isDebugInit = true;

    String debugOn = webapp.getInitParameter("DebugOn");
    if (debugOn != null) {
      StringTokenizer toker = new StringTokenizer(debugOn);
      while (toker.hasMoreTokens()) Debug.set(toker.nextToken(), true);
    }
  }
Пример #15
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)) ;
    }
     */
  }
  /** Initializes Metrics. */
  private void initMetrics(ServletContext servletContext, EnumSet<DispatcherType> disps) {
    log.debug("Initializing Metrics registries");
    servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, metricRegistry);
    servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);

    log.debug("Registering Metrics Filter");
    FilterRegistration.Dynamic metricsFilter =
        servletContext.addFilter("webappMetricsFilter", new InstrumentedFilter());

    metricsFilter.addMappingForUrlPatterns(disps, true, "/*");
    metricsFilter.setAsyncSupported(true);

    log.debug("Registering Metrics Servlet");
    ServletRegistration.Dynamic metricsAdminServlet =
        servletContext.addServlet("metricsServlet", new MetricsServlet());

    metricsAdminServlet.addMapping("/management/jhipster/metrics/*");
    metricsAdminServlet.setAsyncSupported(true);
    metricsAdminServlet.setLoadOnStartup(2);
  }
Пример #17
0
  @Override
  public Set<String> getResourcePaths(String s) {
    final String pluginPath = "/plugins/" + pluginManager.getName(plugin) + "/";
    final Set<String> proxyResults = proxy.getResourcePaths(pluginPath + s);
    final Set<String> results = new HashSet<>();
    for (final String proxyResult : proxyResults) {
      results.add(proxyResult.replaceFirst(pluginPath, ""));
    }

    return results;
  }
 // Added in Servlet 2.5
 public String getContextPath() {
   try {
     Method getContextPathMethod =
         servletContext.getClass().getMethod("getContextPath", (Class<?>[]) null); // $NON-NLS-1$
     return (String) getContextPathMethod.invoke(servletContext, (Object[]) null)
         + proxyContext.getServletPath();
   } catch (Exception e) {
     // ignore
   }
   return null;
 }
Пример #19
0
  /**
   * Initializes the servlet context, based on the servlet context. Parses all context parameters
   * and passes them on to the database context.
   *
   * @param sc servlet context
   * @throws IOException I/O exception
   */
  static synchronized void init(final ServletContext sc) throws IOException {
    // skip process if context has already been initialized
    if (context != null) return;

    // set servlet path as home directory
    final String path = sc.getRealPath("/");
    System.setProperty(Prop.PATH, path);

    // parse all context parameters
    final HashMap<String, String> map = new HashMap<String, String>();
    // store default web root
    map.put(MainProp.HTTPPATH[0].toString(), path);

    final Enumeration<?> en = sc.getInitParameterNames();
    while (en.hasMoreElements()) {
      final String key = en.nextElement().toString();
      if (!key.startsWith(Prop.DBPREFIX)) continue;

      // only consider parameters that start with "org.basex."
      String val = sc.getInitParameter(key);
      if (eq(key, DBUSER, DBPASS, DBMODE, DBVERBOSE)) {
        // store servlet-specific parameters as system properties
        System.setProperty(key, val);
      } else {
        // prefix relative paths with absolute servlet path
        if (key.endsWith("path") && !new File(val).isAbsolute()) {
          val = path + File.separator + val;
        }
        // store remaining parameters (without project prefix) in map
        map.put(key.substring(Prop.DBPREFIX.length()).toUpperCase(Locale.ENGLISH), val);
      }
    }
    context = new Context(map);

    if (SERVER.equals(System.getProperty(DBMODE))) {
      new BaseXServer(context);
    } else {
      context.log = new Log(context);
    }
  }
Пример #20
0
  /** Initializes the static resources production Filter. */
  private void initStaticResourcesProductionFilter(
      ServletContext servletContext, EnumSet<DispatcherType> disps) {

    log.debug("Registering static resources production Filter");
    FilterRegistration.Dynamic staticResourcesProductionFilter =
        servletContext.addFilter(
            "staticResourcesProductionFilter", new StaticResourcesProductionFilter());

    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/index.html");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/assets/*");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
    staticResourcesProductionFilter.setAsyncSupported(true);
  }
 /** 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;
 }
Пример #22
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // get the number of workers to run
    int count = this.getRequestedCount(request, 4);
    // get the executor service
    final ServletContext sc = this.getServletContext();
    final ExecutorService executorService = (ExecutorService) sc.getAttribute("myExecutorService");
    // create work coordinator
    CountDownLatch countDownLatch = new CountDownLatch(count);

    Long t1 = System.nanoTime();
    // create the workers
    List<RunnableWorkUnit2> workers = new ArrayList<RunnableWorkUnit2>();
    for (int i = 0; i < count; i++) {
      RunnableWorkUnit2 wu =
          new RunnableWorkUnit2("RunnableTask" + String.valueOf(i + 1), countDownLatch);
      workers.add(wu);
    }
    // run the workers through the executor
    for (RunnableWorkUnit2 wu : workers) {
      executorService.execute(wu);
    }

    try {
      System.out.println("START WAITING");
      countDownLatch.await();
      System.out.println("DONE WAITING");
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }

    Long t2 = System.nanoTime();
    Writer w = response.getWriter();
    w.write(String.format("\n Request processed in %dms!", (t2 - t1) / 1000000));
    w.flush();
    w.close();
  }
Пример #23
0
  /**
   * Initializes the database context, based on the initial servlet context. Parses all context
   * parameters and passes them on to the database context.
   *
   * @param sc servlet context
   * @throws IOException I/O exception
   */
  public static synchronized void init(final ServletContext sc) throws IOException {
    // check if HTTP context has already been initialized
    if (init) return;
    init = true;

    // set web application path as home directory and HTTPPATH
    final String webapp = sc.getRealPath("/");
    Options.setSystem(Prop.PATH, webapp);
    Options.setSystem(GlobalOptions.WEBPATH, webapp);

    // bind all parameters that start with "org.basex." to system properties
    final Enumeration<String> en = sc.getInitParameterNames();
    while (en.hasMoreElements()) {
      final String key = en.nextElement();
      if (!key.startsWith(Prop.DBPREFIX)) continue;

      String val = sc.getInitParameter(key);
      if (key.endsWith("path") && !new File(val).isAbsolute()) {
        // prefix relative path with absolute servlet path
        Util.debug(key.toUpperCase(Locale.ENGLISH) + ": " + val);
        val = new IOFile(webapp, val).path();
      }
      Options.setSystem(key, val);
    }

    // create context, update options
    if (context == null) {
      context = new Context(false);
    } else {
      context.globalopts.setSystem();
      context.options.setSystem();
    }

    // start server instance
    if (!context.globalopts.get(GlobalOptions.HTTPLOCAL)) new BaseXServer(context);
  }
Пример #24
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();
  }
 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);
 }
Пример #26
0
  protected void processConfiguration(FilterConfig filterConfig) {
    InputStream is;

    if (isNullOrEmpty(this.configFile)) {
      is = servletContext.getResourceAsStream(CONFIG_FILE_LOCATION);
    } else {
      try {
        is = new FileInputStream(this.configFile);
      } catch (FileNotFoundException e) {
        throw logger.samlIDPConfigurationError(e);
      }
    }

    PicketLinkType picketLinkType;

    String configurationProviderName = filterConfig.getInitParameter(CONFIGURATION_PROVIDER);

    if (configurationProviderName != null) {
      try {
        Class<?> clazz = SecurityActions.loadClass(getClass(), configurationProviderName);

        if (clazz == null) {
          throw new ClassNotFoundException(ErrorCodes.CLASS_NOT_LOADED + configurationProviderName);
        }

        this.configProvider = (SAMLConfigurationProvider) clazz.newInstance();
      } catch (Exception e) {
        throw new RuntimeException(
            "Could not create configuration provider [" + configurationProviderName + "].", e);
      }
    }

    try {
      // Work on the IDP Configuration
      if (configProvider != null) {
        try {
          if (is == null) {
            // Try the older version
            is =
                servletContext.getResourceAsStream(
                    GeneralConstants.DEPRECATED_CONFIG_FILE_LOCATION);

            // Additionally parse the deprecated config file
            if (is != null && configProvider instanceof AbstractSAMLConfigurationProvider) {
              ((AbstractSAMLConfigurationProvider) configProvider).setConfigFile(is);
            }
          } else {
            // Additionally parse the consolidated config file
            if (is != null && configProvider instanceof AbstractSAMLConfigurationProvider) {
              ((AbstractSAMLConfigurationProvider) configProvider).setConsolidatedConfigFile(is);
            }
          }

          picketLinkType = configProvider.getPicketLinkConfiguration();
          picketLinkType.setIdpOrSP(configProvider.getSPConfiguration());
        } catch (ProcessingException e) {
          throw logger.samlSPConfigurationError(e);
        } catch (ParsingException e) {
          throw logger.samlSPConfigurationError(e);
        }
      } else {
        if (is != null) {
          try {
            picketLinkType = ConfigurationUtil.getConfiguration(is);
          } catch (ParsingException e) {
            logger.trace(e);
            throw logger.samlSPConfigurationError(e);
          }
        } else {
          is = servletContext.getResourceAsStream(GeneralConstants.DEPRECATED_CONFIG_FILE_LOCATION);
          if (is == null) {
            throw logger.configurationFileMissing(configFile);
          }

          picketLinkType = new PicketLinkType();

          picketLinkType.setIdpOrSP(ConfigurationUtil.getSPConfiguration(is));
        }
      }

      // Close the InputStream as we no longer need it
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          // ignore
        }
      }

      Boolean enableAudit = picketLinkType.isEnableAudit();

      // See if we have the system property enabled
      if (!enableAudit) {
        String sysProp = SecurityActions.getSystemProperty(GeneralConstants.AUDIT_ENABLE, "NULL");
        if (!"NULL".equals(sysProp)) {
          enableAudit = Boolean.parseBoolean(sysProp);
        }
      }

      if (enableAudit) {
        if (auditHelper == null) {
          String securityDomainName = PicketLinkAuditHelper.getSecurityDomainName(servletContext);

          auditHelper = new PicketLinkAuditHelper(securityDomainName);
        }
      }

      SPType spConfiguration = (SPType) picketLinkType.getIdpOrSP();
      processIdPMetadata(spConfiguration);

      this.serviceURL = spConfiguration.getServiceURL();
      this.canonicalizationMethod = spConfiguration.getCanonicalizationMethod();
      this.picketLinkConfiguration = picketLinkType;

      this.issuerID = filterConfig.getInitParameter(ISSUER_ID);
      this.characterEncoding = filterConfig.getInitParameter(CHARACTER_ENCODING);
      this.samlHandlerChainClass = filterConfig.getInitParameter(SAML_HANDLER_CHAIN_CLASS);

      logger.samlSPSettingCanonicalizationMethod(canonicalizationMethod);
      XMLSignatureUtil.setCanonicalizationMethodType(canonicalizationMethod);

      try {
        this.initKeyProvider();
        this.initializeHandlerChain(picketLinkType);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }

      logger.trace("Identity Provider URL=" + getConfiguration().getIdentityURL());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Пример #27
0
 /**
  * Returns the cached instance in the servlet context.
  *
  * @see NutchBeanConstructor
  */
 public static NutchBean get(ServletContext app, Configuration conf) throws IOException {
   final NutchBean bean = (NutchBean) app.getAttribute(KEY);
   return bean;
 }
  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) {
      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) {
      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.");
      }
    }
    // 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();
    }
  }
  /** Business logic to execute. */
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    String serverLanguageId = ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId();
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      conn = ConnectionManager.getConnection(context);

      // fires the GenericEvent.CONNECTION_CREATED event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.CONNECTION_CREATED,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  null));
      DetailSaleDocVO docVO = (DetailSaleDocVO) inputPar;

      // retrieve internationalization settings (Resources object)...
      ServerResourcesFactory factory =
          (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY);
      Resources resources = factory.getResources(userSessionPars.getLanguageId());

      // insert header...
      docVO.setDocStateDOC01(ApplicationConsts.HEADER_BLOCKED);
      Response res =
          insDocBean.insertSaleDoc(
              conn, docVO, userSessionPars, request, response, userSession, context);
      if (res.isError()) {
        conn.rollback();
        return res;
      }

      SaleDocPK refPK =
          new SaleDocPK(
              docVO.getCompanyCodeSys01Doc01DOC01(),
              docVO.getDocTypeDoc01DOC01(),
              docVO.getDocYearDoc01DOC01(),
              docVO.getDocNumberDoc01DOC01());

      // retrieve ref. document item rows...
      GridParams gridParams = new GridParams();
      gridParams.getOtherGridParams().put(ApplicationConsts.SALE_DOC_PK, refPK);
      res =
          rowsAction.executeCommand(
              gridParams, userSessionPars, request, response, userSession, context);
      if (res.isError()) {
        conn.rollback();
        return res;
      }
      java.util.List rows = ((VOListResponse) res).getRows();

      // create rows..
      GridSaleDocRowVO gridRowVO = null;
      DetailSaleDocRowVO rowVO = null;
      java.util.List discRows = null;
      SaleDocRowPK docRowPK = null;
      SaleItemDiscountVO itemDiscVO = null;
      gridParams = new GridParams();
      for (int i = 0; i < rows.size(); i++) {
        gridRowVO = (GridSaleDocRowVO) rows.get(i);

        // retrieve row detail...
        docRowPK =
            new SaleDocRowPK(
                gridRowVO.getCompanyCodeSys01DOC02(),
                gridRowVO.getDocTypeDOC02(),
                gridRowVO.getDocYearDOC02(),
                gridRowVO.getDocNumberDOC02(),
                gridRowVO.getItemCodeItm01DOC02(),
                gridRowVO.getVariantTypeItm06DOC02(),
                gridRowVO.getVariantCodeItm11DOC02(),
                gridRowVO.getVariantTypeItm07DOC02(),
                gridRowVO.getVariantCodeItm12DOC02(),
                gridRowVO.getVariantTypeItm08DOC02(),
                gridRowVO.getVariantCodeItm13DOC02(),
                gridRowVO.getVariantTypeItm09DOC02(),
                gridRowVO.getVariantCodeItm14DOC02(),
                gridRowVO.getVariantTypeItm10DOC02(),
                gridRowVO.getVariantCodeItm15DOC02());

        res =
            rowAction.executeCommand(
                docRowPK, userSessionPars, request, response, userSession, context);
        if (res.isError()) {
          conn.rollback();
          return res;
        }
        rowVO = (DetailSaleDocRowVO) ((VOResponse) res).getVo();
        rowVO.setDocTypeDOC02(docVO.getDocTypeDOC01());
        rowVO.setDocNumberDOC02(docVO.getDocNumberDOC01());
        if (rowVO.getInvoiceQtyDOC02().doubleValue() < rowVO.getQtyDOC02().doubleValue()
            && rowVO.getQtyDOC02().doubleValue() == rowVO.getOutQtyDOC02().doubleValue()) {
          rowVO.setQtyDOC02(
              rowVO
                  .getQtyDOC02()
                  .subtract(
                      rowVO
                          .getInvoiceQtyDOC02()
                          .setScale(
                              rowVO.getDecimalsReg02DOC02().intValue(), BigDecimal.ROUND_HALF_UP)));
          rowVO.setTaxableIncomeDOC02(
              rowVO
                  .getQtyDOC02()
                  .multiply(rowVO.getValueSal02DOC02())
                  .setScale(docVO.getDecimalsREG03().intValue(), BigDecimal.ROUND_HALF_UP));
          rowVO.setTotalDiscountDOC02(new BigDecimal(0));

          // calculate row vat...
          double vatPerc =
              rowVO.getValueReg01DOC02().doubleValue()
                  * (1d - rowVO.getDeductibleReg01DOC02().doubleValue() / 100d)
                  / 100;
          rowVO.setVatValueDOC02(
              rowVO
                  .getTaxableIncomeDOC02()
                  .multiply(new BigDecimal(vatPerc))
                  .setScale(docVO.getDecimalsREG03().intValue(), BigDecimal.ROUND_HALF_UP));

          // calculate row total...
          rowVO.setValueDOC02(rowVO.getTaxableIncomeDOC02().add(rowVO.getVatValueDOC02()));

          res =
              insRowBean.insertSaleItem(
                  conn, rowVO, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }

          // create item discounts...
          gridParams.getOtherGridParams().put(ApplicationConsts.SALE_DOC_ROW_PK, docRowPK);
          res =
              itemDiscAction.executeCommand(
                  gridParams, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
          discRows = ((VOListResponse) res).getRows();
          for (int j = 0; j < discRows.size(); j++) {
            itemDiscVO = (SaleItemDiscountVO) discRows.get(j);
            itemDiscVO.setDocTypeDOC04(docVO.getDocTypeDOC01());
            itemDiscVO.setDocNumberDOC04(docVO.getDocNumberDOC01());
            res =
                insItemDiscBean.insertSaleDocRowDiscount(
                    conn, itemDiscVO, userSessionPars, request, response, userSession, context);
            if (res.isError()) {
              conn.rollback();
              return res;
            }
          }
        }
      }

      // create charges...
      gridParams = new GridParams();
      gridParams.getOtherGridParams().put(ApplicationConsts.SALE_DOC_PK, refPK);
      res =
          chargesAction.executeCommand(
              gridParams, userSessionPars, request, response, userSession, context);
      SaleDocChargeVO chargeVO = null;
      if (res.isError()) {
        conn.rollback();
        return res;
      }
      rows = ((VOListResponse) res).getRows();
      for (int i = 0; i < rows.size(); i++) {
        chargeVO = (SaleDocChargeVO) rows.get(i);
        chargeVO.setDocTypeDOC03(docVO.getDocTypeDOC01());
        chargeVO.setDocNumberDOC03(docVO.getDocNumberDOC01());
        if (chargeVO.getValueDOC03() == null
            || chargeVO.getValueDOC03() != null
                && chargeVO.getInvoicedValueDOC03().doubleValue()
                    < chargeVO.getValueDOC03().doubleValue()) {
          if (chargeVO.getValueDOC03() != null)
            chargeVO.setValueDOC03(
                chargeVO
                    .getValueDOC03()
                    .subtract(chargeVO.getInvoicedValueDOC03())
                    .setScale(docVO.getDecimalsREG03().intValue(), BigDecimal.ROUND_HALF_UP));

          res =
              insChargeBean.insertSaleDocCharge(
                  conn, chargeVO, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
        }
      }

      // create activities...
      res =
          actAction.executeCommand(
              gridParams, userSessionPars, request, response, userSession, context);
      if (res.isError()) {
        conn.rollback();
        return res;
      }
      SaleDocActivityVO actVO = null;
      rows = ((VOListResponse) res).getRows();
      for (int i = 0; i < rows.size(); i++) {
        actVO = (SaleDocActivityVO) rows.get(i);
        actVO.setDocTypeDOC13(docVO.getDocTypeDOC01());
        actVO.setDocNumberDOC13(docVO.getDocNumberDOC01());
        if (actVO.getInvoicedValueDOC13().doubleValue() < actVO.getValueDOC13().doubleValue()) {
          actVO.setValueDOC13(
              actVO
                  .getValueDOC13()
                  .subtract(actVO.getInvoicedValueDOC13())
                  .setScale(docVO.getDecimalsREG03().intValue(), BigDecimal.ROUND_HALF_UP));
          res =
              insActBean.insertSaleActivity(
                  conn, actVO, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
        }
      }

      // create header discounts...
      res =
          discAction.executeCommand(
              gridParams, userSessionPars, request, response, userSession, context);
      if (res.isError()) {
        conn.rollback();
        return res;
      }
      SaleDocDiscountVO discVO = null;
      rows = ((VOListResponse) res).getRows();
      for (int i = 0; i < rows.size(); i++) {
        discVO = (SaleDocDiscountVO) rows.get(i);
        discVO.setDocTypeDOC05(docVO.getDocTypeDOC01());
        discVO.setDocNumberDOC05(docVO.getDocNumberDOC01());
        res =
            insDiscBean.insertSaleDocDiscount(
                conn, discVO, userSessionPars, request, response, userSession, context);
        if (res.isError()) {
          conn.rollback();
          return res;
        }
      }

      // recalculate all taxable incomes, vats, totals...
      SaleDocPK pk =
          new SaleDocPK(
              docVO.getCompanyCodeSys01DOC01(),
              docVO.getDocTypeDOC01(),
              docVO.getDocYearDOC01(),
              docVO.getDocNumberDOC01());
      res =
          totals.updateTaxableIncomes(
              conn, pk, userSessionPars, request, response, userSession, context);
      if (res.isError()) {
        conn.rollback();
        return res;
      }

      // reload doc header with updated totals...
      Response answer =
          docAction.loadSaleDoc(conn, pk, userSessionPars, request, response, userSession, context);

      // fires the GenericEvent.BEFORE_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.BEFORE_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      conn.commit();

      // fires the GenericEvent.AFTER_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.AFTER_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while creating a sale invoice from a sale document",
          ex);
      try {
        conn.rollback();
      } catch (Exception ex3) {
      }
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }

      try {
        ConnectionManager.releaseConnection(conn, context);
      } catch (Exception ex1) {
      }
    }
  }
  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) {
      }
    }
  }