public String buildInterfaceTable(String rule, String[] serviceList) throws FilterParseException {
    StringBuffer buffer = new StringBuffer();
    Filter filter = new Filter();
    Map interfaces = filter.getIPServiceMap(rule);

    Iterator i = interfaces.keySet().iterator();
    while (i.hasNext()) {
      String key = (String) i.next();
      buffer.append("<tr><td valign=\"top\">").append(key).append("</td>");
      buffer.append("<td>");

      if (serviceList != null && serviceList.length != 0) {
        Map services = (Map) interfaces.get(key);
        Iterator j = services.keySet().iterator();
        while (j.hasNext()) {
          String svc = (String) j.next();
          for (int idx = 0; idx < serviceList.length; idx++) {
            if (svc.equals(serviceList[idx])) {
              buffer.append(svc).append("<br>");
            }
          }
        }
      } else {
        buffer.append("All services");
      }
      buffer.append("</td>");

      buffer.append("</tr>");
    }

    return buffer.toString();
  }
예제 #2
0
 /** Converts a space delimitered string to a list of strings */
 private static String[] getStringList(String str) {
   if (str == null) return null;
   ArrayList list = new ArrayList();
   int i = 0;
   int length = str.length();
   StringBuffer sb = null;
   while (i < length) {
     char ch = str.charAt(i);
     if (ch == ' ') {
       // A space was hit. Add string to list
       if (sb != null) {
         list.add(sb.toString());
         sb = null;
       }
     } else if (ch == '\\') {
       // It is a delimiter. Add next character
       if (i + 1 < length) {
         ch = str.charAt(++i);
         if (sb == null) sb = new StringBuffer();
         sb.append(ch);
       }
     } else {
       if (sb == null) sb = new StringBuffer();
       sb.append(ch);
     }
     i++; // Next character
   }
   // Make sure to add the last part to the list too
   if (sb != null) {
     list.add(sb.toString());
   }
   if (list.size() == 0) return null;
   String[] results = new String[list.size()];
   return (String[]) list.toArray(results);
 }
예제 #3
0
  /*
  	Show context number lines of string before and after target line.
  	Add HTML formatting to bold the target line.
  */
  String showScriptContextHTML(String s, int lineNo, int context) {
    StringBuffer sb = new StringBuffer();
    BufferedReader br = new BufferedReader(new StringReader(s));

    int beginLine = Math.max(1, lineNo - context);
    int endLine = lineNo + context;
    for (int i = 1; i <= lineNo + context + 1; i++) {
      if (i < beginLine) {
        try {
          br.readLine();
        } catch (IOException e) {
          throw new RuntimeException(e.toString());
        }
        continue;
      }
      if (i > endLine) break;

      String line;
      try {
        line = br.readLine();
      } catch (IOException e) {
        throw new RuntimeException(e.toString());
      }

      if (line == null) break;
      if (i == lineNo) sb.append("<font color=\"red\">" + i + ": " + line + "</font><br/>");
      else sb.append(i + ": " + line + "<br/>");
    }

    return sb.toString();
  }
예제 #4
0
 // 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
   StringBuffer 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 (debug.messageEnabled()) {
         debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie name = " + cookieName);
         debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie val= " + cookieVal);
       }
       if (cookieStr == null) {
         cookieStr = new StringBuffer();
       } else {
         cookieStr.append(";");
       }
       cookieStr.append(cookieName).append(EQUAL_TO).append(cookieVal);
     }
   }
   if (cookieStr != null) {
     strCookies = cookieStr.toString();
   }
   return strCookies;
 }
예제 #5
0
  /** Return a String representation of this object. */
  public String toString() {

    if (filterConfig == null) return ("KeepSession()");
    StringBuffer sb = new StringBuffer("KeepSession(");
    sb.append(filterConfig);
    sb.append(")");
    return (sb.toString());
  }
예제 #6
0
  public String getClassPath() {
    StringBuffer cpath = new StringBuffer();
    String sep = System.getProperty("path.separator");

    for (int i = 0; i < jars.size(); i++) {
      cpath.append((String) jars.elementAt(i) + sep);
    }

    return cpath.toString();
  }
  private String getLink(
      final String event,
      final String label,
      final String css,
      String defaultValue,
      String selectedValue,
      String tooltip) {
    String status = Utilities.escapeHTML(Utilities.filterOutHTMLTags(tooltip));

    StringBuffer link = new StringBuffer();
    defaultValue = defaultValue == null ? AbstractChip.FALSE : defaultValue;
    selectedValue = selectedValue == null ? AbstractChip.TRUE : selectedValue;
    link.append("<input type=\"hidden\" name=\"" + event + "\" value=\"" + defaultValue + "\" />");
    link.append(
        "<a href=\"#\" onMouseover=\"window.status='"
            + status
            + "'; return true;\" onMouseout=\"window.status=''; return true;\" ");
    if (css != null) {
      link.append("class=\"" + css + "\" ");
    }
    link.append("hidefocus=\"true\" ");
    link.append(
        "onclick=\"document.editorForm.elements['"
            + event
            + "'].value='"
            + selectedValue
            + "';setScrollAndSubmit();return false;\">");
    link.append(label);
    link.append("</a>");
    return link.toString();
  }
예제 #8
0
파일: kbSRU.java 프로젝트: STITCHplus/kbSRU
 public StringBuffer construct_lucene_solr(StringBuffer result, SolrDocument d) {
   for (String field : (d.getFieldNames())) {
     if ((!field.endsWith("_str")) && (!field.equalsIgnoreCase("fullrecord"))) {
       Iterator j = d.getFieldValues(field).iterator();
       while (j.hasNext()) {
         result.append("<" + field + ">");
         result.append(helpers.xmlEncode((String) j.next().toString()));
         field = field.split(" ")[0];
         result.append("</" + field + ">");
       }
     }
   }
   return (result);
 }
예제 #9
0
  /** Convert special characters to entities for XML output */
  public static String escape(String value) {
    String search = "&<>";
    String[] replace = {"&amp;", "&lt;", "&gt;"};

    StringBuffer buf = new StringBuffer();

    for (int i = 0; i < value.length(); i++) {
      char c = value.charAt(i);
      int pos = search.indexOf(c);
      if (pos < 0) buf.append(c);
      else buf.append(replace[pos]);
    }

    return buf.toString();
  }
 private String getShortcutScript(HashMap<String, String> usedButtonShortCuts) {
   StringBuffer shortcuts = new StringBuffer();
   shortcuts.append(" function buttonListShorcuts() {\n");
   Iterator<String> ik = usedButtonShortCuts.keySet().iterator();
   Iterator<String> iv = usedButtonShortCuts.values().iterator();
   while (ik.hasNext() && iv.hasNext()) {
     shortcuts
         .append("  keyArray[keyArray.length] = new keyArrayItem(\"")
         .append(ik.next())
         .append("\", \"")
         .append(iv.next())
         .append("\", null, \"altKey\", false, \"onkeydown\");\n");
   }
   shortcuts.append(" return true;\n}");
   return shortcuts.toString();
 }
예제 #11
0
  String formatScriptResultHTML(
      String script, Object result, Exception error, StringBuffer scriptOutput) throws IOException {
    SimpleTemplate tmplt;

    if (error != null) {
      tmplt = new SimpleTemplate(getClass().getResource("error.template"));

      String errString;

      if (error instanceof bsh.EvalError) {
        int lineNo = ((EvalError) error).getErrorLineNumber();
        String msg = error.getMessage();
        int contextLines = 4;
        errString = escape(msg);
        if (lineNo > -1) errString += "<hr>" + showScriptContextHTML(script, lineNo, contextLines);
      } else errString = escape(error.toString());

      tmplt.replace("error", errString);
    } else {
      tmplt = new SimpleTemplate(getClass().getResource("result.template"));
      tmplt.replace("value", escape(String.valueOf(result)));
      tmplt.replace("output", escape(scriptOutput.toString()));
    }

    return tmplt.toString();
  }
예제 #12
0
 /**
  * Gathers the parameters in the request as a HTTP URL string. to form <code>requestParams</code>
  * String. 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 It also putsthe advice params in a separate
  * <code>policyAdviceList</code> String.
  *
  * @param request an HttpServletRequest object that contains the request the client has made of
  *     the servlet.
  */
 private void parseRequestParams(HttpServletRequest request) {
   StringBuffer adviceList = null;
   StringBuffer parameterString = new StringBuffer(100);
   for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
     String paramName = (String) e.nextElement();
     if (adviceParams.contains(paramName.toLowerCase())) {
       if (adviceList == null) {
         adviceList = new StringBuffer();
       } 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());
   }
   if (adviceList == null) {
     policyAdviceList = null;
   } else {
     policyAdviceList = adviceList.toString();
   }
   if (parameterString.length() > 0) {
     requestParams = (parameterString.deleteCharAt(0).toString());
   } else {
     requestParams = parameterString.toString();
   }
 }
 public static String filter(String input) {
   if (!hasSpecialChars(input)) {
     return (input);
   }
   StringBuffer filtered = new StringBuffer(input.length());
   char c;
   for (int i = 0; i < input.length(); i++) {
     c = input.charAt(i);
     switch (c) {
       case '<':
         filtered.append("&lt;");
         break;
       case '>':
         filtered.append("&gt;");
         break;
       case '"':
         filtered.append("&quot;");
         break;
       case '&':
         filtered.append("&amp;");
         break;
       default:
         filtered.append(c);
     }
   }
   return (filtered.toString());
 }
예제 #14
0
  /** This method sets the Data Source the component should be bound to. */
  public void setDataSource(String dataSource) {
    _dataSource = dataSource;
    if (_dataSource == null) return;

    // search and replace &QUOT; with a single quote. For Engines that have trouble with single
    // quotes inside a tag
    String test = _dataSource.toUpperCase();
    int pos = test.indexOf("&QUOT;");
    if (pos == -1) return;

    StringBuffer work = new StringBuffer(_dataSource);
    while (pos > -1) {
      work.replace(pos, pos + 6, "'");
      test = work.toString().toUpperCase();
      pos = test.indexOf("&QUOT;");
    }
    _dataSource = work.toString();
  }
예제 #15
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    PrintWriter out = response.getWriter();
    String location = URLDecoder.decode(request.getParameter("location"));
    String type = URLDecoder.decode(request.getParameter("type"));
    String unit = URLDecoder.decode(request.getParameter("unit"));
    String awsURL =
        "http://default-environment-ii9naedwp8.elasticbeanstalk.com/?location="
            + URLEncoder.encode(location)
            + "&type="
            + type
            + "&unit="
            + unit;
    // out.write(awsURL);
    String myurl = URLEncoder.encode(awsURL);
    // out.write("\n"+myurl);
    URL url = new URL(awsURL);
    URLConnection urlConnection = url.openConnection();

    InputStream awsResponse = urlConnection.getInputStream();
    InputStreamReader iSReader = new InputStreamReader(awsResponse);
    StringBuffer sb = new StringBuffer();
    String xmlLine;
    BufferedReader buf = new BufferedReader(iSReader);
    try {
      while ((xmlLine = buf.readLine()) != null) {
        sb.append(xmlLine);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    xmlLine = sb.toString();

    response.setContentType("application/json; charset=UTF-8");
    int indent = 6;
    try {
      JSONObject jsonObj = XML.toJSONObject(xmlLine);
      String json1 = jsonObj.toString(indent);
      out.write(json1);
    } catch (JSONException ex) {
      ex.printStackTrace();
    }
  }
예제 #16
0
    public Element reportDtElem() {
      StringBuffer sb = new StringBuffer(255);
      sb.append(shortTypeName);
      sb.append(" [ dataSourceName: ");
      sb.append(pds.getDataSourceName());
      sb.append("; identityToken: ");
      sb.append(pds.getIdentityToken());
      sb.append(" ]");

      Element dtElem = doc.createElement("dt");
      dtElem.appendChild(doc.createTextNode(sb.toString()));
      return dtElem;
    }
예제 #17
0
 private String cryptPassword(String pass) {
   byte[] uniqueKey = pass.getBytes();
   byte[] hash = null;
   try {
     hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
   } catch (Exception e) { // Il ne doit jamais avoir d'erreurs ici
     e.printStackTrace();
   }
   StringBuffer hashString = new StringBuffer();
   for (int i = 0; i < hash.length; ++i) {
     String hex = Integer.toHexString(hash[i]);
     if (hex.length() == 1) {
       hashString.append('0');
       hashString.append(hex.charAt(hex.length() - 1));
     } else {
       hashString.append(hex.substring(hex.length() - 2));
     }
   }
   return hashString.toString();
 }
예제 #18
0
  private String getMessageTable(StringBuffer msg) {
    StringBuffer sb = new StringBuffer();

    if (msg.length() > 0) {
      // sb.append("<a href=\"javascript:clearmsgs()\">Clear Messages</a>");
      sb.append("<table class=\"msgbox\">");
      // sb.append("<tr><th>");
      // sb.append("<input type=\"submit\" value=\"Clear Messages\"
      // onclick=\"clearmsgs()\"></input>");
      // sb.append("</th></tr>");
      sb.append("<tr><td>");
      sb.append(msg.toString());
      sb.append("</td></tr>");
      sb.append("</table>");
    }
    return sb.toString();
  }
  protected void respondAdmin(HttpServletRequest req, HttpServletResponse res) throws IOException {
    res.setContentType("text/xml");
    StringBuffer buf = new StringBuffer();

    String _details = req.getParameter("details");
    boolean details = (_details != null && _details.equals("1"));

    ConnectionGroup.dumpGroupsXML(buf, details);

    String appName = req.getParameter("application");
    if (appName != null && !appName.equals("")) {
      if (appName.equals("*")) {
        Application.dumpApplicationsXML(buf, details);
      } else {
        Application application = Application.getApplication(appName, false);
        if (application != null) application.toString();
      }
    }

    ConnectionAgent.dumpAgentsXML(buf, details);

    ServletOutputStream out = res.getOutputStream();
    try {
      out.println(
          "<connection-info "
              + " max-message-length=\""
              + HTTPConnection.getMaxMessageLen()
              + "\""
              + " connection-length=\""
              + HTTPConnection.getConnectionLength()
              + "\""
              + " reconnection-wait-interval=\""
              + HTTPConnection.getReconnectionWaitInterval()
              + "\""
              + " >");
      out.println(buf.toString());
      out.println("</connection-info>");
    } finally {
      FileUtils.close(out);
    }
  }
예제 #20
0
  // createPageString -
  // Create list of pages for search results
  private String createPageString(
      int numberOfItems, int itemsPerPage, int currentPage, String baseUrl) {
    StringBuffer pageString = new StringBuffer();

    // Calculate the total number of pages
    int totalPages = 1;
    if (numberOfItems > itemsPerPage) {
      double pages = Math.ceil(numberOfItems / (double) itemsPerPage);
      totalPages = (int) Math.ceil(pages);
    }

    //
    if (totalPages > 1) {
      for (int i = 1; i <= totalPages; i++) {
        if (i == currentPage) {
          pageString.append(i);
        } else {
          pageString.append("<a href=\"" + baseUrl + i + "\" title=\"" + i + "\">" + i + "</a>");
        }

        if (i != totalPages) pageString.append(" ");
      }
    } else {
      pageString.append("1");
    }

    return pageString.toString();
  }
예제 #21
0
  private void addProject(
      HttpServletRequest request, HttpServletResponse response, boolean updateFlag)
      throws ServletException, IOException {
    // First order of business is to capture the form parameters into the project bean
    setProjectBean(request);
    // execute the insert
    String id = request.getParameter("id");
    try {
      if (updateFlag) parameterDAO.deleteProject(id);
      project = pb.insert();
    } catch (Exception e) {
      msg.append("A B O R T.  The following database error has occured:<br />");
      msg.append(
          "<strong><span style=\"background-color: #FFFF00\">" + e + "</span></strong><br />");
    } finally {
      if (project > 0) {
        // success
        msg.append(
            "Project <strong><span style=\"background-color: #FFFF00\">" + pb.getProjectname());
        if (updateFlag) {
          msg.append("</span></strong> was U P D A T E D <br />");
        } else {
          msg.append("</span></strong> was I N S E R T E D<br />");
        }

      } else {
        msg.append(
            "F A I L E D to Insert/Update Project "
                + pb.getProjectname()
                + " into database!!!!!!!!!!!<br />");
      }
    }
  }
예제 #22
0
 private static String parseDate(String input) {
   if (input == null || "".equals(input)) {
     return input;
   }
   if (input.length() < 19) {
     return input;
   }
   String d = input.substring(0, 19);
   // try to parse it
   try {
     StringBuffer buf = new StringBuffer(input.length());
     synchronized (formatter) {
       Date date = formatter.parse(d);
       buf.append("<span class=\"date\" title=\"").append(formatter.format(date)).append("\">");
     }
     buf.append(d).append("</span>");
     buf.append(input.substring(19, input.length()));
     return buf.toString();
   } catch (ParseException pe) {
     return input;
   }
 }
 private String getExternalLink(final String url, final String label, final String css) {
   StringBuffer link = new StringBuffer();
   link.append("<a href=\"" + url + "\" ");
   if (css != null) {
     link.append("class=\"" + css + "\" ");
   }
   link.append(">");
   link.append(label);
   link.append("</a>");
   return link.toString();
 }
예제 #24
0
 void sendRaw(
     HttpServletRequest request,
     HttpServletResponse response,
     Exception scriptError,
     Object scriptResult,
     StringBuffer scriptOutput)
     throws IOException {
   response.setContentType("text/plain");
   PrintWriter out = response.getWriter();
   if (scriptError != null) out.println("Script Error:\n" + scriptError);
   else out.println(scriptOutput.toString());
   out.flush();
 }
  public String buildServiceOptions(String rule) throws SQLException {
    List services = NotificationFactory.getInstance().getServiceNames();
    Collections.sort(
        services,
        new Comparator() {
          public int compare(Object o1, Object o2) {
            return ((String) o1).compareToIgnoreCase((String) o2);
          }
        });
    StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < services.size(); i++) {
      if (rule != null && rule.indexOf((String) services.get(i)) > 0) {
        buffer.append(
            "<option selected VALUE='" + services.get(i) + "'>" + services.get(i) + "</option>");
      } else {
        buffer.append("<option VALUE='" + services.get(i) + "'>" + services.get(i) + "</option>");
      }
    }

    return buffer.toString();
  }
  public String buildServiceList(String rule) throws SQLException {
    if (rule == null) {
      return "";
    }

    List services = NotificationFactory.getInstance().getServiceNames();
    Collections.sort(
        services,
        new Comparator() {
          public int compare(Object o1, Object o2) {
            return ((String) o1).compareToIgnoreCase((String) o2);
          }
        });
    StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < services.size(); i++) {
      if (rule.indexOf((String) services.get(i)) > 0) {
        buffer.append(services.get(i)).append("</br>");
      }
    }

    return buffer.toString();
  }
  /**
   * Build a commonly used event list where each event's uei is separated by a </br> tag.
   *
   * @param notice the notification that contains the ueis
   * @return a String representation for the UI
   */
  public String buildEventList(Notification notice) {
    if (notice == null) {
      return "";
    }

    StringBuffer buffer = new StringBuffer();
    for (Iterator iter = notice.getEventInfoCollection().iterator(); iter.hasNext(); ) {
      // create temp event object and use get()
      // NOTE: cannot do this until we also fill in the snmp data
      /*org.opennms.netmgt.xml.event.Event e = EventConfigurationManager.makeEvent(
      		(org.opennms.netmgt.config.notifications.EventInfo)iter.next());
      List events = EventConfigurationManager.get(e);
      */
      List events =
          EventConfigurationManager.getByEventInfo(
              (org.opennms.netmgt.config.notifications.EventInfo) iter.next());
      for (Iterator iter2 = events.iterator(); iter2.hasNext(); ) {
        buffer.append(((Event) iter2.next()).getEventLabel()).append("</br>");
      }
    }

    return buffer.toString();
  }
  public String buildPathSelect(String currentPath) throws ServletException {
    StringBuffer buffer = new StringBuffer("<select NAME=\"path\">");

    Map pathsMap = null;

    try {
      pathsMap = new TreeMap(DestinationPathFactory.getInstance().getPaths());
      Iterator iterator = pathsMap.keySet().iterator();
      while (iterator.hasNext()) {
        String key = (String) iterator.next();
        if (key.equals(currentPath)) {
          buffer.append("<option SELECTED VALUE=" + key + ">" + key + "</option>");
        } else {
          buffer.append("<option VALUE=" + key + ">" + key + "</option>");
        }
      }
    } catch (Exception e) {
      throw new ServletException("couldn't get destination path list.", e);
    }
    buffer.append("</select>");

    return buffer.toString();
  }
  public String buildEventSelect(Notification notice) throws IOException, FileNotFoundException {
    // The list of events needs to be transposed to (label, uei) in
    // order to sort it by label for display.
    List eventVendors =
        EventConfigurationManager.getEventsByVendor(NotificationWizardServlet.WT_VENDOR_NAME);
    StringBuffer buffer = new StringBuffer();
    SortedMap sortedEvents = (SortedMap) new TreeMap();

    List excludeList = NotificationWizardServlet.getExcludeList();

    for (Iterator iter = eventVendors.iterator(); iter.hasNext(); ) {
      com.jjlabs.model.EventVendor e = (com.jjlabs.model.EventVendor) iter.next();
      sortedEvents.put(e.getLabel(), e);
    }

    Iterator j = sortedEvents.keySet().iterator();

    while (j.hasNext()) {
      String label = (String) j.next();
      com.jjlabs.model.EventVendor e = (com.jjlabs.model.EventVendor) sortedEvents.get(label);
      String uei = e.getUei();
      String trimmedUei = NotificationWizardServlet.stripUei(uei);

      if (!excludeList.contains(trimmedUei)) {
        boolean foundUei = NotificationWizardServlet.isEventInNotification(notice, e);
        int id = e.getId();

        if (foundUei) {
          buffer.append("<option selected VALUE=\"" + id + "\">" + label + "</option>");
        } else {
          buffer.append("<option value=\"" + id + "\">" + label + "</option>");
        }
      }
    }

    return buffer.toString();
  }
 private InputStream getReport(
     HttpServletRequest request,
     HttpServletResponse response,
     Tab tab,
     TableModel tableModel,
     Integer columnCountLimit)
     throws ServletException, IOException {
   StringBuffer suri = new StringBuffer();
   suri.append("/xava/jasperReport");
   suri.append("?language=");
   suri.append(Locales.getCurrent().getLanguage());
   suri.append("&widths=");
   suri.append(Arrays.toString(getWidths(tableModel)));
   if (columnCountLimit != null) {
     suri.append("&columnCountLimit=");
     suri.append(columnCountLimit);
   }
   response.setCharacterEncoding(XSystem.getEncoding());
   return Servlets.getURIAsStream(request, response, suri.toString());
 }