Example #1
0
  /**
   * Initialize the backend systems, the log handler and the restrictor. A subclass can tune this
   * step by overriding {@link #createRestrictor(String)} and {@link
   * #createLogHandler(ServletConfig, boolean)}
   *
   * @param pServletConfig servlet configuration
   */
  @Override
  public void init(ServletConfig pServletConfig) throws ServletException {
    super.init(pServletConfig);

    Configuration config = initConfig(pServletConfig);

    // Create a log handler early in the lifecycle, but not too early
    String logHandlerClass = config.get(ConfigKey.LOGHANDLER_CLASS);
    logHandler =
        logHandlerClass != null
            ? (LogHandler) ClassUtil.newInstance(logHandlerClass)
            : createLogHandler(pServletConfig, Boolean.valueOf(config.get(ConfigKey.DEBUG)));

    // Different HTTP request handlers
    httpGetHandler = newGetHttpRequestHandler();
    httpPostHandler = newPostHttpRequestHandler();

    if (restrictor == null) {
      restrictor =
          createRestrictor(NetworkUtil.replaceExpression(config.get(ConfigKey.POLICY_LOCATION)));
    } else {
      logHandler.info("Using custom access restriction provided by " + restrictor);
    }
    configMimeType = config.get(ConfigKey.MIME_TYPE);
    backendManager = new BackendManager(config, logHandler, restrictor);
    requestHandler = new HttpRequestHandler(config, backendManager, logHandler);

    initDiscoveryMulticast(config);
  }
  private boolean resolveBooleanArg(String arg, boolean defaultValue) {
    if (arg == null) return defaultValue;

    try {
      return Boolean.parseBoolean(arg);
    } catch (Exception e) {
      return defaultValue;
    }
  }
Example #3
0
  @Override
  public void init() {
    try {
      this.debug = Boolean.parseBoolean(this.getInitParameter("debug"));

      if (!this.debug) this.pageInfoCache = new HashMap<String, PageInfo>();

      String routesParameter = this.getInitParameter("routes");
      if (routesParameter != null) {
        this.routes = new Properties();
        routes.load(new StringReader(routesParameter));
      }

      String sourceParameter = this.getInitParameter("source");
      if (sourceParameter == null) throw new RuntimeException("Missing init parameter 'source'");
      // automatically insert a reference to our PageServlet.js if not present
      String sourceDelimiter = ";";
      if (sourceParameter.indexOf("PageServlet.js") < 0)
        sourceParameter =
            "jar:file:WEB-INF/lib/glasspages.jar!/glasspages/PageServlet.js"
                + sourceDelimiter
                + sourceParameter;
      this.errorPath = this.getInitParameter("error");
      String[] sourceFiles = sourceParameter.split(sourceDelimiter);
      URL[] sourceUrls = new URL[sourceFiles.length];
      for (int i = 0; i < sourceFiles.length; i++) {
        String sourceFile = sourceFiles[i];
        if (sourceFile.indexOf(':') < 0) sourceFile = "file:" + sourceFile;
        try {
          sourceUrls[i] = new URL(sourceFile);
        } catch (MalformedURLException e) {
          throw new RuntimeException(e);
        }
      }
      this.contextCache = new ScriptContextCache(sourceUrls);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Example #4
0
 private Object toArg(Class type, String val) throws Exception {
   if (type == String.class) {
     return val;
   } else if (type == int.class) {
     return Integer.parseInt(val);
   } else if (type == long.class) {
     return Long.parseLong(val);
   } else if (type == short.class) {
     return Short.parseShort(val);
   } else if (type == boolean.class) {
     return Boolean.parseBoolean(val);
   } else if (type == double.class) {
     return Double.parseDouble(val);
   } else if (type == float.class) {
     return Float.parseFloat(val);
   } else if (type == java.util.Map.class) {
     return new JSONParser().parse(val);
   } else if (type == java.util.List.class) {
     return new JSONParser().parseArray(val);
   }
   throw new RuntimeException("Unsupported type " + type.getName());
 }
  /**
   * Creates REST request.
   *
   * @param cmd Command.
   * @param params Parameters.
   * @return REST request.
   * @throws GridException If creation failed.
   */
  @Nullable
  private GridRestRequest createRequest(
      GridRestCommand cmd, Map<String, Object> params, ServletRequest req) throws GridException {
    GridRestRequest restReq;

    switch (cmd) {
      case CACHE_GET:
      case CACHE_GET_ALL:
      case CACHE_PUT:
      case CACHE_PUT_ALL:
      case CACHE_REMOVE:
      case CACHE_REMOVE_ALL:
      case CACHE_ADD:
      case CACHE_CAS:
      case CACHE_METRICS:
      case CACHE_REPLACE:
      case CACHE_DECREMENT:
      case CACHE_INCREMENT:
      case CACHE_APPEND:
      case CACHE_PREPEND:
        {
          GridRestCacheRequest restReq0 = new GridRestCacheRequest();

          restReq0.cacheName((String) params.get("cacheName"));
          restReq0.key(params.get("key"));
          restReq0.value(params.get("val"));
          restReq0.value2(params.get("val2"));

          Object val1 = params.get("val1");

          if (val1 != null) restReq0.value(val1);

          restReq0.cacheFlags(intValue("cacheFlags", params, 0));
          restReq0.ttl(longValue("exp", params, null));
          restReq0.initial(longValue("init", params, null));
          restReq0.delta(longValue("delta", params, null));

          if (cmd == CACHE_GET_ALL || cmd == CACHE_PUT_ALL || cmd == CACHE_REMOVE_ALL) {
            List<Object> keys = values("k", params);
            List<Object> vals = values("v", params);

            if (keys.size() < vals.size())
              throw new GridException(
                  "Number of keys must be greater or equals to number of values.");

            Map<Object, Object> map = U.newHashMap(keys.size());

            Iterator<Object> keyIt = keys.iterator();
            Iterator<Object> valIt = vals.iterator();

            while (keyIt.hasNext()) map.put(keyIt.next(), valIt.hasNext() ? valIt.next() : null);

            restReq0.values(map);
          }

          restReq = restReq0;

          break;
        }

      case TOPOLOGY:
      case NODE:
        {
          GridRestTopologyRequest restReq0 = new GridRestTopologyRequest();

          restReq0.includeMetrics(Boolean.parseBoolean((String) params.get("mtr")));
          restReq0.includeAttributes(Boolean.parseBoolean((String) params.get("attr")));

          restReq0.nodeIp((String) params.get("ip"));

          restReq0.nodeId(uuidValue("id", params));

          restReq = restReq0;

          break;
        }

      case EXE:
      case RESULT:
      case NOOP:
        {
          GridRestTaskRequest restReq0 = new GridRestTaskRequest();

          restReq0.taskId((String) params.get("id"));
          restReq0.taskName((String) params.get("name"));

          restReq0.params(values("p", params));

          restReq0.async(Boolean.parseBoolean((String) params.get("async")));

          restReq0.timeout(longValue("timeout", params, 0L));

          restReq = restReq0;

          break;
        }

      case LOG:
        {
          GridRestLogRequest restReq0 = new GridRestLogRequest();

          restReq0.path((String) params.get("path"));

          restReq0.from(intValue("from", params, -1));
          restReq0.to(intValue("to", params, -1));

          restReq = restReq0;

          break;
        }

      case VERSION:
        {
          restReq = new GridRestRequest();

          break;
        }

      default:
        throw new GridException("Invalid command: " + cmd);
    }

    restReq.address(new InetSocketAddress(req.getRemoteAddr(), req.getRemotePort()));

    restReq.command(cmd);

    if (params.containsKey("gridgain.login") || params.containsKey("gridgain.password")) {
      GridSecurityCredentials cred =
          new GridSecurityCredentials(
              (String) params.get("gridgain.login"), (String) params.get("gridgain.password"));

      restReq.credentials(cred);
    }

    String clientId = (String) params.get("clientId");

    try {
      if (clientId != null) restReq.clientId(UUID.fromString(clientId));
    } catch (Exception ignored) {
      // Ignore invalid client id. Rest handler will process this logic.
    }

    String destId = (String) params.get("destId");

    try {
      if (destId != null) restReq.destinationId(UUID.fromString(destId));
    } catch (IllegalArgumentException ignored) {
      // Don't fail - try to execute locally.
    }

    String sesTokStr = (String) params.get("sessionToken");

    try {
      if (sesTokStr != null) restReq.sessionToken(U.hexString2ByteArray(sesTokStr));
    } catch (IllegalArgumentException ignored) {
      // Ignore invalid session token.
    }

    return restReq;
  }
Example #6
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType(XML_RESPONSE_HEADER); // Talkback happens in XML form.
    response.setCharacterEncoding("UTF-8"); // Unicode++
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = null; // The talkback buffer.

    // handle startrecord
    Integer startRecord = 0;

    if (!(request.getParameter("startRecord") == null)) {
      try {
        startRecord = Integer.parseInt(request.getParameter("startRecord")) - 1;
      } catch (NumberFormatException e) {
        startRecord = 0;
      }
    }

    // maximumrecords
    Integer maximumRecords = Integer.parseInt(this.config.getProperty("default_maximumRecords"));
    if (!(request.getParameter("maximumRecords") == null)) {
      maximumRecords = Integer.parseInt(request.getParameter("maximumRecords"));
    }

    // operation
    String operation = request.getParameter("operation");

    // x_collection
    String x_collection = request.getParameter("x-collection");
    if (x_collection == null) x_collection = this.config.getProperty("default_x_collection");
    if (x_collection == null) operation = null;

    // sortkeys
    String sortKeys = request.getParameter("sortKeys");

    // sortorder
    String sortOrder = request.getParameter("sortOrder");

    // recordschema
    String recordSchema = request.getParameter("recordSchema");
    if (recordSchema == null) recordSchema = "dc";

    if (recordSchema.equalsIgnoreCase("dcx")) {
      recordSchema = "dcx";
    }

    if (recordSchema.equalsIgnoreCase("solr")) {
      recordSchema = "solr";
    }

    // query request
    String query = request.getParameter("query");
    String q = request.getParameter("q");

    // who is requestor ?
    String remote_ip = request.getHeader("X-FORWARDED-FOR");

    if (remote_ip == null) {
      remote_ip = request.getRemoteAddr().trim();
    } else {
      remote_ip = request.getHeader("X-FORWARDED-FOR");
    }

    // handle debug
    Boolean debug = Boolean.parseBoolean(request.getParameter("debug"));
    if (!debug) {
      out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
    }

    // handle query
    if ((query == null) && (q != null)) {
      query = q;
    } else {
      if ((query != null) && (q == null)) {
        q = query;
      } else {
        operation = null;
      }
    }

    // handle operation
    if (operation == null) {
      if (query != null) {
        operation = "searchRetrieve";
      } else {
        operation = "explain";
      }
    }

    //  searchRetrieve
    if (operation.equalsIgnoreCase("searchRetrieve")) {
      if (query == null) {
        operation = "explain";
        log.debug(operation + ":" + query);
      }
    }

    // start talking back.
    String[] sq = {""};
    String solrquery = "";

    // facet

    String facet = null;
    List<FacetField> fct = null;

    if (request.getParameter("facet") != null) {
      facet = request.getParameter("facet");
      log.debug("facet : " + facet);
    }

    if (operation == null) {
      operation = "searchretrieve";
    } else { // explain response
      if (operation.equalsIgnoreCase("explain")) {
        log.debug("operation = explain");
        out.write("<srw:explainResponse xmlns:srw=\"http://www.loc.gov/zing/srw/\">");
        out.write("</srw:explainResponse>");
      } else { // DEBUG routine
        operation = "searchretrieve";

        String triplequery = null;

        if (query.matches(".*?\\[.+?\\].*?")) { // New symantic syntax
          triplequery = symantic_query(query);
          query = query.split("\\[")[0] + " " + triplequery;
          log.fatal(triplequery);

          solrquery = CQLtoLucene.translate(query, log, config);
        } else {
          solrquery = CQLtoLucene.translate(query, log, config);
        }
        log.debug(solrquery);

        if (debug == true) {
          response.setContentType(HTML_RESPONSE_HEADER);
          out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
          out.write("<html><body>\n\n");
          out.write("'" + remote_ip + "'<br>\n");
          out.write("<form action='http://www.kbresearch.nl/kbSRU'>");
          out.write("<input type=text name=q value='" + query + "' size=120>");
          out.write("<input type=hidden name=debug value=True>");
          out.write("<input type=submit>");
          out.write("<table border=1><tr><td>");
          out.write("q</td><td>" + query + "</td></tr><tr>");
          out.write("<td>query out</td><td>" + URLDecoder.decode(solrquery) + "</td></tr>");
          out.write(
              "<tr><td>SOLR_URL</td><td> <a href='"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/?q="
                  + solrquery
                  + "'>"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/select/?q="
                  + solrquery
                  + "</a><br>"
                  + this.config.getProperty("solr_url")
                  + solrquery
                  + "</td></tr>");
          out.write(
              "<b>SOLR_QUERY</b> : <BR> <iframe width=900 height=400 src='"
                  + this.config.getProperty(
                      "collection." + x_collection.toLowerCase() + ".solr_baseurl")
                  + "/../?q="
                  + solrquery
                  + "'></iframe><BR>");
          out.write(
              "<b>SRU_QUERY</b> : <BR> <a href="
                  + this.config.getProperty("baseurl")
                  + "?q="
                  + query
                  + "'>"
                  + this.config.getProperty("baseurl")
                  + "?q="
                  + query
                  + "</a><br><iframe width=901 height=400 src='http://www.kbresearch.nl/kbSRU/?q="
                  + query
                  + "'></iframe><BR>");
          out.write(
              "<br><b>JSRU_QUERY</b> : <BR><a href='http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection="
                  + x_collection
                  + "'>http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection=GGC</a><br><iframe width=900 height=400 src='http://jsru.kb.nl/sru/?query="
                  + query
                  + "&x-collection=GGC'></iframe>");

        } else { // XML SearchRetrieve response
          String url =
              this.config.getProperty("collection." + x_collection.toLowerCase() + ".solr_baseurl");
          String buffer = "";
          CommonsHttpSolrServer server = null;
          server = new CommonsHttpSolrServer(url);
          log.fatal("URSING " + url);
          server.setParser(new XMLResponseParser());
          int numfound = 0;
          try {
            SolrQuery do_query = new SolrQuery();
            do_query.setQuery(solrquery);
            do_query.setRows(maximumRecords);
            do_query.setStart(startRecord);

            if ((sortKeys != null) && (sortKeys.length() > 1)) {
              if (sortOrder != null) {
                if (sortOrder.equals("asc")) {
                  do_query.setSortField(sortKeys, SolrQuery.ORDER.asc);
                }
                if (sortOrder.equals("desc")) {
                  do_query.setSortField(sortKeys, SolrQuery.ORDER.desc);
                }
              } else {
                for (String str : sortKeys.trim().split(",")) {
                  str = str.trim();
                  if (str.length() > 1) {
                    if (str.equals("date")) {
                      do_query.setSortField("date_date", SolrQuery.ORDER.desc);
                      log.debug("SORTORDERDEBUG | DATE! " + str + " | ");
                      break;
                    } else {
                      do_query.setSortField(str + "_str", SolrQuery.ORDER.asc);
                      log.debug("SORTORDERDEBUG | " + str + " | ");
                      break;
                    }
                  }
                }
              }
            }

            if (facet != null) {
              if (facet.indexOf(",") > 1) {
                for (String str : facet.split(",")) {
                  if (str.indexOf("date") > 1) {
                    do_query.addFacetField(str);
                  } else {
                    do_query.addFacetField(str);
                  }
                  // do_query.setParam("facet.method", "enum");
                }
                // q.setFacetSort(false);
              } else {
                do_query.addFacetField(facet);
              }
              do_query.setFacet(true);
              do_query.setFacetMinCount(1);
              do_query.setFacetLimit(-1);
            }

            log.fatal(solrquery);

            QueryResponse rsp = null;
            boolean do_err = false;
            boolean do_sugg = false;
            SolrDocumentList sdl = null;
            String diag = "";
            StringBuffer suggest = new StringBuffer("");

            String content = "1";

            SolrQuery spellq = do_query;
            try {
              rsp = server.query(do_query);
            } catch (SolrServerException e) {
              String header = this.SRW_HEADER.replaceAll("\\$numberOfRecords", "0");
              out.write(header);
              diag = this.SRW_DIAG.replaceAll("\\$error", e.getMessage());
              do_err = true;
              rsp = null;
            }

            log.fatal("query done..");
            if (!(do_err)) { // XML dc response

              SolrDocumentList docs = rsp.getResults();
              numfound = (int) docs.getNumFound();
              int count = startRecord;
              String header =
                  this.SRW_HEADER.replaceAll("\\$numberOfRecords", Integer.toString(numfound));
              out.write(header);
              out.write("<srw:records>");

              Iterator<SolrDocument> iter = rsp.getResults().iterator();

              while (iter.hasNext()) {
                count += 1;
                if (recordSchema.equalsIgnoreCase("dc")) {
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                  out.write(
                      "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" xmlns:facets=\"info:srw/extension/4/facets\" >");
                  StringBuffer result = new StringBuffer("");

                  construct_lucene_dc(result, resultDoc);

                  out.write(result.toString());
                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }

                if (recordSchema.equalsIgnoreCase("solr")) {
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/solr</srw:recordSchema>");
                  out.write("<srw:recordData xmlns:expand=\"http://www.kbresearch.nl/expand\">");
                  StringBuffer result = new StringBuffer("");
                  construct_lucene_solr(result, resultDoc);
                  out.write(result.toString());

                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }

                if (recordSchema.equalsIgnoreCase("dcx")) { // XML dcx response
                  out.write("<srw:record>");
                  out.write("<srw:recordPacking>xml</srw:recordPacking>");
                  out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                  out.write(
                      "<srw:recordData><srw_dc:dc xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/marc.relators/\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                  SolrDocument resultDoc = iter.next();
                  content = (String) resultDoc.getFieldValue("id");

                  String dcx_data =
                      helpers.getOAIdcx(
                          "http://services.kb.nl/mdo/oai?verb=GetRecord&identifier=" + content,
                          log);
                  if (x_collection.equalsIgnoreCase("ggc-thes")) {
                    dcx_data =
                        helpers.getOAIdcx(
                            "http://serviceso.kb.nl/mdo/oai?verb=GetRecord&identifier=" + content,
                            log);
                  }

                  if (!(dcx_data.length() == 0)) {
                    out.write(dcx_data);
                  } else {
                    // Should not do this!!

                    out.write("<srw:record>");
                    out.write("<srw:recordPacking>xml</srw:recordPacking>");
                    out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                    out.write(
                        "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" >");
                    StringBuffer result = new StringBuffer("");

                    construct_lucene_dc(result, resultDoc);

                    out.write(result.toString());
                    out.write("</srw:recordData>");
                    out.write(
                        "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                    out.write("</srw:record>");
                  }

                  out.write("</srw_dc:dc>");

                  StringBuffer expand_data;
                  boolean expand = false;

                  if (content.startsWith("GGC-THES:AC:")) {
                    String tmp_content = "";
                    tmp_content = content.replaceFirst("GGC-THES:AC:", "");
                    log.fatal("calling get");
                    expand_data =
                        new StringBuffer(
                            helpers.getExpand(
                                "http://www.kbresearch.nl/general/lod_new/get/"
                                    + tmp_content
                                    + "?format=rdf",
                                log));
                    log.fatal("get finini");

                    if (expand_data.toString().length() > 4) {

                      out.write(
                          "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                      out.write(expand_data.toString());
                      expand = true;
                    }
                  } else {
                    expand_data =
                        new StringBuffer(
                            helpers.getExpand(
                                "http://www.kbresearch.nl/ANP.cgi?q=" + content, log));
                    if (expand_data.toString().length() > 0) {
                      if (!expand) {
                        out.write(
                            "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                        expand = true;
                      }
                      out.write(expand_data.toString());
                    }
                  }
                  if (expand) {
                    out.write("</srw_dc:expand>");
                  }

                  out.write("</srw:recordData>");
                  out.write(
                      "<srw:recordPosition>" + Integer.toString(count) + "</srw:recordPosition>");
                  out.write("</srw:record>");
                }
              }
            }

            if ((do_err) || (numfound == 0)) {
              log.fatal("I haz suggestions");

              try {
                spellq.setParam("spellcheck", true);
                spellq.setQueryType("/spell");
                server = new CommonsHttpSolrServer(url);
                rsp = server.query(spellq);
                sdl = rsp.getResults();
                SpellCheckResponse spell;
                spell = rsp.getSpellCheckResponse();
                List<SpellCheckResponse.Suggestion> suggestions = spell.getSuggestions();
                if (suggestions.isEmpty() == false) {
                  suggest.append("<srw:extraResponseData>");
                  suggest.append("<suggestions>");

                  for (SpellCheckResponse.Suggestion sugg : suggestions) {
                    suggest.append("<suggestionfor>" + sugg.getToken() + "</suggestionfor>");
                    for (String item : sugg.getSuggestions()) {
                      suggest.append("<suggestion>" + item + "</suggestion>");
                    }
                    suggest.append("</suggestions>");
                    suggest.append("</srw:extraResponseData>");
                  }
                  do_sugg = true;
                }
              } catch (Exception e) {
                rsp = null;
                // log.fatal(e.toString());
              }
              ;
            }
            ;

            if (!do_err) {
              if (facet != null) {

                try {
                  fct = rsp.getFacetFields();
                  out.write("<srw:facets>");

                  for (String str : facet.split(",")) {
                    out.write("<srw:facet>");
                    out.write("<srw:facetType>");
                    out.write(str);
                    out.write("</srw:facetType>");

                    for (FacetField f : fct) {
                      log.debug(f.getName());
                      // if (f.getName().equals(str+"_str") || (f.getName().equals(str+"_date")) ) {
                      List<FacetField.Count> facetEnties = f.getValues();
                      for (FacetField.Count fcount : facetEnties) {
                        out.write("<srw:facetValue>");
                        out.write("<srw:valueString>");
                        out.write(helpers.xmlEncode(fcount.getName()));
                        out.write("</srw:valueString>");
                        out.write("<srw:count>");
                        out.write(Double.toString(fcount.getCount()));
                        out.write("</srw:count>");
                        out.write("</srw:facetValue>");
                        //   }
                      }
                    }
                    out.write("</srw:facet>");
                  }
                  out.write("</srw:facets>");
                  startRecord += 1;
                } catch (Exception e) {
                }

                // log.fatal(e.toString()); }
              }
            } else {
              out.write(diag);
            }
            out.write("</srw:records>"); // SearchRetrieve response footer
            String footer = this.SRW_FOOTER.replaceAll("\\$query", helpers.xmlEncode(query));
            footer = footer.replaceAll("\\$startRecord", (startRecord).toString());
            footer = footer.replaceAll("\\$maximumRecords", maximumRecords.toString());
            footer = footer.replaceAll("\\$recordSchema", recordSchema);
            if (do_sugg) {
              out.write(suggest.toString());
            }
            out.write(footer);
          } catch (MalformedURLException e) {
            out.write(e.getMessage());
          } catch (IOException e) {
            out.write("TO ERR is Human");
          }
        }
      }
    }
    out.close();
  }
Example #7
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException {
    assert emf != null; // Make sure injection went through correctly.
    EntityManager em = null;
    try {

      // begin a transaction
      utx.begin();
      // create an em.
      // Since the em is created inside a transaction, it is associsated with
      // the transaction

      em = emf.createEntityManager();

      // Get the data from user's form
      String titre = (String) request.getParameter("titre");
      Boolean peutEtreReemprunter = Boolean.valueOf(request.getParameter("peutEtreReemprunter"));
      String typeString = (String) request.getParameter("type");

      ProduitType type = null;
      for (ProduitType t : ProduitType.values()) {
        if (t.toString().equals(typeString)) {
          type = t;
        }
      }

      Date datePublication = new Date();

      String auteur1Txt = (String) request.getParameter("auteur1");
      String auteur2Txt = (String) request.getParameter("auteur2");
      String auteur3Txt = (String) request.getParameter("auteur3");

      Auteur auteur1 = null;
      try {
        auteur1 =
            (Auteur)
                em.createNamedQuery("findAuteur", Auteur.class)
                    .setParameter("nom", auteur1Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      Auteur auteur2 = null;
      try {
        auteur2 =
            (Auteur)
                em.createNamedQuery("findAuteur", Auteur.class)
                    .setParameter("nom", auteur2Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      Auteur auteur3 = null;
      try {
        auteur3 =
            (Auteur)
                em.createNamedQuery("findAuteur", Auteur.class)
                    .setParameter("nom", auteur3Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      List<Auteur> auteurs = new ArrayList<Auteur>();
      if (auteur1 != null) auteurs.add(auteur1);
      if (auteur2 != null) auteurs.add(auteur2);
      if (auteur3 != null) auteurs.add(auteur3);

      String genre1Txt = (String) request.getParameter("genre1");
      String genre2Txt = (String) request.getParameter("genre2");
      String genre3Txt = (String) request.getParameter("genre3");

      Genre genre1 = null;
      try {
        genre1 =
            (Genre)
                em.createNamedQuery("findGenre", Genre.class)
                    .setParameter("nom", genre1Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      Genre genre2 = null;
      try {
        genre2 =
            (Genre)
                em.createNamedQuery("findGenre", Genre.class)
                    .setParameter("nom", genre2Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      Genre genre3 = null;
      try {
        genre3 =
            (Genre)
                em.createNamedQuery("findGenre", Genre.class)
                    .setParameter("nom", genre3Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      List<Genre> genres = new ArrayList<Genre>();
      if (genre1 != null) genres.add(genre1);
      if (genre2 != null) genres.add(genre2);
      if (genre3 != null) genres.add(genre3);

      // Create a person instance out of it
      Produit produit =
          new Produit(titre, peutEtreReemprunter, datePublication, auteurs, genres, type);

      // persist the person entity
      em.persist(produit);

      // commit transaction which will trigger the em to
      // commit newly created entity into database
      utx.commit();

      // Forward to ListPerson servlet to list persons along with the newly
      // created person above
      request.getRequestDispatcher("ListProduit").forward(request, response);
    } catch (Exception ex) {
      throw new ServletException(ex);
    } finally {
      // close the em to release any resources held up by the persistebce provider
      if (em != null) {
        em.close();
      }
    }
  }
  public static void load(Properties properties)
      throws NoSuchAlgorithmException, InstantiationException, IllegalAccessException,
          ClassNotFoundException, IOException, NoSuchProviderException {
    CsrfGuard csrfGuard = SingletonHolder.instance;

    /** load simple properties * */
    csrfGuard.setLogger(
        (ILogger)
            Class.forName(
                    properties.getProperty(
                        "org.owasp.csrfguard.Logger", "org.owasp.csrfguard.log.ConsoleLogger"))
                .newInstance());
    csrfGuard.setTokenName(
        properties.getProperty("org.owasp.csrfguard.TokenName", "OWASP_CSRFGUARD"));
    csrfGuard.setTokenLength(
        Integer.parseInt(properties.getProperty("org.owasp.csrfguard.TokenLength", "32")));
    csrfGuard.setRotate(
        Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Rotate", "false")));
    csrfGuard.setTokenPerPage(
        Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.TokenPerPage", "false")));
    csrfGuard.setTokenPerPagePrecreate(
        Boolean.valueOf(
            properties.getProperty("org.owasp.csrfguard.TokenPerPagePrecreate", "false")));
    csrfGuard.setPrng(
        SecureRandom.getInstance(
            properties.getProperty("org.owasp.csrfguard.PRNG", "SHA1PRNG"),
            properties.getProperty("org.owasp.csrfguard.PRNG.Provider", "SUN")));
    csrfGuard.setNewTokenLandingPage(
        properties.getProperty("org.owasp.csrfguard.NewTokenLandingPage"));

    // default to false if newTokenLandingPage is not set; default to true if set.
    if (csrfGuard.getNewTokenLandingPage() == null) {
      csrfGuard.setUseNewTokenLandingPage(
          Boolean.valueOf(
              properties.getProperty("org.owasp.csrfguard.UseNewTokenLandingPage", "false")));
    } else {
      csrfGuard.setUseNewTokenLandingPage(
          Boolean.valueOf(
              properties.getProperty("org.owasp.csrfguard.UseNewTokenLandingPage", "true")));
    }
    csrfGuard.setSessionKey(
        properties.getProperty("org.owasp.csrfguard.SessionKey", "OWASP_CSRFGUARD_KEY"));
    csrfGuard.setAjax(Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Ajax", "false")));
    csrfGuard.setProtect(
        Boolean.valueOf(properties.getProperty("org.owasp.csrfguard.Protect", "false")));

    /** first pass: instantiate actions * */
    Map<String, IAction> actionsMap = new HashMap<String, IAction>();

    for (Object obj : properties.keySet()) {
      String key = (String) obj;

      if (key.startsWith(ACTION_PREFIX)) {
        String directive = key.substring(ACTION_PREFIX.length());
        int index = directive.indexOf('.');

        /** action name/class * */
        if (index < 0) {
          String actionClass = properties.getProperty(key);
          IAction action = (IAction) Class.forName(actionClass).newInstance();

          action.setName(directive);
          actionsMap.put(action.getName(), action);
          csrfGuard.getActions().add(action);
        }
      }
    }

    /** second pass: initialize action parameters * */
    for (Object obj : properties.keySet()) {
      String key = (String) obj;

      if (key.startsWith(ACTION_PREFIX)) {
        String directive = key.substring(ACTION_PREFIX.length());
        int index = directive.indexOf('.');

        /** action name/class * */
        if (index >= 0) {
          String actionName = directive.substring(0, index);
          IAction action = actionsMap.get(actionName);

          if (action == null) {
            throw new IOException(
                String.format("action class %s has not yet been specified", actionName));
          }

          String parameterName = directive.substring(index + 1);
          String parameterValue = properties.getProperty(key);

          action.setParameter(parameterName, parameterValue);
        }
      }
    }

    /** ensure at least one action was defined * */
    if (csrfGuard.getActions().size() <= 0) {
      throw new IOException("failure to define at least one action");
    }

    /** initialize protected, unprotected pages * */
    for (Object obj : properties.keySet()) {
      String key = (String) obj;

      if (key.startsWith(PROTECTED_PAGE_PREFIX)) {
        String directive = key.substring(PROTECTED_PAGE_PREFIX.length());
        int index = directive.indexOf('.');

        /** page name/class * */
        if (index < 0) {
          String pageUri = properties.getProperty(key);

          csrfGuard.getProtectedPages().add(Pattern.compile(pageUri));
        }
      }

      if (key.startsWith(UNPROTECTED_PAGE_PREFIX)) {
        String directive = key.substring(UNPROTECTED_PAGE_PREFIX.length());
        int index = directive.indexOf('.');

        /** page name/class * */
        if (index < 0) {
          String pageUri = properties.getProperty(key);

          csrfGuard.getUnprotectedPages().add(Pattern.compile(pageUri));
        }
      }
    }

    /** initialize protected methods * */
    String methodList = properties.getProperty("org.owasp.csrfguard.ProtectedMethods");
    if (methodList != null && methodList.trim().length() != 0) {
      for (String method : methodList.split(",")) {
        csrfGuard.getProtectedMethods().add(method.trim());
      }
    }
  }
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    javax.servlet.jsp.PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html;charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");

      User user = null;
      UserFactory userFactory = UserFactory.getInstance();
      String userID = request.getParameter("userID");
      try {
        UserFactory.init();
        user = userFactory.getUser(userID);
      } catch (Exception e) {
        throw new ServletException("Could not find user " + userID + " in user factory.", e);
      }

      out.write("\n");
      out.write("<html>\n");
      out.write("<head>\n    ");
      out.write("<title>WebTelemetry -  | User Management | User Detail");
      out.write("</title>\n    ");
      out.write("<base HREF=\"");
      out.print(org.opennms.web.Util.calculateUrlBase(request));
      out.write("\" />\n    ");
      out.write(
          "<link rel=\"stylesheet\" type=\"text/css\" href=\"/wt-portal/css/default.css\" />\n\t");
      out.write("<script type=\"text/javascript\" src=\"/wt-portal/javascript/WTtools.js\">");
      out.write("</script>\n");
      out.write("</head>\n");
      out.write("<body>\n");
      String title = " User Management  - Detail Summary for: " + userID;
      out.write("\n");
      /* ----  c:if ---- */
      org.apache.taglibs.standard.tag.el.core.IfTag _jspx_th_c_if_0 =
          (org.apache.taglibs.standard.tag.el.core.IfTag)
              _jspx_tagPool_c_if_test.get(org.apache.taglibs.standard.tag.el.core.IfTag.class);
      _jspx_th_c_if_0.setPageContext(pageContext);
      _jspx_th_c_if_0.setParent(null);
      _jspx_th_c_if_0.setTest("${not param.orgAdminPopup}");
      int _jspx_eval_c_if_0 = _jspx_th_c_if_0.doStartTag();
      if (_jspx_eval_c_if_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
        do {
          out.write("\n    ");
          JspRuntimeLibrary.include(
              request,
              response,
              "/includes/header.jsp"
                  + "?"
                  + "title="
                  + java.net.URLEncoder.encode("" + title)
                  + "&"
                  + "help="
                  + "monitoringadmin%2Fusers%2FWTHelp_User.html",
              out,
              false);
          out.write("\n");
          int evalDoAfterBody = _jspx_th_c_if_0.doAfterBody();
          if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break;
        } while (true);
      }
      if (_jspx_th_c_if_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) return;
      _jspx_tagPool_c_if_test.reuse(_jspx_th_c_if_0);
      out.write("\n");
      if (_jspx_meth_c_if_1(pageContext)) return;
      out.write("\n\n");
      out.write("<!-- BEGIN FRAMING TABLE:open tags, keep at 100%-->\n");
      out.write("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n\t");
      out.write("<tr>\n\t\t");
      out.write("<td width=\"10\">");
      out.write(
          "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"1\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
      out.write("</td>\n\t\t");
      out.write("<td>\n");
      out.write("<!-- END FRAMING TABLE:open tags, keep at 100%-->\n");
      out.write("<table width=\"98%\"border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n    ");
      out.write("<tr class=\"tableHeader\">\n        ");
      out.write("<td class=\"tableHeader\" colspan=\"2\">User Information");
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\" width=\"25%\">");
      out.write("<b>Full Name:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\" width=\"75%\">");
      out.print(user.getFullName());
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowDark\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Comments:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(user.getUserComments());
      out.write("</td>\n     ");
      out.write("</tr>\n");
      out.write("</table>\n");
      out.write("<br>\n");
      out.write("<table width=\"98%\"border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n    ");
      out.write("<tr class=\"tableHeader\">\n        ");
      out.write("<td class=\"tableHeader\" colspan=\"2\">Notification Information");
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\" width=\"25%\">");
      out.write("<b>Email:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\" width=\"75%\">");
      out.print(userFactory.getEmail(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowDark\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Pager Email:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(userFactory.getPagerEmail(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Numerical Service:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(userFactory.getNumericPage(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowDark\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Numerical Pin:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(userFactory.getNumericPin(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Text Service:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(userFactory.getTextPage(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowDark\">\n        ");
      out.write("<td class=\"tableText\">");
      out.write("<b>Text Pin:");
      out.write("</b>");
      out.write("</td>\n        ");
      out.write("<td class=\"tableText\">");
      out.print(userFactory.getTextPin(userID));
      out.write("</td>\n     ");
      out.write("</tr>\n");
      out.write("</table>\n");
      out.write("<br>\n");
      out.write("<table width=\"98%\"border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n    ");
      out.write("<tr class=\"tableHeader\">\n        ");
      out.write("<td class=\"tableHeader\" colspan=\"2\">Duty Schedules");
      out.write("</td>\n     ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\" colspan=\"2\">");
      out.write("<br />\n        ");
      out.write("<!-- weekly schedule -->\n                ");
      out.write(
          "<table width=\"50%\" border=\"1\" bordercolor=\"#999999\" cellspacing=\"0\" cellpadding=\"2\" >\n\t\t\t");
      Collection dutySchedules = user.getDutyScheduleCollection();
      out.write("\n                        ");

      int i = 0;
      Iterator iter = dutySchedules.iterator();
      while (iter.hasNext()) {
        DutySchedule tmp = new DutySchedule((String) iter.next());
        Vector curSched = tmp.getAsVector();
        i++;

        out.write("\n                        ");
        out.write("<tr>\n                           ");
        ChoiceFormat days = new ChoiceFormat("0#Mo|1#Tu|2#We|3#Th|4#Fr|5#Sa|6#Su");
        for (int j = 0; j < 7; j++) {
          Boolean curDay = (Boolean) curSched.get(j);

          out.write("\n                          ");
          out.write("<td width=\"5%\">\n                           ");
          out.print((curDay.booleanValue() ? days.format(j) : "X"));
          out.write("\n                          ");
          out.write("</td>\n                          ");
        }
        out.write("\n                          ");
        out.write("<td width=\"5%\">\n                            ");
        out.print(curSched.get(7));
        out.write("\n                          ");
        out.write("</td>\n                          ");
        out.write("<td width=\"5%\">\n                            ");
        out.print(curSched.get(8));
        out.write("\n                          ");
        out.write("</td>\n                        ");
        out.write("</tr>\n                        ");
      }
      out.write("\n                      ");
      out.write("</table>\n        ");
      out.write("<!-- end weekly schedule -->   \n        ");
      out.write("</td>\n    ");
      out.write("</tr>\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\" colspan=\"2\">");
      out.write(
          "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"4\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
      out.write("</td>\n    ");
      out.write("</tr> \n");
      out.write("</table>\n");
      out.write("<br>");
      out.write("<br>\n");
      out.write("<b>Member of the Following Organizations &amp; Groups:");
      out.write("</b>\n");
      out.write("<!-- BEGIN: NEW ASSIGNED GROUPS TABLE -->\n");
      out.write("<table width=\"98%\"border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n\n    ");

      // Get the user's orgs
      WTOrganizationDAO orgDAO = DAOImpl.OrgDAO;
      WTOrganization[] orgs = orgDAO.getWTOrganization();

      if (orgs != null) {
        // Loop thru orgs
        for (int idx = 0; idx < orgs.length; idx++) {

          out.write("\n\n    ");
          out.write("<tr class=\"tableHeader\">\n        ");
          out.write("<td class=\"tableHeader\" colspan=\"2\">Organization Name: ");
          out.print(orgs[idx].getName());
          out.write("</td>\n\t");
          out.write("</tr>\n    ");
          out.write("<tr class=\"tableRowLight\">\n        ");
          out.write("<td class=\"tableText\" width=\"25%\">");
          out.write("<b>Assigned Groups:");
          out.write("</b>");
          out.write("</td>\n        ");
          out.write("<td class=\"tableText\" width=\"75%\">\n            ");

          // Get the orgs groups
          WTGroupManager grpMgr = ManagersImpl.GroupManager;
          int[] orgids = {orgs[idx].getID()};
          List groups = grpMgr.getUserGroups(user.getUserId(), orgids);

          if (groups != null) {
            // Loop thru the groups
            for (Iterator iterGrps = groups.iterator(); iterGrps.hasNext(); ) {
              WTGroup group = (WTGroup) iterGrps.next();
              WTRole role = (group.getRoles() == null ? null : (WTRole) group.getRoles().get(0));

              out.write("\n                    ");
              out.print(group.getName());
              out.write(" (");
              out.print((role == null ? "" : role.getName()));
              out.write(")");
              out.write("<br/>\n            ");
            }
          }

          out.write("\n\n        ");
          out.write("</td>\n\t");
          out.write("</tr>\n\n    ");
        }
      }

      out.write("\n\n    ");
      out.write("<tr class=\"tableRowLight\">\n        ");
      out.write("<td class=\"tableText\" colspan=\"2\">");
      out.write(
          "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"4\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
      out.write("</td>\n    ");
      out.write("</tr> \n");
      out.write("</table>\n");
      out.write("<!-- END: NEW ASSIGNED GROUPS TABLE -->\n\n\n");
      out.write("<!-- BEGIN FRAMING TABLE:close tags-->\n\t\t");
      out.write("</td>\n\t");
      out.write("</tr>\n");
      out.write("</table>\n");
      out.write("<!-- END FRAMING TABLE:close tags-->\n");
      out.write("<br>\n\n");
      JspRuntimeLibrary.include(request, response, "/includes/footer.jsp", out, false);
      out.write("\n");
      out.write("</body>\n");
      out.write("</html>\n\n");
    } catch (Throwable t) {
      out = _jspx_out;
      if (out != null && out.getBufferSize() != 0) out.clearBuffer();
      if (pageContext != null) pageContext.handlePageException(t);
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
    }
  }
  /** 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();

    PreparedStatement pstmt = null;
    Connection conn = 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));

      GridParams pars = (GridParams) inputPar;

      BigDecimal rootProgressiveHIE01 =
          (BigDecimal) pars.getOtherGridParams().get(ApplicationConsts.ROOT_PROGRESSIVE_HIE01);
      BigDecimal progressiveHIE01 =
          (BigDecimal) pars.getOtherGridParams().get(ApplicationConsts.PROGRESSIVE_HIE01);
      BigDecimal progressiveHIE02 =
          (BigDecimal) pars.getOtherGridParams().get(ApplicationConsts.PROGRESSIVE_HIE02);
      Boolean productsOnly =
          (Boolean) pars.getOtherGridParams().get(ApplicationConsts.PRODUCTS_ONLY);
      Boolean compsOnly =
          (Boolean) pars.getOtherGridParams().get(ApplicationConsts.COMPONENTS_ONLY);

      HierarchyLevelVO vo =
          (HierarchyLevelVO) pars.getOtherGridParams().get(ApplicationConsts.TREE_FILTER);
      if (vo != null) {
        progressiveHIE01 = vo.getProgressiveHIE01();
        progressiveHIE02 = vo.getProgressiveHie02HIE01();
      }

      // retrieve companies list...
      ArrayList companiesList =
          ((JAIOUserSessionParameters) userSessionPars).getCompanyBa().getCompaniesList("ITM01");
      String companies = "";
      for (int i = 0; i < companiesList.size(); i++)
        companies += "'" + companiesList.get(i).toString() + "',";
      companies = companies.substring(0, companies.length() - 1);

      String sql =
          "select ITM01_ITEMS.COMPANY_CODE_SYS01,ITM01_ITEMS.ITEM_CODE,SYS10_TRANSLATIONS.DESCRIPTION,ITM01_ITEMS.PROGRESSIVE_HIE02,ITM01_ITEMS.MIN_SELLING_QTY_UM_CODE_REG02,"
              + "ITM01_ITEMS.PROGRESSIVE_HIE01,ITM01_ITEMS.SERIAL_NUMBER_REQUIRED,REG02_MEASURE_UNITS.DECIMALS "
              + " from ITM01_ITEMS,SYS10_TRANSLATIONS,REG02_MEASURE_UNITS where "
              + "ITM01_ITEMS.PROGRESSIVE_HIE02=? and "
              + "ITM01_ITEMS.PROGRESSIVE_SYS10=SYS10_TRANSLATIONS.PROGRESSIVE and "
              + "SYS10_TRANSLATIONS.LANGUAGE_CODE=? and "
              + "ITM01_ITEMS.COMPANY_CODE_SYS01 in ("
              + companies
              + ") and "
              + "ITM01_ITEMS.ENABLED='Y' and "
              + "ITM01_ITEMS.MIN_SELLING_QTY_UM_CODE_REG02=REG02_MEASURE_UNITS.UM_CODE ";

      if (productsOnly != null && productsOnly.booleanValue())
        sql += " and ITM01_ITEMS.MANUFACTURE_CODE_PRO01 is not null ";

      if (compsOnly != null && compsOnly.booleanValue())
        sql += " and ITM01_ITEMS.MANUFACTURE_CODE_PRO01 is null ";

      if (rootProgressiveHIE01 == null || !rootProgressiveHIE01.equals(progressiveHIE01)) {
        // retrieve all subnodes of the specified node...
        pstmt =
            conn.prepareStatement(
                "select HIE01_LEVELS.PROGRESSIVE,HIE01_LEVELS.PROGRESSIVE_HIE01,HIE01_LEVELS.LEV from HIE01_LEVELS "
                    + "where ENABLED='Y' and PROGRESSIVE_HIE02=? and PROGRESSIVE>=? "
                    + "order by LEV,PROGRESSIVE_HIE01,PROGRESSIVE");
        pstmt.setBigDecimal(1, progressiveHIE02);
        pstmt.setBigDecimal(2, progressiveHIE01);
        ResultSet rset = pstmt.executeQuery();

        HashSet currentLevelNodes = new HashSet();
        HashSet newLevelNodes = new HashSet();
        String nodes = "";
        int currentLevel = -1;
        while (rset.next()) {
          if (currentLevel != rset.getInt(3)) {
            // next level...
            currentLevel = rset.getInt(3);
            currentLevelNodes = newLevelNodes;
            newLevelNodes = new HashSet();
          }
          if (rset.getBigDecimal(1).equals(progressiveHIE01)) {
            newLevelNodes.add(rset.getBigDecimal(1));
            nodes += rset.getBigDecimal(1) + ",";
          } else if (currentLevelNodes.contains(rset.getBigDecimal(2))) {
            newLevelNodes.add(rset.getBigDecimal(1));
            nodes += rset.getBigDecimal(1) + ",";
          }
        }
        rset.close();
        pstmt.close();
        if (nodes.length() > 0) nodes = nodes.substring(0, nodes.length() - 1);
        sql += " and PROGRESSIVE_HIE01 in (" + nodes + ")";
      }

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("companyCodeSys01ITM01", "ITM01_ITEMS.COMPANY_CODE_SYS01");
      attribute2dbField.put("itemCodeITM01", "ITM01_ITEMS.ITEM_CODE");
      attribute2dbField.put("descriptionSYS10", "SYS10_TRANSLATIONS.DESCRIPTION");
      attribute2dbField.put("progressiveHie02ITM01", "ITM01_ITEMS.PROGRESSIVE_HIE02");
      attribute2dbField.put(
          "minSellingQtyUmCodeReg02ITM01", "ITM01_ITEMS.MIN_SELLING_QTY_UM_CODE_REG02");
      attribute2dbField.put("progressiveHie01ITM01", "ITM01_ITEMS.PROGRESSIVE_HIE01");
      attribute2dbField.put("serialNumberRequiredITM01", "ITM01_ITEMS.SERIAL_NUMBER_REQUIRED");
      attribute2dbField.put("decimalsREG02", "REG02_MEASURE_UNITS.DECIMALS");

      ArrayList values = new ArrayList();
      values.add(progressiveHIE02);
      values.add(serverLanguageId);

      // read from ITM01 table...
      Response answer =
          QueryUtil.getQuery(
              conn,
              userSessionPars,
              sql,
              values,
              attribute2dbField,
              GridItemVO.class,
              "Y",
              "N",
              context,
              pars,
              50,
              true);

      // 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));
      return answer;

    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while fetching items list",
          ex);
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }
      try {
        ConnectionManager.releaseConnection(conn, context);
      } catch (Exception ex1) {
      }
    }
  }
Example #11
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);
  }
}
  private void handleLoginPost(
      Request request, HttpServletResponse httpServletResponse, boolean secured) throws Exception {
    String userId = request.getParameter(PARAM_USER_ID);
    String password = request.getParameter(PARAM_PASSWORD);
    String rememberAccountStr = request.getParameter(PARAM_REMEMBER_ACCOUNT);
    boolean rememberAccount = Boolean.parseBoolean(rememberAccountStr);
    LoginInfo.SessionInfo sessionInfo = UserHelpers.getSessionInfo(request);

    logOut(sessionInfo.browserId);

    User user = userDb.get(userId);
    if (user == null) {
      WebUtils.redirectToError("User " + userId + " not found", request, httpServletResponse);
      return;
    }

    if (!user.checkPassword(password)) {
      WebUtils.redirectToError("Invalid password", request, httpServletResponse);
      return;
    }

    if (!user.active) {
      WebUtils.redirectToError(
          "Account for User " + userId + " needs to be activated", request, httpServletResponse);
      return;
    }

    LOG.info("Logged in user " + userId);

    sessionInfo.sessionId = null;
    if (sessionInfo.browserId == null) {
      sessionInfo.browserId = getRandomId();
    } else {
      for (LoginInfo loginInfo : loginInfoDb.getLoginsForBrowser(sessionInfo.browserId)) {
        if (userId.equals(loginInfo.userId)) {
          sessionInfo.sessionId = loginInfo.sessionId;
          break;
        }
      }
    }

    long expireOn = System.currentTimeMillis() + Config.getConfig().loginExpireInterval;
    if (sessionInfo.sessionId == null) {
      sessionInfo.sessionId = getRandomId();
      Config config = Config.getConfig();
      loginInfoDb.add(
          new LoginInfo(
              sessionInfo.browserId,
              sessionInfo.sessionId,
              userId,
              expireOn,
              rememberAccount,
              config.defaultStyle,
              config.defaultItemsPerPage,
              config.defaultFeedDateFormat));
      LOG.info(String.format("Logging in in a new session. User: %s", user));
    } else {
      loginInfoDb.updateExpireTime(sessionInfo.browserId, sessionInfo.sessionId, expireOn);
      LOG.info(String.format("Logging in in an existing session. User: %s", user));
    }

    WebUtils.saveCookies(
        httpServletResponse, secured, sessionInfo.browserId, sessionInfo.sessionId);

    httpServletResponse.sendRedirect("/");
  }
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    javax.servlet.jsp.PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html;charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n\n\n");
      out.write("\n\n");

      Vector vMibs = (Vector) request.getAttribute("mibs");

      String strIp = (String) request.getAttribute("ip");
      if (strIp == null) strIp = "";

      String strCommunity = (String) request.getAttribute("cs");
      if (strCommunity == null) strCommunity = "";

      String strPort = (String) request.getAttribute("port");
      if (strPort == null) strPort = "161";

      String strRetries = (String) request.getAttribute("retries");
      if (strRetries == null) strRetries = "1";

      String strTimeout = (String) request.getAttribute("timeout");
      if (strTimeout == null) strTimeout = "3000";

      String strOID = (String) request.getAttribute("oid");
      if (strOID == null) strOID = "";

      String strDesc = (String) request.getAttribute("desc");
      if (strDesc == null) strDesc = "";

      String strASN1 = (String) request.getAttribute("asn1");
      if (strASN1 == null) strASN1 = "";

      String authpass = (String) request.getAttribute("authpass");
      if (authpass == null) authpass = "";

      String privpass = (String) request.getAttribute("privpass");
      if (privpass == null) privpass = "";

      String version = (String) request.getAttribute("version");
      if (version == null) version = "version 1";

      String securityname = (String) request.getAttribute("securityname");
      if (securityname == null) securityname = "";

      String seclevel = (String) request.getAttribute("seclevel");
      if (seclevel == null) seclevel = "AUTH_PRIV";

      String authproto = (String) request.getAttribute("authproto");
      authproto = authproto == null ? "MD5" : authproto;

      String privproto = (String) request.getAttribute("privproto");
      privproto = privproto == null ? "DES" : privproto;

      out.write("\n\n\n");
      out.write("<html>\n");
      out.write("<head>\n  ");
      out.write("<title>WebTelemetry - Tools - SNMP Walk");
      out.write("</title>\n  ");
      out.write(
          "<link rel=\"stylesheet\" type=\"text/css\" href=\"/wt-portal/css/default.css\" />\n  ");
      out.write("<script type=\"text/javascript\" src=\"/wt-portal/javascript/WTtools.js\">");
      out.write("</script>\n\n\n\t");
      out.write(
          "<script type=text/javascript>\n\t\n\t// Validate the SNMP form\n\tfunction validateForm()\n\t{\n\t    var seclevel = \"\";\n\t\tvar seclevelChecked = \"\";\n\t\tif (document.snmpwalk.ip.value == \"\" ) \n\t\t{\n\t\t    alert (\"Please fill in the ip address field.\");\n\t\t    return false;\n\t\t}\n\t\telse \n\t\t{\n\t\t\tif (!verifyIP(document.snmpwalk.ip.value))\n\t\t\t{\n\t\t\t\tdocument.snmpwalk.ip.focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\t\t\t\t\n\t\tif (document.snmpwalk.port.value != \"\" ) \n\t\t{\n\t\t\tif (!checkInteger(trim(document.snmpwalk.port.value))) {\n\t            alert (\"Please enter a whole number for 'Port' and try again.\");\n\t            document.snmpwalk.port.focus();\n\t            return false;\n\t        }\n\t    }\n\t    \n\t    if (document.snmpwalk.retries.value != \"\" ) \n\t\t{\n\t\t\tif (!checkInteger(trim(document.snmpwalk.retries.value))) {\n\t            alert (\"Please enter a whole number for 'Retries' and try again.\");\n\t            document.snmpwalk.retries.focus();\n\t            return false;\n\t        }\n\t    }\n\t    \n\t    if (document.snmpwalk.timeout.value != \"\" ) \n\t\t{\n");
      out.write(
          "\t\t\tif (!checkInteger(trim(document.snmpwalk.timeout.value))) {\n\t            alert (\"Please enter a whole number for 'Timeout' and try again.\");\n\t            document.snmpwalk.timeout.focus();\n\t            return false;\n\t        }\n\t    }\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\tvar sel = document.getElementById( \"version\");\t\t\t\n\t\tvar opt = sel.options[ sel.selectedIndex];\t\n\t\t\n\t\tif( opt.text != \"version 3\")\n\t\t{\n\t\t\t// Community String\n\t\t\tvar cs = document.snmpwalk.cs.value;\n\t\t\tif (cs == \"\" || cs == null || trim(cs).length ");
      out.write(
          "<= 0)\n\t\t\t{\n\t\t    \talert (\"Please fill in the community string field.\");\n\t\t    \tdocument.snmpwalk.cs.focus();\n\t\t    \treturn false;\n\t\t    }\n\t\t}\n\t\telse\n        {\n            // Security name\n            var secname = document.getElementById( \"securityname\");  \n            if( secname.value == null || trim(secname.value).length == 0)\n            {\n                alert( \"Please enter a security name\");\n                secname.focus();\n                return false;\n            }\n\n            //Find Security level, pass checks\n\t\t\tfor (var i = 0; i ");
      out.write(
          "< document.snmpwalk.seclevel.length; i++)  \n\t\t\t{ \n\t\t\t\tseclevel = document.snmpwalk.seclevel[i].value;\n\t\t\t\tsecChecked = document.snmpwalk.seclevel[i].checked;\n\t\t\n\t\t\t\tif (secChecked){\n\t\t\t\t\tseclevelChecked = seclevel;\n\t\t\t\t}\n\t\n\t\t\t\tif ( (seclevel == \"AUTH_PRIV\") && (secChecked) )\n\t\t\t\t{\n\t\t\t\t\tif( !checkAuthPassFld() || !checkPrivPassFld())\n\t              \t{            \t\n\t               \t\treturn false;\n\t           \t\t}\t\n\t\t\t\t}\n\t\t\t\telse\n\t        \t{\n\t\t \t\t\tif( (seclevel == \"AUTH_NOPRIV\") && (secChecked && !checkAuthPassFld()) )\n\t\t         \t{                \t\n\t\t        \t\treturn false;\n\t\t     \t\t}\n\t\t   \t\t}    \n\t\t\t}   \n        }\n\t    \n\t\t// The following is needed to support Mozilla & IE browsers with retrieving values from drop-down boxes (version, authproto, privproto).\n\t\tvar versionSel = document.snmpwalk.version;\n\t\tvar versionVal = versionSel.options[ versionSel.selectedIndex].text;\t\n\t\tvar authprotoSel = document.snmpwalk.authproto;\n\t\tvar authprotoVal = authprotoSel.options[ authprotoSel.selectedIndex].text;\t\n\t\tvar privprotoSel = document.snmpwalk.privproto;\n");
      out.write(
          "\t\tvar privprotoVal = privprotoSel.options[ privprotoSel.selectedIndex].text;\n\t\t\n\t\t// The followings are needed to avoid passing inappropriate SNMP version-dependent browser saved values to the servlet. \n\t\tvar authpassVal = document.snmpwalk.authpass.value; \n\t\tvar privpassVal = document.snmpwalk.privpass.value; \n\t\tvar communityStr = document.snmpwalk.cs.value;\n\t\t\n\t\tif (versionVal == \"version 3\")\n\t\t{\n\t\t\tcommunityStr = \"\";\n\t\t\tif (seclevelChecked == \"AUTH_NOPRIV\")\n\t\t\t{\n\t\t\t\tprivpassVal = \"\";\n\t\t\t\tprivprotoVal = \"\"; \n\t\t\t}\n\t\t\telse if (seclevelChecked == \"NOAUTH_NOPRIV\")\n\t\t\t{\n\t\t\t\tauthpassVal = \"\";\n\t\t\t\tauthprotoVal = \"\";\n\t\t\t\tprivpassVal = \"\";\n\t\t\t\tprivprotoVal = \"\"; \n\t\t\t}\n\t\t}\n\t\telse \n\t\t{\n\t\t\tauthpassVal = \"\";\n\t\t\tauthprotoVal = \"\";\n\t\t\tprivpassVal = \"\";\n\t\t\tprivprotoVal = \"\"; \n\t\t}\n\t\t\n\t    top.frames[1].document.snmpwalk.ip.value=document.snmpwalk.ip.value;\t    \t\t\n\t    top.frames[1].document.snmpwalk.oid.value=document.snmpwalk.oid.value;\t\n\t    top.frames[1].document.snmpwalk.port.value=document.snmpwalk.port.value;\n\t    top.frames[1].document.snmpwalk.retries.value=document.snmpwalk.retries.value;\n");
      out.write(
          "\t    top.frames[1].document.snmpwalk.timeout.value=document.snmpwalk.timeout.value;\n\t    top.frames[1].document.snmpwalk.cs.value=communityStr;\t\t\n\t    top.frames[1].document.snmpwalk.version.value=versionVal;  \t\t\t\n\t    top.frames[1].document.snmpwalk.securityname.value=document.snmpwalk.securityname.value; \n\t    top.frames[1].document.snmpwalk.seclevel.value=seclevelChecked; \t\t\n\t    top.frames[1].document.snmpwalk.authpass.value=authpassVal; \t\n\t    top.frames[1].document.snmpwalk.authproto.value=authprotoVal; \t\n\t    top.frames[1].document.snmpwalk.privpass.value=privpassVal; \t\n\t    top.frames[1].document.snmpwalk.privproto.value=privprotoVal;    \n\t    top.frames[1].document.snmpwalk.button.value='GetResults';\n\t    top.frames[1].document.snmpwalk.submit();\n\t    \n\t    return true;   \n\t}\n\n\t// Validate ASN.1 value\n\tfunction validateLookup()\n\t{\n\t    if (document.snmpwalk.desc.value == \"\" ) \n\t\t{\n\t\t    alert (\"Please fill in ASN.1 Description (example: hrStorageDescr).\");\n\t\t    return false;\n\t\t}\n\t\telse\n\t\t\treturn true;\n");
      out.write(
          "\t}\n\t\n\t// Show MIB pop-up window\n\tfunction viewMIB()\n\t{\n\t    if (document.snmpwalk.mibs.selectedIndex == -1 ) \n\t\t{\n\t\t    alert (\"Please select a MIB to view.\");\n\t\t}\n\t\tvar mib = document.snmpwalk.mibs.options[document.snmpwalk.mibs.selectedIndex];\n\t    var win = window.open('");
      out.print(WTTools.getMibURL(request));
      out.write(
          "' + mib.text, '', \n\t\t\t'status=yes,resizeable=yes,scrollbars=yes,menubar=yes,height=600,width=800');\t\n\t    return false;\n\t}\n\t\n\t// hide element\n    function hide( targetId)\n    {\n        if (document.getElementById)\n        {\n            target = document.getElementById(targetId);\n            target.style.visibility = \"hidden\";\n            target.style.display = \"none\";\n        }\n    }\n    // show element\n    function show( targetId)\n    {\n        if (document.getElementById)\n        {\n            target = document.getElementById(targetId);\n            target.style.visibility = \"visible\";\n            target.style.display = \"\";\n        }\n    }\n    \n    // Adjust frame\n    function adjustFrames(topFrameSize)\n    {\n    \tvar framesSize = topFrameSize + \",*\";\n    \tparent.document.getElementById(\"snmpframes\").rows = framesSize;   \n    }\n\n\t\n\t// Check for SNMPv3 selection\n\tfunction checkForSNMPv3()\n\t{\n\t\tvar sel = document.getElementById( \"version\");\n\t\tvar opt = sel.options[ sel.selectedIndex];\n\t\tif( opt.text == \"version 3\")\n");
      out.write(
          "\t\t{\t\t\t\n\t\t\thide (\"csOptions\");\n\t\t\tshow (\"snmpOptions\"); \n\t\t\tadjustFrames(420);\n\t\t\tcheckSecLevel();\t\t\t\n\t\t}\n\t\telse\n\t\t{\t\t\t\n\t\t\tshow (\"csOptions\");\n\t\t\thide (\"snmpOptions\"); \n\t\t\thide (\"authOptions\");   \n\t\t\thide (\"privOptions\");   \n\t\t\tadjustFrames(270);\n\t\t}\n\n\t\t// This is work around for IE browsers which do not support ");
      out.write(
          "<option disabled>\n\t\t// This text will not appear for any other browsers as this option can never be selected \n\t\tif(( opt.text == \"SNMPv3 disabled\") || ( opt.text == \"SNMPv3 expired\"))\n\t\t{\n\t\t\talert(\"You are currently not licensed to use this feature.  Please contact your sales representative for questions regarding this feature.\");\n\n\t\t\t// When the user selects SNMP v3 feature, select index is changed to version 1\n\t\t\tsel.selectedIndex = sel.options[sel.selectedIndex];\n\t\t}\n\t}\n\t\n\t// Check Auth Passphrase\n\tfunction checkAuthPassFld()\n    {\n        var authpass = document.getElementById( \"authpassfld\");\n        if( authpass.value == null || authpass.value.length ");
      out.write(
          "< 8)\n        {\n            alert( \"Authentication Passphrase must be 8 characters or more\");\n            authpass.focus();\n            return false;\n        }\n\n        return true;\n    }\n    \n    // Check Privacy Passphrase\n    function checkPrivPassFld()\n    {\n        var privpass = document.getElementById( \"privpassfld\");\n        if( privpass.value == null || privpass.value.length ");
      out.write(
          "< 8)\n        {\n            alert( \"Privacy Passphrase must be 8 characters or more\");\n            privpass.focus();\n            return false;\n        }\n\n        return true;\n    }\n    \n    function checkSecLevel()\n    { \n    \tvar secLevelChecked;   \t\n    \tfor (var i = 0; i ");
      out.write(
          "< document.snmpwalk.seclevel.length; i++)  \n\t\t{ \n\t\t\tvar seclevel = document.snmpwalk.seclevel[i].value;\n\t\t\tvar secChecked = document.snmpwalk.seclevel[i].checked;\n\t\t\tif ( secChecked )\n\t\t\t{\n\t\t\t\tsecLevelChecked = seclevel;\n\t\t\t}\n\t\t}\t\t\n\t\t\n\t\tif ( secLevelChecked == \"AUTH_PRIV\" )\n\t\t{\n\t\t\tif( checkAuthPassFld() || checkPrivPassFld())\n         \t{\n\t\t\t\tshowAuthPriv();\t\n\t\t\t}\n\t\t}\n\t\telse \n    \t{\t    \t\t\n\t  \t\tif ( (secLevelChecked == \"AUTH_NOPRIV\") && checkAuthPassFld() )\n\t    \t{\n\t     \t\tshowAuth();\n\t  \t\t}\n\t  \t\telse \n\t    \t{\n\t    \t\thideAuthPriv();\n\t    \t}\n   \t\t} \n    }\n    \n \n\tfunction showAuthPriv()\n\t{\n\t\tshow( \"authOptions\");\n\t\tshow( \"privOptions\");\n\t}\n\t    \n\t\n\tfunction showAuth()\n\t{\n\t\tshow( \"authOptions\");\n\t\thide( \"privOptions\");\n\t}\n\t    \n\t\n\tfunction hideAuthPriv()\n\t{\n\t\thide( \"authOptions\");\n\t \thide( \"privOptions\");\n\t}\n\t\n\tfunction checkForSpaces( evt)\n    {\n        evt = (evt) ? evt : ((window.event) ? event : null);\n        if( evt)\n        {\n            var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);\n");
      out.write(
          "            if( elem)\n            {\n                var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);\n                return( charCode != 32);\n            }\n        }\n    }\n\n\t");
      out.write("</script>\n");
      out.write("</head>\n\n\n");
      out.write("<body onload='checkForSNMPv3()'>\n");
      /* ----  c:import ---- */
      org.apache.taglibs.standard.tag.el.core.ImportTag _jspx_th_c_import_0 =
          (org.apache.taglibs.standard.tag.el.core.ImportTag)
              _jspx_tagPool_c_import_url_context.get(
                  org.apache.taglibs.standard.tag.el.core.ImportTag.class);
      _jspx_th_c_import_0.setPageContext(pageContext);
      _jspx_th_c_import_0.setParent(null);
      _jspx_th_c_import_0.setContext("/wt-monitor");
      _jspx_th_c_import_0.setUrl("/includes/header.jsp");
      int[] _jspx_push_body_count_c_import_0 = new int[] {0};
      try {
        int _jspx_eval_c_import_0 = _jspx_th_c_import_0.doStartTag();
        if (_jspx_eval_c_import_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
          if (_jspx_eval_c_import_0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
            javax.servlet.jsp.tagext.BodyContent _bc = pageContext.pushBody();
            _jspx_push_body_count_c_import_0[0]++;
            out = _bc;
            _jspx_th_c_import_0.setBodyContent(_bc);
            _jspx_th_c_import_0.doInitBody();
          }
          do {
            out.write("\n\t");
            if (_jspx_meth_c_param_0(
                _jspx_th_c_import_0, pageContext, _jspx_push_body_count_c_import_0)) return;
            out.write("\n\t");
            if (_jspx_meth_c_param_1(
                _jspx_th_c_import_0, pageContext, _jspx_push_body_count_c_import_0)) return;
            out.write("\n\t");
            if (_jspx_meth_c_param_2(
                _jspx_th_c_import_0, pageContext, _jspx_push_body_count_c_import_0)) return;
            out.write("\n\t");
            if (_jspx_meth_c_param_3(
                _jspx_th_c_import_0, pageContext, _jspx_push_body_count_c_import_0)) return;
            out.write("\n");
            int evalDoAfterBody = _jspx_th_c_import_0.doAfterBody();
            if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break;
          } while (true);
          if (_jspx_eval_c_import_0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE)
            out = pageContext.popBody();
          _jspx_push_body_count_c_import_0[0]--;
        }
        if (_jspx_th_c_import_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) return;
      } catch (Throwable _jspx_exception) {
        while (_jspx_push_body_count_c_import_0[0]-- > 0) out = pageContext.popBody();
        _jspx_th_c_import_0.doCatch(_jspx_exception);
      } finally {
        _jspx_th_c_import_0.doFinally();
        _jspx_tagPool_c_import_url_context.reuse(_jspx_th_c_import_0);
      }
      out.write("\n\n");
      out.write("<!-- BEGIN FRAMING TABLE:open tags, keep at 100%-->\n");
      out.write("<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n\t");
      out.write("<tr valign=\"top\">\n\t\t");
      out.write("<td valign=\"top\" width=\"10\">");
      out.write(
          "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"1\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
      out.write("</td>\n\t\t");
      out.write("<td>\n");
      out.write("<!-- END FRAMING TABLE:open tags, keep at 100%-->\n\n");
      out.write("<form action=\"");
      out.print(WTTools.getServletURL(request));
      out.write("WTsnmpWalkServlet\" method=\"get\" name=\"snmpwalk\" autocomplete=\"off\">\n\n");
      out.write(
          "<table width=\"100%\" valign=\"top\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n\n        ");
      out.write("<td width=\"32%\" valign=\"top\" bgcolor=\"#f0f0f0\">\n        ");
      out.write("<!-- BEGIN WALK SNMP TABLES -->\n            ");
      out.write(
          "<table width=\"100%\" valign=\"top\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n                ");
      out.write("<tr class=\"tableHeader\">\n                    ");
      out.write("<td class=\"tableHeader\" colspan=\"2\">Walk an SNMP Agent");
      out.write("</td>\n                ");
      out.write("</tr>\n                ");
      out.write("<tr class=\"tableRowLight\">\n                    ");
      out.write("<td class=\"tableText\" width=\"45%\">");
      out.write("<b>IP Address:");
      out.write("</b>");
      out.write("<A class=\"tt\" HREF=\"javascript: towerTip(");
      out.print(WTTips.TIP_SNMP_IPADDR);
      out.write(");\" TITLE=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n                    ");
      out.write("<td class=\"tableText\" >");
      out.write("<input type=\"text\" name=\"ip\" value=\"");
      out.print(strIp);
      out.write("\" size=\"23\">");
      out.write("</td>\n                ");
      out.write("</tr>                \n                ");
      out.write("<tr class=\"tableRowLight\">\n                    ");
      out.write("<td class=\"tableText\" width=\"45%\">");
      out.write("<b>Starting OID:");
      out.write("</b>");
      out.write("<A class=\"tt\" HREF=\"javascript: towerTip(");
      out.print(WTTips.TIP_SNMP_START_OID);
      out.write(");\" TITLE=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n                    ");
      out.write("<td class=\"tableText\" >");
      out.write("<input type=\"text\" size=\"23\" name=\"oid\" value=\"");
      out.print(strOID);
      out.write("\">");
      out.write("</td>\n                ");
      out.write("</tr>\n                ");
      out.write("<tr class=\"tableRowLight\">\n                    ");
      out.write("<td class=\"tableText\" width=\"45%\">");
      out.write("<b>Port:");
      out.write("</b>");
      out.write("<A class=\"tt\" HREF=\"javascript: towerTip(");
      out.print(WTTips.TIP_SNMP_PORT);
      out.write(");\" TITLE=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n                    ");
      out.write("<td class=\"tableText\" >");
      out.write("<input type=\"text\" size=\"23\" maxlength=10 name=\"port\" value=\"");
      out.print(strPort);
      out.write("\" >");
      out.write("</td>               \t\t\n                ");
      out.write("</tr>\n                ");
      out.write("<tr class=\"tableRowLight\">\n                    ");
      out.write("<td class=\"tableText\" width=\"45%\">");
      out.write("<b>Retries:");
      out.write("</b>");
      out.write("<A class=\"tt\" HREF=\"javascript: towerTip(");
      out.print(WTTips.TIP_RETRIES);
      out.write(");\" TITLE=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n                    ");
      out.write("<td class=\"tableText\" >");
      out.write("<input type=\"text\" size=\"4\" maxlength=10 name=\"retries\" value=\"");
      out.print(strRetries);
      out.write("\" >");
      out.write("</td>               \t\t\n                ");
      out.write("</tr>\n                ");
      out.write("<tr class=\"tableRowLight\">\n                    ");
      out.write("<td class=\"tableText\" width=\"45%\">");
      out.write("<b>Timeout(ms):");
      out.write("</b>");
      out.write("<A class=\"tt\" HREF=\"javascript: towerTip(");
      out.print(WTTips.TIP_TIMEOUT);
      out.write(");\" TITLE=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n                    ");
      out.write("<td class=\"tableText\" >");
      out.write("<input type=\"text\" size=\"23\" maxlength=10 name=\"timeout\" value=\"");
      out.print(strTimeout);
      out.write("\" >");
      out.write("</td>               \t\t\n                ");
      out.write("</tr>\n                ");
      out.write("<tr class=\"tableRowLight\">\n                    ");
      out.write("<td class=\"tableText\" width=\"45%\">");
      out.write("<b>SNMP Version:");
      out.write("</b>");
      out.write("<A class=\"tt\" HREF=\"javascript: towerTip(");
      out.print(WTTips.TIP_SNMP_VERSION);
      out.write(");\" TITLE=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n                    ");
      out.write("<td class=\"tableText\" >\n                    \t");
      out.write(
          "<select name=\"version\" id=\"version\" onclick=\"checkForSNMPv3()\">\n                \t\t\t");
      out.write("<option ");
      out.print(version.equals("version 1") ? "SELECTED" : "");
      out.write(">version 1\n                \t\t\t");
      out.write("<option ");
      out.print(version.equals("version 2c") ? "SELECTED" : "");
      out.write(">version 2c\n\t");

      com.websina.license.LicenseManager lim = com.websina.license.LicenseManager.getInstance();
      if (lim != null) { // Check if license is not null
        if (lim.isValid()) { //  Check if license is valid
          if (((Boolean.valueOf(
                  lim.getFeature(com.websina.license.License.WT_SECURE_SNMPV3_ENABLED_FIELD_NAME)))
              .booleanValue())) { //  Check if feature is enabled
            if ((lim.daysLeft(com.websina.license.License.WT_SECURE_SNMPV3_EXPIRATION_FIELD_NAME)
                    > 0)
                || (lim.daysLeft(com.websina.license.License.WT_SECURE_SNMPV3_EXPIRATION_FIELD_NAME)
                    == -1)) { // Check if feature has expired (-1 indicates never expired)

              out.write("\t\t\t\t\n                \t\t\t");
              out.write("<option ");
              out.print(version.equals("version 3") ? "SELECTED" : "");
              out.write(">version 3\n\t");
            } else {
              out.write("\n\t\t\t\t\t\t\t");
              out.write("<!-- The text for ");
              out.write(
                  "<option disabled> tag is changed as a workaround for IE browsers -->\n\t\t\t\t");
              out.write(
                  "<!-- Although other browsers will not allow to select this option -->\n\t\t\t\t");
              out.write(
                  "<!-- IE lets you select it and hence call checkForSNMPv3() which displays a message that the feature is not enabled and select version 1 -->\n\t\t\t\t");
              out.write("<!-- SNMPv3 enabled and expired -->\n\t\t\t\t");
              out.write("<option disabled=\"disabled\" style=\"color:#aaa\">SNMPv3 expired");
              out.write("</option>\n\t");
            }
          } else {
            out.write("\n\t\t\t\t\t\t\t");
            out.write("<!-- License is valid, SNMPv3 is disabled -->\n\t\t\t\t");
            out.write("<option disabled=\"disabled\" style=\"color:#aaa\">SNMPv3 disabled");
            out.write("</option>\n     ");
          }
        }
      }
      out.write("  \n            \t\t\t");
      out.write("</select>\n                    ");
      out.write("</td>\n             \t");
      out.write("</tr>\n            ");
      out.write("</table>\n            \n            ");
      out.write("<!-- COMMUNITY STRING OPTION -->\n                \n            ");
      out.write("<div id=\"csOptions\" style=\"visibility: visible\"> \n\t\t\t\t");
      out.write(
          "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n                \t");
      out.write("<tr class=\"tableRowLight\">\n               \t  \t\t");
      out.write("<td class=\"tableText\" width=\"45%\">");
      out.write("<b>Community String:");
      out.write("</b>");
      out.write("<A class=\"tt\" HREF=\"javascript: towerTip(");
      out.print(WTTips.TIP_SNMP_COMMSTR);
      out.write(");\" TITLE=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n                   \t\t");
      out.write("<td class=\"tableText\" >");
      out.write("<input type=\"password\" name=\"cs\" value=\"");
      out.print(strCommunity);
      out.write("\" size=\"23\">");
      out.write("</td>\n                \t");
      out.write("</tr>\n             \t");
      out.write("</table>\n             ");
      out.write("</div>\n                \n\t\t\t");
      out.write("<!-- SNMP v3 OPTIONS -->               \n                \n\t\t\t");
      out.write("<div id=\"snmpOptions\" style=\"display: none; visibility: hidden\"> \n\t\t\t\t");
      out.write(
          "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n\t\t\t\t\t\t\t\n                \t");
      out.write("<!-- SNMP Version 3 Config Label -->\n                \t");
      out.write("<BR/>");
      out.write("<HR width=\"95% align=\"center\">\n                \t");
      out.write("<tr class=\"tableRowLight\">\n                \t\t");
      out.write("<td class=\"tableText\" colspan=\"2\">");
      out.write("<b>SNMP Version 3 Options");
      out.write("</b>");
      out.write("</td>\n                \t");
      out.write("</tr>                              \n                \t\n                \t");
      out.write("<!-- Security Name -->\n                \t");
      out.write("<tr class=\"tableRowLight\">\n                    \t");
      out.write("<td class=\"tableText\" width=\"45%\">");
      out.write("<b>Security Name:");
      out.write("</b>");
      out.write("</td>\n                    \t");
      out.write("<td class=\"tableText\" >");
      out.write(
          "<INPUT type=\"text\" name=\"securityname\" id=\"securityname\" size=\"23\" maxlength=\"255\" value=\"");
      out.print(securityname);
      out.write("\" >");
      out.write("</td>\n                \t");
      out.write("</tr> \n                \t\n                \t");
      out.write("<!-- Security Level Options -->\n                \t");
      out.write("<tr class=\"tableRowLight\"> \n                    \t");
      out.write("<td class=\"tableText\">");
      out.write("<b>Security Level:");
      out.write("</b>");
      out.write("<A class=\"tt\" HREF=\"javascript: towerTip(");
      out.print(WTTips.TIP_SNMP_SECURITY_LEVEL);
      out.write(");\" TITLE=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n               \t\t");
      out.write("</tr>\n               \t\t\n               \t\t");
      out.write("<!-- Authentication with Privacy radio button-->\n               \t\t");
      out.write("<tr class=\"tableRowLight\">\n                    \t");
      out.write("<td class=\"tableText\" colspan=\"2\">\n                    \t\t");
      out.write(
          "<input type=\"radio\" onClick=\"showAuthPriv();adjustFrames(600)\" name=\"seclevel\" id=\"authpriv\" \n                    \t\tvalue=\"AUTH_PRIV\" ");
      out.print("AUTH_PRIV".equals(seclevel) ? "CHECKED" : "");
      out.write("> \n                    \t\tAuthentication with Privacy\n                   \t\t");
      out.write("</td>\n               \t\t");
      out.write("</tr>\n               \t\t\n               \t\t");
      out.write("<!-- Authentication without Privacy radio button-->\n               \t\t");
      out.write("<tr class=\"tableRowLight\"> \n                    \t");
      out.write("<td class=\"tableText\" colspan=\"2\">\n                    \t\t");
      out.write(
          "<input type=\"radio\" onClick=\"showAuth();adjustFrames(500)\" name=\"seclevel\" id=\"authnopriv\" \n                    \t\tvalue=\"AUTH_NOPRIV\" ");
      out.print("AUTH_NOPRIV".equals(seclevel) ? "CHECKED" : "");
      out.write(
          "> \n                    \t\tAuthentication without Privacy\n                   \t\t");
      out.write("</td>\n               \t\t");
      out.write("</tr> \n               \t\t\n               \t\t");
      out.write("<!-- No Authentication and No Privacy radio button-->\n               \t\t");
      out.write("<tr class=\"tableRowLight\"> \n                    \t");
      out.write("<td class=\"tableText\" colspan=\"2\">\n                    \t\t");
      out.write(
          "<input type=\"radio\" onClick=\"hideAuthPriv();adjustFrames(420)\" name=\"seclevel\" id=\"noauthnopriv\" \n                    \t\tvalue=\"NOAUTH_NOPRIV\" ");
      out.print("NOAUTH_NOPRIV".equals(seclevel) ? "CHECKED" : "");
      out.write(
          "> \n                    \t\tNo Authentication and no Privacy\n                   \t\t");
      out.write("</td>\n               \t\t");
      out.write("</tr> \n               \t\t\n              \t");
      out.write("</table>\n\t\t\t");
      out.write("</div>  \t\n  \n\t\t\t");
      out.write("<!-- Authentication Passphrase & Protocol-->\t\n\t\t\t");
      out.write("<div id=\"authOptions\" style=\"display:none; visibility:hidden\"> \n\t\t\t\t");
      out.write(
          "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n               \t\t");
      out.write("<br/>\n               \t\t");
      out.write("<!-- Authentication Passphrase -->\n               \t\t");
      out.write("<tr class=\"tableRowLight\">               \t\t\t \n                    \t\t");
      out.write("<td class=\"tableText\" colspan=\"2\">");
      out.write("<b>Authentication:");
      out.write("</b>");
      out.write("</td> \n               \t\t");
      out.write("</tr> \n               \t\t");
      out.write("<tr class=\"tableRowLight\"> \n               \t\t\t");
      out.write("<td class=\"tableText\" width=\"31%\">Passphrase");
      out.write("<a class=\"tt\" href=\"javascript:towerTip(");
      out.print(WTTips.TIP_SNMP_AUTH_PASS);
      out.write(");\" title=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n                    \t");
      out.write("<td class=\"tableText\" >");
      out.write(
          "<input type=\"password\" name=\"authpass\" id=\"authpassfld\" size=\"18\" maxlength=\"255\" value=\"");
      out.print(authpass);
      out.write("\" >&nbsp;(min. 8 char.)");
      out.write("</td>\n               \t\t");
      out.write("</tr>\n               \t\t               \t\t\n               \t\t");
      out.write("<!-- Authentication Protocol -->               \t\t\n               \t\t");
      out.write("<tr class=\"tableRowLight\"> \n               \t\t\t");
      out.write("<td class=\"tableText\" width=\"31%\">Protocol");
      out.write("<a class=\"tt\" href=\"javascript:towerTip(");
      out.print(WTTips.TIP_SNMP_AUTH_PROC);
      out.write(");\" title=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n                    \t");
      out.write("<td class=\"tableText\" >\n                    \t\t");
      out.write("<select name=\"authproto\" id=\"authprotofld\">\n                \t\t\t\t");
      out.write("<option ");
      out.print("MD5".equals(authproto) ? "SELECTED" : "");
      out.write(">MD5");
      out.write("</option>\n                \t\t\t\t");
      out.write("<option ");
      out.print("SHA".equals(authproto) ? "SELECTED" : "");
      out.write(">SHA");
      out.write("</option>\n            \t\t\t\t");
      out.write("</select>            \t\t\t \n            \t\t\t");
      out.write("</td>                      \t             \t\t\n               \t\t");
      out.write("</tr>\n           \t\t");
      out.write("</table>\n\t\t\t");
      out.write("</div>  \t\n             \t\t\n            ");
      out.write("<!-- Privacy Passphrase & Protocol-->   \t\t\n\t       \t");
      out.write("<div id=\"privOptions\" style=\"display:none; visibility:hidden\"> \n\t\t\t\t");
      out.write(
          "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n               \t\t");
      out.write("<br/>               \t\t              \t\t\n               \t\t");
      out.write("<!-- Privacy Passphrase -->\n               \t\t");
      out.write("<tr class=\"tableRowLight\">\n                    \t\t");
      out.write("<td class=\"tableText\" colspan=\"2\">");
      out.write("<b>Privacy:");
      out.write("</b>");
      out.write("</td>\n                    ");
      out.write("</tr>                \t\t\n               \t\t\n               \t\t");
      out.write("<tr class=\"tableRowLight\"> \n               \t\t\t");
      out.write("<td class=\"tableText\" width=\"31%\">Passphrase");
      out.write("<a class=\"tt\" href=\"javascript:towerTip(");
      out.print(WTTips.TIP_SNMP_PRIV_PASS);
      out.write(");\" title=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n                    \t");
      out.write("<td class=\"tableText\" >");
      out.write(
          "<input type=\"password\" name=\"privpass\" id=\"privpassfld\" size=\"18\" maxlength=\"255\" value=\"");
      out.print(privpass);
      out.write("\" >&nbsp;(min. 8 char.)");
      out.write("</td>\n               \t\t");
      out.write("</tr>\n               \t\t    \n               \t\t");
      out.write("<!-- Privacy Protocol -->              \t\t\n               \t\t");
      out.write("<tr class=\"tableRowLight\"> \n               \t\t\t");
      out.write("<td class=\"tableText\" width=\"31%\">Protocol");
      out.write("<a class=\"tt\" href=\"javascript:towerTip(");
      out.print(WTTips.TIP_SNMP_PRIV_PROC);
      out.write(");\" title=\"Telemetry Tip\">");
      out.write("<img src=\"/wt-portal/images/icons/tower_tips.gif\" border=\"0\">");
      out.write("</a>");
      out.write("</td>\n                    \t");
      out.write("<td class=\"tableText\" >                    \t\t\n                    \t\t");
      out.write("<select name=\"privproto\" id=\"privprotofld\">\n                \t\t\t\t");
      out.write("<option ");
      out.print("DES".equals(privproto) ? "SELECTED" : "");
      out.write(">DES");
      out.write("</option>\n                \t\t\t\t");
      out.write("<option ");
      out.print("AES 128".equals(privproto) ? "SELECTED" : "");
      out.write(">AES 128");
      out.write("</option>\n                \t\t\t\t");
      out.write("<option ");
      out.print("AES 192".equals(privproto) ? "SELECTED" : "");
      out.write(">AES 192");
      out.write("</option>\n                \t\t\t\t");
      out.write("<option ");
      out.print("AES 256".equals(privproto) ? "SELECTED" : "");
      out.write(">AES 256");
      out.write("</option>\n            \t\t\t\t");
      out.write("</select>\n            \t\t\t");
      out.write("</td>                      \t             \t\t\n               \t\t");
      out.write("</tr> \n       \t\t\t");
      out.write("</table>\n\t\t\t");
      out.write("</div>              \t\t\n                           \n     \t\t");
      out.write("<!-- End of SNMP v3 OPTIONS --> \n       \n        \t");
      out.write("<!-- SNMP Submit button -->\n\t\t\t");
      out.write("<tr class=\"tableRowLight\">\n\t\t\t\t");
      out.write("<td class=\"tableText\" colspan=\"2\">\n             \t\t");
      out.write("<INPUT type=\"hidden\" name=\"button\" value=\"\">\n\t\t\t\t\t");
      out.write(
          "<INPUT type=\"image\" src=\"/wt-portal/images/buttons/btn_walk.gif\" onClick=\"document.snmpwalk.button.value='Walk'; return validateForm();\">\n       \t\t\t");
      out.write("</td>\n       \t\t");
      out.write("</tr>\n\t");

      if (lim != null) { // Check if license is not null
        if (lim.isValid()) { //  Check if license is valid
          if (((Boolean.valueOf(
                  lim.getFeature(com.websina.license.License.WT_SECURE_SNMPV3_ENABLED_FIELD_NAME)))
              .booleanValue())) { //  Check if feature is enabled
            if ((lim.daysLeft(com.websina.license.License.WT_SECURE_SNMPV3_EXPIRATION_FIELD_NAME)
                    > 0)
                || (lim.daysLeft(com.websina.license.License.WT_SECURE_SNMPV3_EXPIRATION_FIELD_NAME)
                    == -1)) { // Check if feature has expired (-1 indicates never expired)

              out.write("\t\t\n       \t\t");
              out.write("<!-- License valid, SNMPv3 enabled and expired -->\t\t\t\n       \t\t");
              out.write("<tr class=\"tableRowLight\">\n       \t\t\t");
              out.write("<td colspan=\"2\">");
              out.write(
                  "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"10\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
              out.write("</td>\n       \t\t");
              out.write("</tr>\n   ");
            } else {
              out.write("\n       \t\t");
              out.write("<!-- SNMPv3 enabled and expired -->\n       \t\t");
              out.write("<tr class=\"tableRowLight\">\n       \t\t\t");
              out.write("<td colspan=\"2\" class=\"tableText\">");
              out.write("<span class=\"error\">Access to SNMP v3 has expired.");
              out.write("</span>");
              out.write("<br>&nbsp;\n       \t\t\t");
              out.write("</td>\n\t\t\t");
              out.write("</tr>\n   ");
            }
          } else {
            out.write("\n       \t\t");
            out.write("<!-- License is valid, SNMPv3 is disabled -->\n       \t\t");
            out.write("<tr class=\"tableRowLight\">\n       \t\t\t");
            out.write("<td colspan=\"2\">");
            out.write(
                "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"10\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
            out.write("</td>\n       \t\t");
            out.write("</tr>\n     ");
          }
        }
      }
      out.write("    \n\n\t\t\t");
      out.write("</table>\n        ");
      out.write("<!-- END WALK SNMP TABLES -->\n        ");
      out.write("</td>               \n  \n        ");
      out.write("<td valign=\"top\">");
      out.write(
          "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"10\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
      out.write("</td>\n        ");
      out.write("<td valign=\"top\" bgcolor=\"#f0f0f0\">\n        ");
      out.write("<!-- BEGIN MIB TABLE -->\n            ");
      out.write(
          "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n                ");
      out.write("<tr class=\"tableHeader\">\n                    ");
      out.write("<td class=\"tableHeader\">View MIBs");
      out.write("</td>\n                ");
      out.write("</tr>\n                ");
      out.write("<tr class=\"tableRowLight\">\n                    ");
      out.write("<td class=\"tableText\">\n                    \t");
      out.write("<select name=mibs size=7>\n\t\t\t\t\t\t    ");

      if (vMibs != null) {
        for (int j = 0; j < vMibs.size(); j++) {

          out.print("<OPTION>" + (String) vMibs.get(j));
        }
      }

      out.write("\n\t\t\t\t\t    ");
      out.write("</select>\n                    ");
      out.write("</td>\n                ");
      out.write("</tr>\n                ");
      out.write("<tr class=\"tableRowLight\">\n                    ");
      out.write("<td class=\"tableText\">\n\t\t\t\t\t");
      out.write(
          "<INPUT type=\"image\" src=\"/wt-portal/images/buttons/btn_view_MIB.gif\" onClick=\"document.snmpwalk.button.value='View MIB'; return viewMIB();\">&nbsp;&nbsp;");
      out.write(
          "<INPUT type=\"image\" src=\"/wt-portal/images/buttons/btn_reload_MIB.gif\" onClick=\"document.snmpwalk.button.value='Reload MIBs';\">");
      out.write("</td>\n                ");
      out.write("</tr>\n            ");
      out.write("</table>\n        ");
      out.write("<!-- END MIB TABLE -->\n        ");
      out.write("</td>\n        \n        ");
      out.write("<td valign=\"top\">");
      out.write(
          "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"10\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
      out.write("</td>\n\t\t");
      out.write("<td valign=\"top\" bgcolor=\"#f0f0f0\">\n        ");
      out.write("<!-- BEGIN ASN TABLE -->\n            ");
      out.write(
          "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n                ");
      out.write("<tr class=\"tableHeader\">\n                    ");
      out.write("<td class=\"tableHeader\">Lookup ASN.1 Values By Name");
      out.write("</td>\n                ");
      out.write("</tr>\n                ");
      out.write("<tr class=\"tableRowLight\">\n                    ");
      out.write("<td class=\"tableText\">");
      out.write("<INPUT type=\"text\" name=\"desc\" value=\"");
      out.print(strDesc);
      out.write("\" size=\"30\" >");
      out.write("</td>\n                ");
      out.write("</tr>\n                ");
      out.write("<tr class=\"tableRowLight\">\n                    ");
      out.write("<td class=\"tableText\">");
      out.write("<textarea cols=\"30\" rows=\"5\">");
      out.print(strASN1);
      out.write("</textarea>");
      out.write("</td>\n                ");
      out.write("</tr>\n                ");
      out.write("<tr class=\"tableRowLight\">\n                    ");
      out.write("<td class=\"tableText\">\n\t                    ");
      out.write(
          "<INPUT type=\"image\" src=\"/wt-portal/images/buttons/btn_lookup.gif\" onClick=\"document.snmpwalk.button.value='lookup'; return validateLookup();\">\n                    ");
      out.write("</td>\n                ");
      out.write("</tr>\n            ");
      out.write("</table>");
      out.write("<BR>\n        ");
      out.write("<!-- END ASN TABLE -->\n        ");
      out.write("</td>        \n    \t");
      out.write("<td valign=\"top\">");
      out.write(
          "<img src=\"/wt-portal/images/spacers/spacer.gif\" height=\"10\" width=\"10\" border=\"0\" alt=\"WebTelemetry\">");
      out.write("</td>        \n    ");
      out.write("</tr>\n");
      out.write("</table>\n");
      out.write("</form>\n");
      out.write("<!-- BEGIN FRAMING TABLE:close tags-->\n\t\t");
      out.write("</td>\n\t");
      out.write("</tr>\n");
      out.write("</table>\n");
      out.write("<!-- END FRAMING TABLE:close tags-->   \n  ");
      out.write("</body>\n");
      out.write("</html>\n");
    } catch (Throwable t) {
      out = _jspx_out;
      if (out != null && out.getBufferSize() != 0) out.clearBuffer();
      if (pageContext != null) pageContext.handlePageException(t);
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
    }
  }