@DataBoundConstructor
  public WwpassSecurityRealm(String certFile, String keyFile, String name, boolean allowsSignup) {

    this.disableSignup = !allowsSignup;

    this.name = name;

    if (certFile != null && !certFile.isEmpty() && keyFile != null && !keyFile.isEmpty()) {
      this.certFile = certFile;
      this.keyFile = keyFile;
    } else {
      if (System.getProperty("os.name").startsWith("Windows")) {
        this.certFile = DEFAULT_CERT_FILE_WINDOWS;
        this.keyFile = DEFAULT_KEY_FILE_WINDOWS;
      } else if (System.getProperty("os.name").startsWith("Linux")) {
        this.certFile = DEFAULT_CERT_FILE_LINUX;
        this.keyFile = DEFAULT_KEY_FILE_LINUX;
      } else {
        LOGGER.severe(Messages.WwpassSession_UnsupportedOsError());
        throw new Failure(Messages.WwpassSession_AuthError());
      }
    }

    if (!hasSomeUser()) {
      // if Hudson is newly set up with the security realm and there's no user account created yet,
      // insert a filter that asks the user to create one
      try {
        PluginServletFilter.addFilter(CREATE_FIRST_USER_FILTER);
      } catch (ServletException e) {
        throw new AssertionError(e); // never happen because our Filter.init is no-op
      }
    }
  }
예제 #2
0
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @throws IOException I/O exception
   */
  public HTTPContext(final HttpServletRequest rq, final HttpServletResponse rs) throws IOException {

    req = rq;
    res = rs;
    final String m = rq.getMethod();
    method = HTTPMethod.get(m);

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log(false, m, uri);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);

    segments = toSegments(req.getPathInfo());
    path = join(0);

    user = System.getProperty(DBUSER);
    pass = System.getProperty(DBPASS);

    // set session-specific credentials
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
  @Override
  public void init(FilterConfig fc) throws ServletException {
    log.info("DispatcherFilter starting ...");
    log.info("java.version = {}", JdkUtils.JAVA_VERSION);
    log.info("webmvc.version = {}", WebConfig.VERSION);
    log.info("user.dir = {}", System.getProperty("user.dir"));
    log.info("java.io.tmpdir = {}", System.getProperty("java.io.tmpdir"));
    log.info("user.timezone = {}", System.getProperty("user.timezone"));
    log.info("file.encoding = {}", System.getProperty("file.encoding"));

    try {
      long ts = System.currentTimeMillis();

      ServletContext sc = fc.getServletContext();
      String configLocation = fc.getInitParameter("configLocation");
      WebInitializer.initialize(sc, configLocation);

      httpEncoding = WebConfig.getHttpEncoding();
      httpCache = WebConfig.isHttpCache();
      router = WebConfig.getRouter();
      bypassRequestUrls = WebConfig.getBypassRequestUrls();
      corsRequestProcessor = WebConfig.getCORSRequestProcessor();
      resultHandlerResolver = WebConfig.getResultHandlerResolver();
      fileUploadResolver = WebConfig.getFileUploadResolver();
      exceptionHandler = WebConfig.getExceptionHandler();

      log.info("web.root = {}", WebConfig.getWebroot());
      log.info("web.development = {}", WebConfig.isDevelopment());
      log.info("web.upload.dir = {}", WebConfig.getUploaddir());
      log.info("web.urls.router = {}", router.getClass().getName());
      log.info(
          "web.urls.bypass = {}",
          (bypassRequestUrls == null) ? null : bypassRequestUrls.getClass().getName());
      log.info(
          "web.urls.cors = {}",
          (corsRequestProcessor == null) ? null : corsRequestProcessor.getClass().getName());

      for (Plugin plugin : WebConfig.getPlugins()) {
        log.info("load plugin: {}", plugin.getClass().getName());
        plugin.initialize();
      }

      for (Interceptor interceptor : WebConfig.getInterceptors()) {
        log.info("load interceptor: {}", interceptor.getClass().getName());
        interceptor.initialize();
      }

      log.info(
          "DispatcherFilter initialize successfully, Time elapsed: {} ms.",
          System.currentTimeMillis() - ts);

    } catch (Exception e) {
      log.error("Failed to initialize DispatcherFilter", e);
      log.error("*************************************");
      log.error("          System.exit(1)             ");
      log.error("*************************************");
      System.exit(1);
    }
  }
예제 #4
0
  /** @param e */
  @Override
  public void contextInitialized(ServletContextEvent e) {
    ServletContext context = e.getServletContext();

    // retrieve jyro.home
    String dirName = context.getInitParameter(Jyro.JYRO_HOME);
    if (dirName == null) {
      dirName = System.getProperty(Jyro.JYRO_HOME);
      if (dirName == null) {
        throw new IllegalStateException(
            Jyro.JYRO_HOME + " not specified in servlet or context paramter, system property");
      }
    }

    // resolve relative path
    File dir = new File(dirName);
    if (!dir.isAbsolute()) {
      dirName = context.getRealPath(dirName);
      dir = new File(dirName);
    }
    logger.info(Jyro.JYRO_HOME + "=" + dirName);

    // build and startup Jyro
    String contextPath = context.getContextPath();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try {
      platform = new JyroPlatform(contextPath, dir, loader, null);
      platform.startup();
    } catch (Exception ex) {
      throw new IllegalStateException(ex);
    }
  }
예제 #5
0
  public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
    String configFile = System.getProperty("jboss.server.config.dir") + "/picketlink.xml";
    if (new File(configFile).exists()) this.configFile = configFile;

    this.servletContext = filterConfig.getServletContext();
    processConfiguration(filterConfig);
  }
예제 #6
0
 // For war agent needs to be switched on
 private boolean listenForDiscoveryMcRequests(Configuration pConfig) {
   // Check for system props, system env and agent config
   boolean sysProp =
       System.getProperty("jolokia." + ConfigKey.DISCOVERY_ENABLED.getKeyValue()) != null;
   boolean env = System.getenv("JOLOKIA_DISCOVERY") != null;
   boolean config = pConfig.getAsBoolean(ConfigKey.DISCOVERY_ENABLED);
   return sysProp || env || config;
 }
예제 #7
0
 public void test_init_absolutePath() throws ServletException {
   String os = System.getProperty("os.name");
   if (os.startsWith("Windows")) {
     config.parameterValue = "C:/Temp";
   } else {
     config.parameterValue = "/abc/def";
   }
   servlet.init(config);
   assertEquals("prefix value", config.parameterValue, servlet.prefix);
 }
예제 #8
0
 // Try to find an URL for system props or config
 private String findAgentUrl(Configuration pConfig) {
   // System property has precedence
   String url = System.getProperty("jolokia." + ConfigKey.DISCOVERY_AGENT_URL.getKeyValue());
   if (url == null) {
     url = System.getenv("JOLOKIA_DISCOVERY_AGENT_URL");
     if (url == null) {
       url = pConfig.get(ConfigKey.DISCOVERY_AGENT_URL);
     }
   }
   return NetworkUtil.replaceExpression(url);
 }
예제 #9
0
  public static void showServerInfo(PrintStream out) {
    out.println("Server Info");
    out.println(
        " getDocumentBuilderFactoryVersion(): "
            + XMLEntityResolver.getDocumentBuilderFactoryVersion());
    out.println();

    Properties sysp = System.getProperties();
    Enumeration e = sysp.propertyNames();
    List<String> list = Collections.list(e);
    Collections.sort(list);

    out.println("System Properties:");
    for (String name : list) {
      String value = System.getProperty(name);
      out.println("  " + name + " = " + value);
    }
    out.println();
  }
예제 #10
0
  public static void log(String depbugstatement) {
    SimpleLayout layout = new SimpleLayout();

    FileAppender appender = null;
    try {
      String userDir = System.getProperty("user.dir");
      // FileInputStream fis = null;
      if (userDir.indexOf(":") != -1) {
        appender = new FileAppender(layout, "..\\server\\default\\log\\caIMAGE.log", false);
      } else {
        appender = new FileAppender(layout, "../log/caIMAGE.log", false);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    logger.addAppender(appender);
    logger.setLevel((Level) Level.DEBUG);
    logger.debug(depbugstatement);
  }
예제 #11
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);
    }
  }
예제 #12
0
package com.jspsmart.upload;
예제 #13
0
/**
 * The <code>CDCClientServlet</code> is the heart of the Cross Domain Single Signon mechanism of
 * OpenAM in the DMZ along with the distributed auth. <br>
 * The following is the algorithm used by the program:
 *
 * <ol>
 *   <li>If request does not contain SSO related cookie or policy has generated some advices then
 *       redirect request to the distributed auth service.
 *   <li>If request contains SSO related cookie and no advices.
 *       <ul>
 *         <li>Tunnel the Request to OpenAM.
 *         <li>Send the received AuthNResponse as Form POST to the original request requested using
 *             the goto parameter in the query string.
 *       </ul>
 * </ol>
 */
public class CDCClientServlet extends HttpServlet {
  private static final ArrayList adviceParams = new ArrayList();
  private static final Set<String> INVALID_SET = new HashSet<String>();
  private static final Set<String> VALID_LOGIN_URIS = new HashSet<String>();
  private static final String LEFT_ANGLE = "<";
  private static final String RIGHT_ANGLE = ">";
  private static final String URLENC_RIGHT_ANGLE = "%3e";
  private static final String URLENC_LEFT_ANGLE = "%3c";
  private static final String URLENC_JAVASCRIPT = "javascript%3a";
  private static final String JAVASCRIPT = "javascript:";
  private static final String DELIM = ",";
  private static final String DEBUG_FILE_NAME = "amCDC";
  private static final char QUESTION_MARK = '?';
  private static final char AMPERSAND = '&';
  private static final char EQUAL_TO = '=';
  private static final char SEMI_COLON = ';';
  private static final char SPACE = ' ';
  private static final String GOTO_PARAMETER = "goto";
  private static final String TARGET_PARAMETER = "TARGET";
  private static final String CDCURI = "/cdcservlet";
  private static final String LOGIN_URI = "loginURI";
  private static String cdcAuthURI;
  private static final String AUTHURI = "/UI/Login";
  private static final String RESPONSE_HEADER_ALERT = "X-DSAME-Assertion-Form";
  private static final String RESPONSE_HEADER_ALERT_VALUE = "true";
  private static final String FORBIDDEN_STR_MATCH = "#403x";
  private static final String SERVER_ERROR_STR_MATCH = "#500x";
  static Debug debug = Debug.getInstance(DEBUG_FILE_NAME);

  static {
    initConfig();
  }

  private static SSOTokenManager tokenManager;
  private static String sessionServiceName = "iPlanetAMSessionService";
  private static String authURLCookieName;
  private static String authURLCookieDomain;
  private static String deployDescriptor;
  boolean serverMode =
      Boolean.valueOf(
              System.getProperty(
                  Constants.SERVER_MODE, SystemProperties.get(Constants.SERVER_MODE, "false")))
          .booleanValue();
  private static boolean cookieEncoding = SystemProperties.getAsBoolean(Constants.AM_COOKIE_ENCODE);

  /**
   * @param config the ServletConfig object that contains configutation information for this
   *     servlet.
   * @exception ServletException if an exception occurs that interrupts the servlet's normal
   *     operation.
   */
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    if (debug.messageEnabled()) {
      debug.message("CDCClientServlet.init:CDCClientServlet " + "Initializing...");
    }
    try {
      tokenManager = SSOTokenManager.getInstance();
    } catch (SSOException ssoe) {
      debug.error("CDCClientServlet.init:unable to get SSOTokenManager", ssoe);
    }
    authURLCookieName =
        SystemProperties.get(Constants.AUTH_UNIQUE_COOKIE_NAME, "sunIdentityServerAuthNServer");
    authURLCookieDomain = SystemProperties.get(Constants.AUTH_UNIQUE_COOKIE_DOMAIN, "");
    deployDescriptor =
        SystemProperties.get(Constants.AM_DISTAUTH_DEPLOYMENT_DESCRIPTOR, "/distauth");
  }

  /**
   * Handles the HTTP GET request.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception ServletException if an input or output error is detected when the servlet handles
   *     the GET request
   * @exception IOException if the request for the GET could not be handled
   */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGetPost(request, response);
  }

  /**
   * Handles the HTTP POST request.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception ServletException if an input or output error is detected when the servlet handles
   *     the GET request
   * @exception IOException if the request for the GET could not be handled
   */
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGetPost(request, response);
  }

  /**
   * The method redirects the user to the authentication module if he is not authenticated; else
   * redirects him back to the original referrer.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception ServletException if an input or output error is detected when the servlet handles
   *     the GET request
   * @exception IOException if the request for the GET could not be handled
   */
  private void doGetPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.doGetPost:Query String received= " + request.getQueryString());
    }
    String gotoParameter = request.getParameter(GOTO_PARAMETER);
    String targetParameter = request.getParameter(TARGET_PARAMETER);
    if (targetParameter == null) {
      targetParameter = request.getParameter(TARGET_PARAMETER.toLowerCase());
    }
    // if check if goto ot target have invalid strings, to avoid
    // accepting invalid injected javascript.

    if ((gotoParameter != null) || (targetParameter != null)) {
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet:doGetPost():validating goto: "
                + gotoParameter
                + " and target: "
                + targetParameter);
      }
      for (String invalidStr : INVALID_SET) {
        if (gotoParameter != null && gotoParameter.toLowerCase().contains(invalidStr)) {
          showError(response, SERVER_ERROR_STR_MATCH + "GOTO parameter has invalid characters");
          return;
        }
        if (targetParameter != null && targetParameter.toLowerCase().contains(invalidStr)) {
          showError(response, SERVER_ERROR_STR_MATCH + "TARGET parameter has invalid characters");
          return;
        }
      }
    }

    /* Steps to be done
     * 1. If no SSOToken or policy advice present , forward to
     *    authentication.
     * 2. If SSOToken is valid tunnel request to the backend AM's
     *    CDCServlet and Form POST the received response to the agent.
     */
    // Check for a valid SSOToken in the request. If SSOToken is not found
    // or if the token is invalid, redirect the user for authentication.
    // Also re-direct if there are policy advices in the query string
    SSOToken token = getSSOToken(request, response);
    // collect advices in parsedRequestParams[0] String and rest of params
    // other than original goto url in parsedRequestParams[1] String.
    String[] parsedRequestParams = parseRequestParams(request);

    if ((token == null) || (parsedRequestParams[0] != null)) {
      // Redirect to authentication
      redirectForAuthentication(request, response, parsedRequestParams[0], parsedRequestParams[1]);
    } else {

      // tunnel request to AM
      // send the request to the CDCServlet of AM where the session
      // was created.
      sendAuthnRequest(request, response, token);
    }
  }

  /**
   * This the main method of this servlet which takes in the request opens a URLConnection to the
   * CDCServlet endpoint in the OpenAM, and tunnels the request content to it. It parses the
   * Response received and if the HTTP_STATUS is "HTTP_OK" or "HTTP_MOVED_TEMP" POSTs the received
   * Liberty Authn Response to the goto URL specified in the original request.
   */
  private void sendAuthnRequest(
      HttpServletRequest request, HttpServletResponse response, SSOToken token)
      throws ServletException, IOException {
    SessionID sessid = new SessionID(request);
    URL CDCServletURL = null;
    URL sessionServiceURL = null;
    try {
      sessionServiceURL = Session.getSessionServiceURL(sessid);
    } catch (SessionException se) {
      debug.error(
          "CDCClientServlet.sendAuthnRequest: Cannot locate" + " OpenAM instance to forward to.",
          se);
      showError(response, "Cannot locate OpenAM instance to forward to");
    }
    if (sessionServiceURL == null) {
      showError(response, "Cannot locate OpenAM instance to forward to");
    }
    // replace "sessionservice" by cdcservlet in obtained URL
    // we use naming so that we get the URL of the exact server
    // where the session is located and get the right deployment
    // descriptor.
    String sessionServiceURLString = sessionServiceURL.toString();
    int serviceNameIndex =
        sessionServiceURLString.lastIndexOf(
            "/", sessionServiceURLString.length() - 2); // avoiding trailing "/"
    // if any
    StringBuilder buffer = new StringBuilder(150);
    buffer
        .append(sessionServiceURLString.substring(0, serviceNameIndex))
        .append(CDCURI)
        .append(QUESTION_MARK)
        .append(request.getQueryString()); // add query string to
    // CDCServletURL

    CDCServletURL = new URL(buffer.toString());

    // save the go to URL of the agent side to ultimately
    // POST to.
    try {
      HttpURLConnection connection = HttpURLConnectionManager.getConnection(CDCServletURL);
      connection.setRequestMethod("GET");
      connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
      connection.setDoOutput(true);
      connection.setUseCaches(false);
      // replay cookies
      String strCookies = getCookiesFromRequest(request);
      if (strCookies != null) {
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet.sendAuthnRequest:Setting " + "cookies = " + strCookies);
        }
        connection.setRequestProperty("Cookie", strCookies);
      }
      // dont wish to follow redirect to agent, since
      // the response needs to go via the CDCClientServlet.
      HttpURLConnection.setFollowRedirects(false);

      // Receiving input from CDCServlet on the AM server instance
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Getting " + "response back from  " + CDCServletURL);
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Response " + "Code " + connection.getResponseCode());
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Response "
                + "Message= "
                + connection.getResponseMessage());
      }

      // Check response code
      if ((connection.getResponseCode() == HttpURLConnection.HTTP_OK)
          || (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)) {
        /**
         * Read the response back from CDCServlet, got a redirect since this response contains the
         * "LARES" ( Liberty authn response, which needs to be posted back to the dest url (agent).
         */
        StringBuilder inBuf = new StringBuilder();
        BufferedReader in =
            new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        int len;
        char[] buf = new char[1024];
        while ((len = in.read(buf, 0, buf.length)) != -1) {
          inBuf.append(buf, 0, len);
        }
        String inString = inBuf.toString();
        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.sendAuthnRequest:" + "Received response data = " + inString);
        }
        // put the received Liberty Auth Response
        // in the servlet's response.
        sendAuthnResponse(request, response, inString);
      } else {
        debug.error("CDCClientServlet.sendAuthnRequest: Response " + "code NOT OK/MOVED_TEMP ");
        showError(
            response,
            "ERROR: Received HTTP error code "
                + connection.getResponseCode()
                + " from "
                + CDCServletURL);
      }
    } catch (ConnectException ce) {
      // Debug the exception
      if (debug.warningEnabled()) {
        debug.warning(
            "CDCClientServlet.sendAuthnRequest: " + "Connection Exception to " + CDCServletURL, ce);
      }
      showError(
          response, "Could not connect to CDCServlet at " + CDCServletURL + ":" + ce.getMessage());
    }
  }

  // Get cookies string from HTTP request object
  private String getCookiesFromRequest(HttpServletRequest request) {
    Cookie cookies[] = CookieUtils.getCookieArrayFromReq(request);
    // above call would return pure sid in iPlanetDirectoryPro cookie
    // independent of container encoding
    StringBuilder cookieStr = null;
    String strCookies = null;
    if (cookies != null) {
      for (int nCookie = 0; nCookie < cookies.length; nCookie++) {
        String cookieName = cookies[nCookie].getName();
        String cookieVal = cookies[nCookie].getValue();
        if (cookieName.equals(CookieUtils.getAmCookieName()) && cookieEncoding) {
          cookieVal = URLEncDec.encode(cookieVal);
        }
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie name = " + cookieName);
          debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie val= " + cookieVal);
        }
        if (cookieStr == null) {
          cookieStr = new StringBuilder();
        } else {
          cookieStr.append(SEMI_COLON).append(SPACE);
        }
        cookieStr.append(cookieName).append(EQUAL_TO).append(cookieVal);
      }
    }
    if (cookieStr != null) {
      strCookies = cookieStr.toString();
    }
    return strCookies;
  }

  /**
   * Gathers the parameters in the request as a HTTP URL string. to form request parameters and
   * policy advice String array. It collects all the parameters from the original request except the
   * original goto url and any advice parameters. Note: All the paramters will be url decoded by
   * default., we should make sure that these values are encoded again
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @return An String array, index 0 is policy advice, index 1 is rest of the request parameters
   */
  private String[] parseRequestParams(HttpServletRequest request) {
    StringBuilder adviceList = null;
    StringBuilder parameterString = new StringBuilder(100);
    for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
      String paramName = (String) e.nextElement();
      if (adviceParams.contains(paramName.toLowerCase())) {
        if (adviceList == null) {
          adviceList = new StringBuilder();
        } else {
          adviceList.append(AMPERSAND);
        }
        String[] values = request.getParameterValues(paramName);
        for (int i = 0; values != null && i < values.length; i++) {
          adviceList.append(paramName).append(EQUAL_TO).append(values[i]);
        }
      } else {
        if (!paramName.equals(GOTO_PARAMETER)) {
          String[] values = request.getParameterValues(paramName);
          for (int i = 0; values != null && i < values.length; i++) {
            parameterString
                .append(AMPERSAND)
                .append(paramName)
                .append(EQUAL_TO)
                .append(URLEncDec.encode(values[i]));
          }
        }
      }
    }
    if (debug.messageEnabled()) {
      debug.message("CDCClientServlet.parseRequestParams:" + "Advice List is = " + adviceList);
      debug.message(
          "CDCClientServlet.parseRequestParams:"
              + "Parameter String is = "
              + parameterString.toString());
    }

    String policyAdviceList;
    String requestParams;

    if (adviceList == null) {
      policyAdviceList = null;
    } else {
      policyAdviceList = adviceList.toString();
    }

    if (parameterString.length() > 0) {
      requestParams = (parameterString.deleteCharAt(0).toString());
    } else {
      requestParams = parameterString.toString();
    }

    return new String[] {policyAdviceList, requestParams};
  }

  /**
   * Redirects the HTTP request to the Authentication module. It gets the authentication url from
   * <code>SystemProperties</code>.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception IOException If an input or output exception occurs
   */
  private void redirectForAuthentication(
      HttpServletRequest request,
      HttpServletResponse response,
      String policyAdviceList,
      String requestParams)
      throws IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.redirectForAuthentication: " + "requestURL=" + request.getRequestURL());
    }
    StringBuilder redirectURL = new StringBuilder(100);
    StringBuilder gotoURL = new StringBuilder(100);

    // Check if user has authenticated to another OpenAM
    // instance
    String authURL = null;
    Cookie authCookie = CookieUtils.getCookieFromReq(request, authURLCookieName);
    if (authCookie != null) {
      authURL = CookieUtils.getCookieValue(authCookie);
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication: "
                + "got an authenticated URL= "
                + authURL);
      }
    }
    try {
      if (authURL == null
          || authURL.length() == 0
          || !authURL.toLowerCase().startsWith("http")
          || policyAdviceList != null) {
        String finalURL = request.getParameter(GOTO_PARAMETER);

        if (finalURL == null || finalURL.equals("")) {
          finalURL = request.getParameter(TARGET_PARAMETER);
        }

        if (finalURL == null || finalURL.equals("")) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication: "
                    + "goto or target parameter is missing in the request.");
          }

          showError(response, SERVER_ERROR_STR_MATCH);
          return;
        }

        gotoURL
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(TARGET_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(finalURL))
            .append(AMPERSAND)
            .append(requestParams);

        // Construct the login URL
        String loginURI = request.getParameter(LOGIN_URI);
        String cdcUri;

        if (loginURI != null && !loginURI.isEmpty() && isValidCDCURI(loginURI)) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication:found " + LOGIN_URI + "=" + loginURI);
          }

          cdcUri = loginURI;
        } else {
          cdcUri = cdcAuthURI;
        }

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication: Login URI is set to = " + cdcUri);
        }

        if (cdcUri.indexOf(QUESTION_MARK) == -1) {
          redirectURL.append(cdcUri).append(QUESTION_MARK);
        } else {
          redirectURL.append(cdcUri).append(AMPERSAND);
        }

        if (policyAdviceList != null) {
          redirectURL.append(policyAdviceList).append(AMPERSAND);
        }
        redirectURL
            .append(GOTO_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(gotoURL.toString()));

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication"
                  + ":redirectURL before dispatching is="
                  + redirectURL);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(redirectURL.toString());
        dispatcher.forward(request, response);
      } else {
        // Redirect the user to the authenticated URL
        redirectURL
            .append(authURL)
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(request.getQueryString());
        // Reset the cookie value to null, to avoid continuous loop
        // when a load balancer is used
        if (authCookie != null) {
          authCookie.setValue("");
          response.addCookie(authCookie);
        }
        response.sendRedirect(redirectURL.toString());
      }

      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication:"
                + "Forwarding for authentication to= "
                + redirectURL);
      }
    } catch (IOException ex) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication: Failed "
              + "in forwarding to Authentication service. IOException",
          ex);
      showError(response, "Could for forward to authentication service:" + ex.getMessage());
    } catch (ServletException se) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. ServletException",
          se);
      showError(response, "Could for forward to authentication service:" + se.getMessage());
    } catch (IllegalStateException ie) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. Illegal state",
          ie);
      showError(response, "Could for forward to authentication service:" + ie.getMessage());
    }
  }

  /**
   * Shows Application Error message to the user.
   *
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @param msg Message to be displayed.
   */
  private void showError(HttpServletResponse response, String msg) throws IOException {
    ServletOutputStream out = null;
    if (msg == null || msg.equals("") || msg.contains(SERVER_ERROR_STR_MATCH)) {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      return;
    }

    try {
      out = response.getOutputStream();
      out.println(msg);
      out.flush();
    } catch (IOException e) {
      debug.error("CDCClientServlet.showError::Could not show error " + "message to the user " + e);
    } finally {
      try {
        out.close();
      } catch (IOException ignore) {
      }
    }
  }

  /**
   * Returns the SSOToken of the user. If user has not authenticated re-directs the user to login
   * page
   */
  private SSOToken getSSOToken(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    SSOToken token = null;
    try {
      /* SSOTokenManager.createSSOToken() throws an SSOException if the
       * token is not valid, so for a invalid token manager.isValidToken()
       * will never get executed for an invalid token.
       */
      if (((token = tokenManager.createSSOToken(request)) == null)
          || !tokenManager.isValidToken(token)) {
        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.getSSOToken:SSOToken is "
                  + "either null or not valid: "
                  + token
                  + "\nRedirecting for authentication");
        }
        token = null;
      }
    } catch (com.iplanet.sso.SSOException e) {
      if (debug.messageEnabled()) {
        debug.message("CDCClientServlet.getSSOToken:SSOException " + "caught= " + e);
      }
      token = null;
    }
    return (token);
  }

  private void sendAuthnResponse(
      HttpServletRequest request, HttpServletResponse response, String authnResponse) {
    if (debug.messageEnabled()) {
      debug.message("CDCClientServlet.sendAuthnResponse: Called");
    }
    try {
      if (debug.messageEnabled()) {
        debug.message("CDCClientServlet.sendAuthnResponse: " + "AuthnResponse= " + authnResponse);
      }
      response.setContentType("text/html");
      response.setHeader("Pragma", "no-cache");
      response.setHeader(RESPONSE_HEADER_ALERT, RESPONSE_HEADER_ALERT_VALUE);

      if (authnResponse.contains(FORBIDDEN_STR_MATCH)) {
        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.sendAuthnResponse: " + "AuthnResponse showing 403 error page");
        }

        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
      }

      if (authnResponse.contains(SERVER_ERROR_STR_MATCH)) {
        if (debug.messageEnabled()) {
          debug.error(
              "CDCClientServlet.sendAuthnResponse: " + "ERROR: An application error has occured.");
        }

        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
      }

      PrintWriter out = response.getWriter();
      out.println(authnResponse);
      out.close();
      if (debug.messageEnabled()) {
        debug.message("CDCClientServlet.sendAuthnResponse: " + "AuthnResponse sent successfully");
      }
      return;
    } catch (IOException ioe) {
      debug.error("CDCClientServlet.sendAuthnResponse:" + ioe.getMessage());
    }
  }

  /**
   * Return <code>true</code> if the passed URI is valid compared to the valid set loaded during
   * initialization.
   *
   * @param cdcUri The URI to test.
   * @return <code>true</code> if the URI is considered valid, <code>false</code> otherwise.
   */
  private boolean isValidCDCURI(String cdcUri) {
    int questionMark = cdcUri.indexOf(QUESTION_MARK);

    // We are only interested in the URI part up to any parameters that may be included.
    if (questionMark != -1) {
      cdcUri = cdcUri.substring(0, questionMark);
    }

    // If there is not an exact match for the passed value then it cannot be considered valid
    boolean result = VALID_LOGIN_URIS.contains(cdcUri);

    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.isValidCDCURI: checking if "
              + cdcUri
              + " is in validLoginURISet: "
              + VALID_LOGIN_URIS
              + " result:"
              + result);
    }

    return result;
  }

  private static void initConfig() {
    adviceParams.add("module");
    adviceParams.add("authlevel");
    adviceParams.add("role");
    adviceParams.add("service");
    adviceParams.add("user");
    adviceParams.add("realm");
    adviceParams.add("org");
    adviceParams.add("resource");
    adviceParams.add("sunamcompositeadvice");
    String invalidStrings = SystemPropertiesManager.get(Constants.INVALID_GOTO_STRINGS);
    if (INVALID_SET.isEmpty()) {
      debug.message("CDCClientServlet.initConfig: creating invalidSet");
      if (invalidStrings == null) {
        debug.message("CDCClientServlet.initConfig: invalidStrings is null");
        INVALID_SET.add(LEFT_ANGLE);
        INVALID_SET.add(RIGHT_ANGLE);
        INVALID_SET.add(URLENC_LEFT_ANGLE);
        INVALID_SET.add(URLENC_RIGHT_ANGLE);
        INVALID_SET.add(JAVASCRIPT);
        INVALID_SET.add(URLENC_JAVASCRIPT);
      } else {
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet.initConfig: invalidStrings is: " + invalidStrings);
        }
        StringTokenizer st = new StringTokenizer(invalidStrings, DELIM);
        while (st.hasMoreTokens()) {
          INVALID_SET.add(st.nextToken());
        }
      }
      debug.message("CDCClientServlet.initConfig: created invalidSet " + INVALID_SET);
    }

    String urlFromProps = SystemProperties.get(Constants.CDCSERVLET_LOGIN_URL);
    cdcAuthURI = (urlFromProps != null) ? urlFromProps : AUTHURI;

    String validLoginURIStrings = SystemPropertiesManager.get(Constants.VALID_LOGIN_URIS);
    debug.message("CDCClientServlet.initConfig: creating validLoginURISet");
    if (validLoginURIStrings == null) {
      debug.message(
          "CDCClientServlet.initConfig: validLoginURIStrings is null, creating default set");
      VALID_LOGIN_URIS.add(cdcAuthURI);
    } else {
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.initConfig: validLoginURIStrings is: " + validLoginURIStrings);
      }
      StringTokenizer st = new StringTokenizer(validLoginURIStrings, DELIM);
      while (st.hasMoreTokens()) {
        VALID_LOGIN_URIS.add(st.nextToken());
      }
    }
    debug.message("CDCClientServlet.initConfig: created validLoginURISet " + VALID_LOGIN_URIS);
  }
}
예제 #14
0
  /**
   * Valida los p�rametros entrada y ejecuta los servicios de alta, baja o cambio.
   *
   * @param registro Parametros que se recogen de la sesion del usuario y se le envian a la clase
   *     CON. Estos par�metros son: CVE_GPO_EMPRESA (Clave del grupo empresa), CVE_USUARIO_BITACORA
   *     (clave del usuario que realiza la operacion), RegistroOriginal (registro leido
   *     originalmente y se utiliza cuando se ejecuta la operaci�n de modificacion y se verifica que
   *     no se hallan realizado modificaciones al registro).
   * @param request Objeto que provee de informaci�n al servlet sobre el request del cliente. El
   *     contenedor de servlets crea un objeto HttpServletRequest y lo env�a como un par�metro a
   *     este m�todo.
   * @param response Objeto que provee de informaci�n del servlet sobre el response del cliente. El
   *     contenedor de servlets crea un objeto HttpServletResponse y lo env�a como un par�metro a
   *     este m�todo.
   * @param config Objeto que provee de informaci�n del servlet sobre el ServletConfig del cliente.
   *     El contenedor de servlets crea un objeto ServletConfig y lo env�a como un par�metro a este
   *     m�todo.
   * @param catalogoSL Instancia del Ejb CatalogoSL que ejecuta en la base de datos las operaciones
   *     especificadas en la clase CON
   * @param contexto Objeto que contiene informaci�n acerca del entorno del servidor de
   *     aplicaciones.
   * @param iTipoOperacion Operaci�n que debe ejecutar la clase CON. Las operaciones se encuentran
   *     especificadas en la clase {@link com.rapidsist.portal.cliente.CatalogoControl
   *     CatalogoControl}
   * @return Respuesta del servicio de alta, baja o cambio y la p�gina a donde se redirecciona el
   *     control.
   * @throws RemoteException Si se gener� un error en el Ejb CatalogoSL.
   * @throws java.lang.Exception Si se gener� un error dentro de la clase CON.
   */
  public RegistroControl actualiza(
      Registro registro,
      HttpServletRequest request,
      HttpServletResponse response,
      ServletConfig config,
      CatalogoSL catalogoSL,
      Context contexto,
      int iTipoOperacion)
      throws RemoteException, Exception {
    RegistroControl registroControl = new RegistroControl();

    Object referencia = contexto.lookup("java:comp/env/ejb/PublicacionSL");
    PublicacionSLHome publicacionHome =
        (PublicacionSLHome) PortableRemoteObject.narrow(referencia, PublicacionSLHome.class);
    PublicacionSL publicacion = publicacionHome.create();

    // OBTIENE LOS DATOS DEL USUARIO
    HttpSession session = request.getSession(true);
    Usuario usuario = (Usuario) session.getAttribute("Usuario");
    registro.addDefCampo("CVE_PORTAL", usuario.sCvePortal);
    registro.addDefCampo("CVE_USUARIO", usuario.sCveUsuario);

    Date dFecha = new Date();
    // ESTE OBJETO ES NECESARIO PARA INICIALIZAR EL OBJETO QUE PERMITE GUARDAR LOS ARCHIVOS
    int iResultadoSave = 0; // VARIABLE CON EL VALOR RESULTANTE DE GUARDAR EL ARCHIVO
    // INSTANCIA LA CLASE SE REALIZA EL UPLOAD
    SmartUpload mySmartUpload = new SmartUpload();
    // INICIALIZA EL UPLOAD
    mySmartUpload.initialize(config, request, response);
    // REALIZA LA CARGA DEL O DE LOS ARCHIVOS
    mySmartUpload.upload();
    // SALVA EL ARCHIVO CON EL NOMBRE ORIGINAL DENTRO DEL SERVIDOR
    Files archivos = mySmartUpload.getFiles();

    // OBTIENE LOS VALORES DE LOS PARAMETROS
    java.util.Enumeration e = mySmartUpload.getRequest().getParameterNames();

    String sUrlImagenAnterior = "";
    String sUrlImagenReferencia = "";
    String sUrlTamanoOriginal = "";
    String sUrlTamanoAnterior = "";
    String sUrlVideoAnterior = "";
    String sTamano = "";
    String sAutoPlay = "";
    String sUrlOpcionAutoPlayAnterior = "";

    // OBTIENE LOS PARAMETROS DE LA PAGINA
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      String value = mySmartUpload.getRequest().getParameter(name);
      // ASIGNA EL VALOR AL REGISTRO QUE SE VA A DAR DE ALTA EN LA
      // BASE DE DATOS

      if (name.equals("CveSeccion")) {
        registro.addDefCampo("CVE_SECCION", value);
      }
      if (name.equals("IdPublicacion")) {
        registro.addDefCampo("ID_PUBLICACION", value);
      }
      if (name.equals("IdNivelAcceso")) {
        registro.addDefCampo("ID_NIVEL_ACCESO", value);
      }
      if (name.equals("NomPublicacion")) {
        registro.addDefCampo("NOM_PUBLICACION", value);
      }
      if (name.equals("TxComentario")) {
        registro.addDefCampo("TX_COMENTARIO", value);
      }
      if (name.equals("DescPublicacion")) {
        registro.addDefCampo("DESC_PUBLICACION", value);
      }
      if (name.equals("IdPrioridad")) {
        registro.addDefCampo("ID_PRIORIDAD", value);
      }
      if (name.equals("FIniVigencia")) {
        dFecha = Fecha2.toDate(value);
        registro.addDefCampo("F_INI_VIGENCIA", Fecha2.formatoBDStatic(dFecha));
      }
      if (name.equals("FFinVigencia")) {
        dFecha = Fecha2.toDate(value);
        registro.addDefCampo("F_FIN_VIGENCIA", Fecha2.formatoBDStatic(dFecha));
      }
      if (name.equals("OperacionCatalogo")) {
        registro.addDefCampo("OPERACION_CATALOGO", value);
      }
      if (name.equals("rbTamano")) {
        registro.addDefCampo("TAMANO", value);
        sTamano = value;
      }
      if (name.equals("OperacionCatalogo")) {
        registro.addDefCampo("OPERACION_CATALOGO", value);
      }
      if (name.equals("UrlImagenAnterior")) {
        sUrlImagenAnterior = value;
      }
      if (name.equals("UrlVideoAnterior")) {
        sUrlVideoAnterior = value;
      }
      if (name.equals("UrlTamanoAnterior")) {
        sUrlTamanoAnterior = value;
      }
      if (name.equals("UrlTamanoOriginal")) {
        sUrlTamanoOriginal = value;
      }
      if (name.equals("rbAutoPlay")) {
        registro.addDefCampo("AUTO_PLAY", value);
        sAutoPlay = value;
      }
      if (name.equals("UrlOpcionAutoPlayAnterior")) {
        sUrlOpcionAutoPlayAnterior = value;
      }
    }

    // OBTIENE EL DIRECTORIO RAIZ
    String sRaiz = getRoot(System.getProperty("user.dir"));

    // RUTA DONDE ALMACENA EL ARCHIVO
    String sRutaCompleta =
        sRaiz
            + "Desarrollo"
            + System.getProperty("file.separator")
            + "Cuentas"
            + System.getProperty("file.separator")
            + "Rapidsist"
            + System.getProperty("file.separator")
            + "Servidores"
            + System.getProperty("file.separator")
            + "jboss"
            + System.getProperty("file.separator")
            + "Portal"
            + System.getProperty("file.separator")
            + "deploy"
            + System.getProperty("file.separator")
            + "Portal"
            + System.getProperty("file.separator")
            + "portal.war"
            + System.getProperty("file.separator")
            + "Portales"
            + System.getProperty("file.separator")
            + "Icmar"
            + System.getProperty("file.separator")
            + "stream"
            + System.getProperty("file.separator")
            + "video";

    // SE INICIALIZA LA VARIABLE DEL NOMBRE DEL ARCHIVO QUE CONTIENE EL VIDEO
    String sNombreArchivoVideo = null;

    // SE OBTIENE EL PRIMER ARCHIVO
    File archivo = archivos.getFile(0);

    // SE OBTIENE EL NOMBRE DEL PRIMER ARCHIVO QUE SE ENVIA EN EL FORMULARIO
    sNombreArchivoVideo = archivo.getFileName();

    // SE INICIALIZA LA VARIABLE DEL NOMBRE DEL ARCHIVO QUE CONTIENE LA IMAGEN
    String sNombreArchivoImagen = null;

    // SE OBTIENE EL SEGUNDO ARCHIVO
    File archivo_imagen = archivos.getFile(1);

    // SE OBTIENE EL NOMBRE DEL ARCHIVO QUE CONTIENE EL STREAM
    sNombreArchivoImagen = archivo_imagen.getFileName();

    // ALMACENA LOS ARCHIVOS
    iResultadoSave = mySmartUpload.save(sRutaCompleta);

    registro.addDefCampo("VIDEO", sNombreArchivoVideo);
    registro.addDefCampo("URL_PUBLICACION", sNombreArchivoVideo);
    registro.addDefCampo("URL_IMAGEN", sNombreArchivoImagen);

    if (sNombreArchivoVideo.equals("")) {
      sNombreArchivoVideo = sUrlVideoAnterior;
      registro.addDefCampo("VIDEO", sNombreArchivoVideo);
    }

    if (sNombreArchivoImagen.equals("")) {
      sNombreArchivoImagen = sUrlImagenAnterior;
      registro.addDefCampo("URL_IMAGEN", sNombreArchivoImagen);
    }

    if (sNombreArchivoImagen.equals("")) {
      registro.addDefCampo("URL_IMAGEN", " ");
    }

    if (sTamano.equals("")) {
      sTamano = sUrlTamanoAnterior;
      registro.addDefCampo("TAMANO", sTamano);
    }

    if (sAutoPlay.equals("")) {
      sAutoPlay = sUrlOpcionAutoPlayAnterior;
      registro.addDefCampo("AUTO_PLAY", sAutoPlay);
    }

    if (sAutoPlay.equals("")) {
      registro.addDefCampo("AUTO_PLAY", "No");
    }

    if ((sNombreArchivoVideo.equals("")) || (sTamano.equals(""))) {

      com.rapidsist.portal.catalogos.ResultadoCatalogo resultadoCatalogoControlado =
          new com.rapidsist.portal.catalogos.ResultadoCatalogo();
      resultadoCatalogoControlado.mensaje.setClave("PUBLICACION_NO_ENVIA_ARCHIVO");
      resultadoCatalogoControlado.mensaje.setTipo("Error");
      resultadoCatalogoControlado.mensaje.setDescripcion(
          "Por favor seleccione el archivo de video que desea publicar o/y el tama�o de la pantalla...");
      registroControl.resultadoCatalogo = resultadoCatalogoControlado;
    } else {

      // ES BAJA
      if (registro.getDefCampo("OPERACION_CATALOGO").equals("BA")) {
        String sArchivoVideo =
            sRutaCompleta
                + System.getProperty("file.separator")
                + (String) registro.getDefCampo("VIDEO");
        String sArchivoVideoImagen =
            sRutaCompleta
                + System.getProperty("file.separator")
                + (String) registro.getDefCampo("URL_IMAGEN");

        // SE BORRAN LOS ARCHIVOS DE AUDIO
        BorraPublicacion borraPublicacion = new BorraPublicacion();
        borraPublicacion.BorraArchivo(sArchivoVideo);
        borraPublicacion.BorraArchivo(sArchivoVideoImagen);

        boolean bExito =
            publicacion.BorraObjetoJNDI(
                usuario.sCveGpoEmpresa, usuario.sCvePortal, usuario.sCveUsuario);
      }

      // DIRECCIONA A LA JSP
      registroControl.sPagina =
          "/ProcesaCatalogo?Funcion=PublicacionesVideo&OperacionCatalogo=IN&Filtro=Todos";

      registroControl.resultadoCatalogo =
          catalogoSL.modificacion("PublicacionesVideo", registro, iTipoOperacion);
    }
    return registroControl;
  }
public class RuleML2008LiaisonChair extends HttpServlet {

  public static final String FS = System.getProperty("file.separator");

  private final String instantiation = "SymposiumPlanner08";
  private final String topic = "LiaisonChair";
  private String address;
  private String port;
  private String poslAddress;
  private String rdfAddress;
  private String messageEndpoint;

  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }

  /////////////////////////

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    System.out.println("Publicty Chair Servlet RuleML-2009");
    out.println("Publicty Chair Servlet RuleML-2009");

    Calendar cal = new GregorianCalendar();

    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH) + 1;
    int day = cal.get(Calendar.DAY_OF_MONTH);

    String date;

    if (month == 10 || month == 11 || month == 12) date = "" + year + month + day;
    else date = "" + year + "0" + month + day;

    date = "date(" + date + ":integer).";
    System.out.println("Publicty Chair Servlet Console update:");
    System.out.println(date);
  }

  /////////////////////////

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      address = PAConfiguration.getAddress();
      port = PAConfiguration.getPort(instantiation);
      poslAddress = PAConfiguration.getPOSL(instantiation, topic);
      rdfAddress = PAConfiguration.getRDFTaxonomy(instantiation);
      messageEndpoint = PAConfiguration.getEndpointName(instantiation, topic);
    } catch (BadConfigurationException e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
      System.exit(0);
    }
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
      System.out.println("5 Publicty Chair Servlet");
      System.out.println(response.toString());

      BufferedReader brd = request.getReader();

      String input = "";
      String message = "";

      while (!input.equals("</RuleML>")) {

        input = brd.readLine();

        message = message + input;
      }
      String[] varOrder = getVariableOrder(message);
      System.out.println("Received Message: " + message);

      //	BackwardReasoner br = new BackwardReasoner();
      //   Iterator solit =null;
      //   DefiniteClause dc = null;
      //   SymbolTable.reset();

      POSLParser pp = new POSLParser();
      // String contents = "c(a).\nc(b).\nc(c).";

      Date t1 = new GregorianCalendar().getTime();
      System.out.println(t1.getHours() + ":" + t1.getMinutes());
      // append time to contents

      System.out.println("day: " + t1.getDay());
      System.out.println("day: " + t1.getYear());
      System.out.println("day: " + t1.getMonth());

      // time
      String time = "time(" + t1.getHours() + ":integer).";
      System.out.println(time);

      String url = poslAddress;

      // String url = "http://www.jdrew.org/oojdrew/test.posl";
      String contents = "";

      // day of the week
      int day = t1.getDay();
      boolean weekday = true;

      if (day == 0 || day == 6) {
        weekday = false;
      }

      String dayOfWeek;

      if (weekday) {
        dayOfWeek = "day(weekday).";
      } else {
        dayOfWeek = "day(weekend).";
      }
      // full date
      Calendar cal = new GregorianCalendar();

      int year = cal.get(Calendar.YEAR);
      int month = cal.get(Calendar.MONTH) + 1;
      int day2 = cal.get(Calendar.DAY_OF_MONTH);

      String date;

      String day3 = "" + day2;

      if (day2 == 1 || day2 == 2 || day2 == 3 || day2 == 4 || day2 == 5 || day2 == 6 || day2 == 7
          || day2 == 8 || day2 == 9) {

        day3 = "0" + day2;
      }

      if (month == 10 || month == 11 || month == 12) date = "" + year + month + day3;
      else date = "" + year + "0" + month + day3;

      date = "date(" + date + ":integer).";

      System.out.println(date);

      String url2 = rdfAddress;
      HttpClient client2 = new HttpClient();
      GetMethod method2 = new GetMethod(url2);
      method2.setFollowRedirects(true);
      String typestr = "";
      // Execute the GET method
      int statusCode2 = client2.executeMethod(method2);
      if (statusCode2 != -1) {
        typestr = method2.getResponseBodyAsString();
      }
      System.out.println("Types: " + typestr);
      Types.reset();
      RDFSParser.parseRDFSString(typestr);

      try {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        method.setFollowRedirects(true);

        // Execute the GET method
        int statusCode = client.executeMethod(method);
        if (statusCode != -1) {
          contents = method.getResponseBodyAsString();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      contents = contents + "\n" + time;
      contents = contents + "\n" + dayOfWeek;
      contents = contents + "\n" + date;

      BackwardReasoner br = new BackwardReasoner();
      Iterator solit = null;
      DefiniteClause dc = null;
      SymbolTable.reset();

      pp.parseDefiniteClauses(contents);

      br.loadClauses(pp.iterator());
      System.out.println("TEST");
      Iterator it = pp.iterator();
      while (it.hasNext()) {
        DefiniteClause d = (DefiniteClause) it.next();
        System.out.println("Loaded clause: " + d.toPOSLString());
      }

      br = new BackwardReasoner(br.clauses, br.oids);

      MessageParser m = new MessageParser(message);
      Element atom = null;

      try {

        atom = m.parseForContent();

      } catch (Exception e) {

        System.out.println("Invalid Message");
        // out.flush();

      }

      QueryBuilder q = new QueryBuilder(atom);
      String query = q.generateDoc();
      System.out.println("ABOUT TO INPUT THIS QUERY:" + query);
      RuleMLParser qp = new RuleMLParser();

      try {

        dc = qp.parseRuleMLQuery(query);

      } catch (Exception e) {
        System.out.println("Invalid Query");
        // out.flush();
      }

      // solit = br.iterativeDepthFirstSolutionIterator(dc);

      solit = br.iterativeDepthFirstSolutionIterator(dc);

      int varSize = 0;

      while (solit.hasNext()) {

        Vector data = new Vector();

        BackwardReasoner.GoalList gl = (BackwardReasoner.GoalList) solit.next();

        Hashtable varbind = gl.varBindings;
        javax.swing.tree.DefaultMutableTreeNode root = br.toTree();
        root.setAllowsChildren(true);

        javax.swing.tree.DefaultTreeModel dtm = new DefaultTreeModel(root);

        int i = 0;
        Object[][] rowdata = new Object[varbind.size()][2];
        varSize = varbind.size();

        Enumeration e = varbind.keys();
        while (e.hasMoreElements()) {
          Object k = e.nextElement();
          Object val = varbind.get(k);
          String ks = (String) k;
          rowdata[i][0] = ks;
          rowdata[i][1] = val;
          i++;
        }

        data.addElement(rowdata);
        String[] messages = new String[data.size()];
        MessageGenerator g =
            new MessageGenerator(
                data, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel(), varOrder);
        messages = g.Messages2();

        String appender = "";

        URL sender = new URL(address + ":" + port);
        HttpMessage msg = new HttpMessage(sender);
        Properties props = new Properties();

        for (int i1 = 0; i1 < data.size(); i1++) {
          System.out.println(i1 + ")" + messages[i1].toString());
          props.put("text", messages[i1].toString());
          InputStream in = msg.sendGetMessage(props);
        }
        System.out.println("NEXT MESSAGE");
      }

      MessageGenerator g =
          new MessageGenerator(
              null, varSize, messageEndpoint, m.getId(), m.getProtocol(), m.getRel());

      URL sender = new URL(address + ":" + port);
      HttpMessage msg = new HttpMessage(sender);
      Properties props = new Properties();

      String finalMessage = g.finalMessage(query);

      System.out.println(finalMessage);

      props.put("text", finalMessage);
      InputStream in = msg.sendGetMessage(props);

      System.out.println("Stop_Communication");

    } catch (Exception e) {
      System.out.println("ERROR has occured : " + e.toString());
    }
    out.close();
  }

  // Get parameters from the request URL.
  String getRequestParam(HttpServletRequest request, String param) {
    if (request != null) {
      String paramVal = request.getParameter(param);
      return paramVal;
    }
    return null;
  }
  /**
   * Is used to remember the order of variables so that the message returned to the OA does not
   * contain randomly ordered data.
   *
   * @param message The RuleML message
   * @return An array containing the order of the variables.
   */
  public static String[] getVariableOrder(String message) {
    Vector<String> variables = new Vector<String>();
    String[] variableList;
    // Break string up
    StringTokenizer st = new StringTokenizer(message, "<");

    String temp = ""; // Temporary storage
    String tempVar = ""; // Temporary variable storage

    // While information remains
    while (st.hasMoreTokens()) {
      temp = st.nextToken();
      // If it is a variable
      if (temp.startsWith("Var>")) {
        tempVar = "";
        // Get the name of the variable
        for (int i = 4; i < temp.length(); i++) {
          if (temp.charAt(i) == '<') break;
          else tempVar = tempVar + temp.charAt(i);
        }
        variables.addElement(tempVar); // Store the variable name
      }
    }
    // Convert the vector to an array
    variableList = new String[variables.size()];
    for (int i = 0; i < variables.size(); i++) {
      variableList[i] = variables.elementAt(i);
    }
    return variableList;
  }
  // End getVariableOrder() method
}