Example #1
0
 public boolean isPalindrome(String s) {
   if (s.length() == 0) return true;
   // System.out.println(cs);
   int i = 0, j = s.length() - 1;
   boolean flag = true;
   while (i < j) {
     // System.out.println(s.charAt(i)+" vs " + s.charAt(j)  );
     if (Character.isLetterOrDigit(s.charAt(i)) == false) {
       // System.out.println("i is not alphanumeric " + s.charAt(i)  );
       i++;
       continue;
     }
     if (Character.isLetterOrDigit(s.charAt(j)) == false) {
       // System.out.println("j is not alphanumeric:" + s.charAt(j)  );
       j--;
       continue;
     }
     if (s.charAt(i) == s.charAt(j) || Math.abs(s.charAt(i) - s.charAt(j)) == 32) {
       if ((Character.isDigit(s.charAt(i)) && Character.isLetter(s.charAt(j)))
           || (Character.isDigit(s.charAt(j)) && Character.isLetter(s.charAt(i)))) {
         flag = false;
         break;
       }
       flag = true;
       i++;
       j--;
     } else {
       flag = false;
       // System.out.println(s.charAt(i)+" vs " + s.charAt(j)  );
       break;
     }
   }
   System.out.println(flag);
   return flag;
 }
Example #2
0
 /**
  * ** Returns true if the specified character is a valid character to use in ** an ID ** @param ch
  * The character ** @return True if the specified character is a valid character to use in ** an
  * ID
  */
 public static boolean isValidIDChar(char ch) {
   // At a minimum, avoid the following special chars:
   //   $   - substitution character
   //   {}  - have had problems using this character in MySQL
   //   %   - MySQL wildcard character
   //   *   - generic wildcard character
   //   \   - escape character
   //   ?   - just don't use it
   //   ,   - will get confused as a field separator
   //   |   - will get confused as a field separator
   //   /   - will get confused as a field separator
   //   =   - will get confused as a key=value separator
   //   "'` - quotation characters
   //   #   - possible beginning of comment
   //   ~   - just don't use it
   //   ?   - just don't use it
   //   ^   - just don't use it
   // Pending possibles:
   //   !   - Looks like '|'?
   //   -   - ?
   //   +   - ?
   // @abc,#abc,_abc,.abc,&abc
   if (Character.isLetterOrDigit(ch)) {
     return true;
   } else if ((ch == '.') || (ch == '_')) {
     // definately accept these
     return true;
   } else if ((ch == '@') || (ch == '&') || (ch == '-')) {
     // we'll consider these
     return true;
   } else {
     return false;
   }
 }
Example #3
0
 public boolean isBullet(Cell cell) {
   char c = get(cell);
   return (c == 'o' || c == '*')
       && isBlank(cell.getEast())
       && isBlank(cell.getWest())
       && Character.isLetterOrDigit(get(cell.getEast().getEast()));
 }
 /** This helper method will return the end of the next word in the buffer. */
 private static int getNextWordEnd(Segment text, int startPos) {
   for (char ch = text.setIndex(startPos); ch != Segment.DONE; ch = text.next()) {
     if (!Character.isLetterOrDigit(ch)) {
       return text.getIndex();
     }
   }
   return text.getEndIndex();
 }
Example #5
0
  /*
  Extracted words and lowercase the words from the indicated file.
  @param char_data: the file data
  @return char_data: after filter and normalize of the file data
  */
  public static List<Character> filter_chars_normalize(List<Character> char_data) throws Exception {

    for (int i = 0; i < char_data.size(); i++) {
      char ch = char_data.get(i);
      if (!Character.isLetterOrDigit(ch)) char_data.set(i, ' ');
      else char_data.set(i, Character.toLowerCase(ch));
    }
    return char_data;
  }
Example #6
0
 /**
  * ** Returns true if the specified character should be hex-encoded in a URL ** @param ch The
  * character to test ** @return True if the specified character should be hex-encoded in a URL
  */
 private static boolean shouldEncodeArgChar(char ch) {
   if (Character.isLetterOrDigit(ch)) {
     return false;
   } else if ((ch == '_') || (ch == '-') || (ch == '.')) {
     return false;
   } else {
     return true;
   }
 }
Example #7
0
 private static void validateLocalePart(String localePart) {
   for (int i = 0; i < localePart.length(); i++) {
     char ch = localePart.charAt(i);
     if (ch != '_' && ch != ' ' && !Character.isLetterOrDigit(ch)) {
       throw new IllegalArgumentException(
           "Locale part \"" + localePart + "\" contains invalid characters");
     }
   }
 }
Example #8
0
 public boolean isPalindrome(String s) {
   int len = s.length();
   if (len == 0) return true;
   int ind_l = 0, ind_r = len - 1;
   String str = s.toLowerCase();
   while (ind_l < ind_r) {
     while (ind_l < ind_r && !Character.isLetterOrDigit(str.charAt(ind_l))) {
       ++ind_l;
     }
     while (ind_l < ind_r && !Character.isLetterOrDigit(str.charAt(ind_r))) {
       --ind_r;
     }
     if (str.charAt(ind_l) == str.charAt(ind_r)) {
       ind_l++;
       ind_r--;
     } else return false;
   }
   return true;
 }
Example #9
0
 /**
  * Codage d'une chaine pour servir en tant que nom de fichier. Remplace tous ce qui n'est ni
  * lettre ni chiffre en code hexa préfixé par _
  */
 private static String codage(String s) {
   StringBuffer r = new StringBuffer();
   char a[] = s.toCharArray();
   for (int i = 0; i < a.length; i++) {
     char c = a[i];
     if (!Character.isLetterOrDigit(c)) r.append(PREFIX + Util.hex(c));
     else r.append(c);
   }
   return r.toString();
 }
Example #10
0
  /**
   * given a sentence, returns a new version of it which is lowercased and strips everything except
   * letters and digit from it
   */
  public static String canonicalizeSentence(String sentence) {
    if (sentence == null) return null;

    StringBuilder sb = new StringBuilder();
    for (char ch : sentence.toCharArray())
      if (Character.isLetterOrDigit(ch)) {
        sb.append(Character.toLowerCase(ch));
      }
    return sb.toString();
  }
 /**
  * cleanString.
  *
  * @param in a {@link java.lang.String} object.
  * @return a {@link java.lang.String} object.
  */
 public static String cleanString(String in) {
   StringBuffer out = new StringBuffer();
   char c;
   for (int i = 0; i < in.length(); i++) {
     c = in.charAt(i);
     if (c == ' ' || c == '-') out.append('_');
     else if (Character.isLetterOrDigit(c) || c == '_') {
       out.append(c);
     }
   }
   return out.toString().toLowerCase();
 }
Example #12
0
 public Vector getCloseTags(String desc) {
   final StringBuffer buf = new StringBuffer(desc);
   final Vector tags = new Vector();
   StringBuffer bit = null;
   char quotes = '\0';
   int i = -1;
   char lastC = ' ';
   while ((++i) < buf.length()) {
     switch (buf.charAt(i)) {
       case '<':
         if (quotes != '\0') bit = null;
         else if (bit != null) {
           if (MXP.tagDebug) {
             System.out.println("/TAG/CLOSER2S=" + Util.toStringList(tags));
             System.out.flush();
           }
           return tags;
         } else bit = new StringBuffer("");
         break;
       case '>':
         if ((quotes == '\0') && (bit != null) && (bit.toString().trim().length() > 0))
           tags.add(bit.toString().toUpperCase().trim());
         bit = null;
         break;
       case ' ':
       case '\t':
         if ((quotes == '\0') && (bit != null) && (bit.toString().trim().length() > 0))
           tags.add(bit.toString().toUpperCase().trim());
         bit = null;
         break;
       case '"':
       case '\'':
         if (lastC == '\\') bit = null;
         else if ((quotes != '\0') && (quotes == buf.charAt(i))) quotes = '\0';
         else if (quotes == '\0') quotes = buf.charAt(i);
         bit = null;
         break;
       default:
         if ((bit != null) && (Character.isLetterOrDigit(buf.charAt(i))))
           bit.append(buf.charAt(i));
         else bit = null;
         break;
     }
     lastC = buf.charAt(i);
   }
   if (MXP.tagDebug) {
     System.out.println("/TAG/CLOSERS=" + Util.toStringList(tags));
     System.out.flush();
   }
   return tags;
 }
Example #13
0
  /**
   * Handles info messages resulting from a query execution.
   *
   * @param msg info message
   * @return true if error was found
   */
  private boolean error(final String msg) {
    final String line = msg.replaceAll("[\\r\\n].*", "");
    Matcher m = XQERROR.matcher(line);
    int el, ec = 2;
    if (!m.matches()) {
      m = XMLERROR.matcher(line);
      if (!m.matches()) return true;
      el = Integer.parseInt(m.group(1));
      errFile = getEditor().file.path();
    } else {
      el = Integer.parseInt(m.group(1));
      ec = Integer.parseInt(m.group(2));
      errFile = m.group(3);
    }

    final EditorArea edit = find(IO.get(errFile), false);
    if (edit == null) return true;

    // find approximate error position
    final int ll = edit.last.length;
    int ep = ll;
    for (int e = 1, l = 1, c = 1; e < ll; ++c, e += cl(edit.last, e)) {
      if (l > el || l == el && c == ec) {
        ep = e;
        break;
      }
      if (edit.last[e] == '\n') {
        ++l;
        c = 0;
      }
    }
    if (ep < ll && Character.isLetterOrDigit(cp(edit.last, ep))) {
      while (ep > 0 && Character.isLetterOrDigit(cp(edit.last, ep - 1))) ep--;
    }
    edit.error(ep);
    errPos = ep;
    return true;
  }
Example #14
0
 public String computeUrl() {
   StringBuilder sb = new StringBuilder();
   if (null != title) {
     for (int i = 0; i < title.length(); i++) {
       Character c = title.charAt(i);
       sb.append(Character.isLetterOrDigit(c) ? c : '_');
     }
   }
   sb.append('_');
   if (null != id) {
     sb.append(id);
   }
   url = sb.toString();
   Logger.info("url: " + url);
   return url;
 }
Example #15
0
 /**
  * ** Returns true if the URL starts with a protocol definition (ie. "http://...") ** @param url
  * The URL to test ** @return True if the URL starts with a protocol definition
  */
 public static boolean isAbsoluteURL(String url) {
   if (url == null) {
     return false;
   } else {
     // per "http://en.wikipedia.org/wiki/URI_scheme" all URL "schemes" contain only
     // alphanumeric or "." characters, and appears to be < 16 characters in length.
     for (int i = 0; (i < 16) && (i < url.length()); i++) {
       char ch = url.charAt(i);
       if (ch == ':') {
         return true; // A colon is the first non-alphanumeric we ran in to
       } else if (!Character.isLetterOrDigit(ch) && (ch != '.')) {
         return false;
       }
     }
     return false;
   }
 }
  /**
   * This method gets called when a property we're interested in is about to change. In case we
   * don't like the new value we throw a PropertyVetoException to prevent the actual change from
   * happening.
   *
   * @param evt a <tt>PropertyChangeEvent</tt> object describing the event source and the property
   *     that will change.
   * @exception PropertyVetoException if we don't want the change to happen.
   */
  public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
    if (evt.getPropertyName().equals(PROP_STUN_SERVER_ADDRESS)) {
      // make sure that we have a valid fqdn or ip address.

      // null or empty port is ok since it implies turning STUN off.
      if (evt.getNewValue() == null) return;

      String host = evt.getNewValue().toString();
      if (host.trim().length() == 0) return;

      boolean ipv6Expected = false;
      if (host.charAt(0) == '[') {
        // This is supposed to be an IPv6 litteral
        if (host.length() > 2 && host.charAt(host.length() - 1) == ']') {
          host = host.substring(1, host.length() - 1);
          ipv6Expected = true;
        } else {
          // This was supposed to be a IPv6 address, but it's not!
          throw new PropertyVetoException("Invalid address string" + host, evt);
        }
      }

      for (int i = 0; i < host.length(); i++) {
        char c = host.charAt(i);
        if (Character.isLetterOrDigit(c)) continue;

        if ((c != '.' && c != ':') || (c == '.' && ipv6Expected) || (c == ':' && !ipv6Expected))
          throw new PropertyVetoException(host + " is not a valid address nor host name", evt);
      }

    } // is prop_stun_server_address
    else if (evt.getPropertyName().equals(PROP_STUN_SERVER_PORT)) {

      // null or empty port is ok since it implies turning STUN off.
      if (evt.getNewValue() == null) return;

      String port = evt.getNewValue().toString();
      if (port.trim().length() == 0) return;

      try {
        Integer.valueOf(evt.getNewValue().toString());
      } catch (NumberFormatException ex) {
        throw new PropertyVetoException(port + " is not a valid port! " + ex.getMessage(), evt);
      }
    }
  }
  /**
   * Has duplicate: {@link
   * com.intellij.coverage.listeners.CoverageListener#sanitize(java.lang.String, java.lang.String)}
   * as FileUtil is not available in client's vm
   */
  @NotNull
  public static String sanitizeFileName(@NotNull String name) {
    StringBuilder result = new StringBuilder();

    for (int i = 0; i < name.length(); i++) {
      final char ch = name.charAt(i);

      if (ch > 0 && ch < 255) {
        if (Character.isLetterOrDigit(ch)) {
          result.append(ch);
        } else {
          result.append("_");
        }
      }
    }

    return result.toString();
  }
Example #18
0
 /**
  * Strip out non-printing characters, replacing them with a character which will not change where
  * the end of the first sentence is found. This character is the hash mark, '&#035;'.
  */
 public String stripNonPrintingChars(String s, Doc doc) {
   if (!stripNonPrintables) return s;
   char[] sa = s.toCharArray();
   for (int i = 0; i < sa.length; i++) {
     char c = sa[i];
     // TODO still have an issue with Unicode: 0xfc in java.lang.String.toUpperCase comments
     //            if (Character.isDefined(c))
     if (Character.isLetterOrDigit(c)) continue;
     // There must be a better way that is still platform independent!
     if (c == ' ' || c == '.' || c == ',' || c == '\r' || c == '\t' || c == '\n' || c == '!'
         || c == '?' || c == ';' || c == ':' || c == '[' || c == ']' || c == '(' || c == ')'
         || c == '~' || c == '@' || c == '#' || c == '$' || c == '%' || c == '^' || c == '&'
         || c == '*' || c == '-' || c == '=' || c == '+' || c == '_' || c == '|' || c == '\\'
         || c == '/' || c == '\'' || c == '}' || c == '{' || c == '"' || c == '<' || c == '>'
         || c == '`') continue;
     /* Doesn't seem to return the expected values?
                 int val = Character.getNumericValue(c);
     //            if (s.indexOf("which is also a test for non-printable") != -1)
     //                System.out.println("** Char " + i + "[" + c + "], val =" + val); //DEBUG
                 // Ranges from http://www.unicode.org/unicode/reports/tr20/
                 // Should really replace 0x2028 and  0x2029 with <br/>
                 if (val == 0x0 ||
                     inRange(val, 0x2028, 0x2029) ||
                     inRange(val, 0x202A, 0x202E) ||
                     inRange(val, 0x206A, 0x206F) ||
                     inRange(val, 0xFFF9, 0xFFFC) ||
                     inRange(val, 0xE0000, 0xE007F)) {
                     if (trace) {
                         System.out.println("Warning: changed non-printing character  " + sa[i] + " in " + doc.name());
                     }
                     sa[i] = '#';
                 }
     */
     // Replace the non-printable character with a printable character
     // which does not change the end of the first sentence
     sa[i] = '#';
   }
   return new String(sa);
 }
Example #19
0
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
      String uri = getDecodedUri(request);
      try {
        boolean use_hex = false;
        String f_name = request.getParameter("frame_id");
        String hex_string = request.getParameter("hex_string");
        if (f_name == null) {
          throw new RuntimeException("Cannot find value for parameter \'frame_id\'");
        }
        if (hex_string != null && hex_string.toLowerCase().equals("true")) {
          use_hex = true;
        }

        Frame dataset = DKV.getGet(f_name);
        // TODO: Find a way to determing the hex_string parameter. It should not always be false
        InputStream is = dataset.toCSV(true, use_hex);
        response.setContentType("application/octet-stream");
        // Clean up the file name
        int x = f_name.length() - 1;
        boolean dot = false;
        for (; x >= 0; x--)
          if (!Character.isLetterOrDigit(f_name.charAt(x)) && f_name.charAt(x) != '_')
            if (f_name.charAt(x) == '.' && !dot) dot = true;
            else break;
        String suggested_fname = f_name.substring(x + 1).replace(".hex", ".csv");
        if (!suggested_fname.endsWith(".csv")) suggested_fname = suggested_fname + ".csv";
        f_name = suggested_fname;
        response.addHeader("Content-Disposition", "attachment; filename=" + f_name);
        setResponseStatus(response, HttpServletResponse.SC_OK);
        OutputStream os = response.getOutputStream();
        water.util.FileUtils.copyStream(is, os, 2048);
      } catch (Exception e) {
        sendErrorResponse(response, e, uri);
      } finally {
        logRequest("GET", request, response);
      }
    }
Example #20
0
 /**
  * Replaces letters or numbers that are on horizontal or vertical lines, with the appropriate
  * character that will make the line continuous (| for vertical and - for horizontal lines)
  */
 public void replaceTypeOnLine() {
   int width = getWidth();
   int height = getHeight();
   for (int yi = 0; yi < height; yi++) {
     for (int xi = 0; xi < width; xi++) {
       char c = get(xi, yi);
       if (Character.isLetterOrDigit(c)) {
         boolean isOnHorizontalLine = isOnHorizontalLine(xi, yi);
         boolean isOnVerticalLine = isOnVerticalLine(xi, yi);
         if (isOnHorizontalLine && isOnVerticalLine) {
           set(xi, yi, '+');
           if (DEBUG) System.out.println("replaced type on line '" + c + "' with +");
         } else if (isOnHorizontalLine) {
           set(xi, yi, '-');
           if (DEBUG) System.out.println("replaced type on line '" + c + "' with -");
         } else if (isOnVerticalLine) {
           set(xi, yi, '|');
           if (DEBUG) System.out.println("replaced type on line '" + c + "' with |");
         }
       }
     }
   }
 }
 private static String FilterID(String id) {
   if (id == null) {
     return null;
   } else {
     StringBuffer newID = new StringBuffer();
     int st = 0;
     for (int i = 0; i < id.length(); i++) {
       char ch = Character.toLowerCase(id.charAt(i));
       if (Character.isLetterOrDigit(ch)) {
         newID.append(ch);
         st = 1;
       } else if (st == 1) {
         newID.append("_");
         st = 0;
       } else {
         // ignore char
       }
     }
     while ((newID.length() > 0) && (newID.charAt(newID.length() - 1) == '_')) {
       newID.setLength(newID.length() - 1);
     }
     return newID.toString();
   }
 }
Example #22
0
  /**
   * Do "smart" encodging on a string. This means that valid HTML entities and tags, Helma macros
   * and HTML comments are passed through unescaped, while other occurrences of '<', '>' and '&' are
   * encoded to HTML entities.
   *
   * @param str the string to encode
   * @param ret the string buffer to encode to
   * @param paragraphs if true use p tags for paragraphs, otherwise just use br's
   * @param allowedTags a set containing the names of allowed tags as strings. All other tags will
   *     be escaped
   */
  public static final void encode(
      String str, StringBuffer ret, boolean paragraphs, Set<String> allowedTags) {
    if (str == null) {
      return;
    }

    int l = str.length();

    // where to insert the <p> tag in case we want to create a paragraph later on
    int paragraphStart = ret.length();

    // what kind of element/text are we leaving and entering?
    // this is one of TEXT|SEMIBLOCK|BLOCK|INTERNAL
    // depending on this information, we decide whether and how to insert
    // paragraphs and line breaks. "entering" a tag means we're at the '<'
    // and exiting means we're at the '>', not that it's a start or close tag.
    byte entering = TEXT;
    byte exiting = TEXT;

    Stack<String> openTags = new Stack<String>();

    // are we currently within a < and a > that consitute some kind of tag?
    // we use tag balancing to know whether we are inside a tag (and should
    // pass things through unchanged) or outside (and should encode stuff).
    boolean insideTag = false;

    // are we inside an HTML tag?
    boolean insideHtmlTag = false;
    boolean insideCloseTag = false;
    byte htmlTagMode = TAG_NAME;

    // if we are inside a <code> tag, we encode everything to make
    // documentation work easier
    boolean insideCodeTag = false;
    boolean insidePreTag = false;

    // are we within a Helma <% macro %> tag? We treat macro tags and
    // comments specially, since we can't rely on tag balancing
    // to know when we leave a macro tag or comment.
    boolean insideMacroTag = false;

    // are we inside an HTML comment?
    boolean insideComment = false;

    // the quotation mark we are in within an HTML or Macro tag, if any
    char htmlQuoteChar = '\u0000';
    char macroQuoteChar = '\u0000';

    // number of newlines met since the last non-whitespace character
    int linebreaks = 0;

    // did we meet a backslash escape?
    boolean escape = false;

    boolean triggerBreak = false;

    for (int i = 0; i < l; i++) {
      char c = str.charAt(i);

      // step one: check if this is the beginning of an HTML tag, comment or
      // Helma macro.
      if (c == '<') {
        if (i < (l - 2)) {
          if (!insideMacroTag && ('%' == str.charAt(i + 1))) {
            // this is the beginning of a Helma macro tag
            if (!insideCodeTag) {
              insideMacroTag = insideTag = true;
              macroQuoteChar = '\u0000';
            }
          } else if (('!' == str.charAt(i + 1)) && ('-' == str.charAt(i + 2))) {
            // the beginning of an HTML comment?
            if (!insideCodeTag) {
              insideComment = insideTag = ((i < (l - 3)) && ('-' == str.charAt(i + 3)));
            }
          } else if (!insideTag) {
            // check if this is a HTML tag.
            insideCloseTag = ('/' == str.charAt(i + 1));
            int tagStart = insideCloseTag ? (i + 2) : (i + 1);
            int j = tagStart;

            while ((j < l) && Character.isLetterOrDigit(str.charAt(j))) j++;

            if ((j > tagStart) && (j < l)) {
              String tagName = str.substring(tagStart, j).toLowerCase();

              if ("code".equals(tagName) && insideCloseTag && insideCodeTag) {
                insideCodeTag = false;
              }

              if (((allowedTags == null) || allowedTags.contains(tagName))
                  && allTags.contains(tagName)
                  && !insideCodeTag) {
                insideHtmlTag = insideTag = true;
                htmlQuoteChar = '\u0000';
                htmlTagMode = TAG_NAME;

                exiting = entering;
                entering = TEXT;

                if (internalTags.contains(tagName)) {
                  entering = INTERNAL;
                } else if (blockTags.contains(tagName)) {
                  entering = BLOCK;
                } else if (semiBlockTags.contains(tagName)) {
                  entering = paragraphs ? BLOCK : SEMIBLOCK;
                }

                if (entering > 0) {
                  triggerBreak = !insidePreTag;
                }

                if (insideCloseTag) {
                  int t = openTags.search(tagName);

                  if (t == -1) {
                    i = j;
                    insideHtmlTag = insideTag = false;

                    continue;
                  } else if (t > 1) {
                    for (int k = 1; k < t; k++) {
                      Object tag = openTags.pop();
                      if (!emptyTags.contains(tag)) {
                        ret.append("</");
                        ret.append(tag);
                        ret.append(">");
                      }
                    }
                  }

                  openTags.pop();
                } else {
                  openTags.push(tagName);
                }

                if ("code".equals(tagName) && !insideCloseTag) {
                  insideCodeTag = true;
                }

                if ("pre".equals(tagName)) {
                  insidePreTag = !insideCloseTag;
                }
              }
            }
          }
        } // if (i < l-2)
      }

      if ((triggerBreak || linebreaks > 0) && !Character.isWhitespace(c)) {

        if (!insideTag) {
          exiting = entering;
          entering = TEXT;
          if (exiting >= SEMIBLOCK) {
            paragraphStart = ret.length();
          }
        }

        if (entering != INTERNAL && exiting != INTERNAL) {
          int swallowBreaks = 0;
          if (paragraphs
              && (entering != BLOCK || exiting != BLOCK)
              && (exiting < BLOCK)
              && (linebreaks > 1)
              && paragraphStart < ret.length()) {
            ret.insert(paragraphStart, "<p>");
            ret.append("</p>");
            swallowBreaks = 2;
          }

          // treat entering a SEMIBLOCK as entering a TEXT
          int _entering = entering == SEMIBLOCK ? TEXT : entering;
          for (int k = linebreaks - 1; k >= 0; k--) {
            if (k >= swallowBreaks && k >= _entering && k >= exiting) {
              ret.append("<br />");
            }
            ret.append(newLine);
          }
          if (exiting >= SEMIBLOCK || linebreaks > 1) {
            paragraphStart = ret.length();
          }
        }

        linebreaks = 0;
        triggerBreak = false;
      }

      switch (c) {
        case '<':
          if (insideTag) {
            ret.append('<');
          } else {
            ret.append("&lt;");
          }

          break;

        case '&':

          // check if this is an HTML entity already,
          // in which case we pass it though unchanged
          if ((i < (l - 3)) && !insideCodeTag) {
            // is this a numeric entity?
            if (str.charAt(i + 1) == '#') {
              int j = i + 2;

              while ((j < l) && Character.isDigit(str.charAt(j))) j++;

              if ((j < l) && (str.charAt(j) == ';')) {
                ret.append("&");

                break;
              }
            } else {
              int j = i + 1;

              while ((j < l) && Character.isLetterOrDigit(str.charAt(j))) j++;

              if ((j < l) && (str.charAt(j) == ';')) {
                ret.append("&");

                break;
              }
            }
          }

          // we didn't reach a break, so encode the ampersand as HTML entity
          ret.append("&amp;");

          break;

        case '\\':
          ret.append(c);

          if (insideTag && !insideComment) {
            escape = !escape;
          }

          break;

        case '"':
        case '\'':
          ret.append(c);

          if (!insideComment) {
            // check if the quote is escaped
            if (insideMacroTag) {
              if (escape) {
                escape = false;
              } else if (macroQuoteChar == c) {
                macroQuoteChar = '\u0000';
              } else if (macroQuoteChar == '\u0000') {
                macroQuoteChar = c;
              }
            } else if (insideHtmlTag) {
              if (escape) {
                escape = false;
              } else if (htmlQuoteChar == c) {
                htmlQuoteChar = '\u0000';
                htmlTagMode = TAG_SPACE;
              } else if (htmlQuoteChar == '\u0000') {
                htmlQuoteChar = c;
              }
            }
          }

          break;

        case '\n':
          if (insideTag || insidePreTag) {
            ret.append('\n');
          } else {
            linebreaks++;
          }

          break;
        case '\r':
          if (insideTag || insidePreTag) {
            ret.append('\r');
          }
          break;

        case '>':

          // For Helma macro tags and comments, we overrule tag balancing,
          // i.e. we don't require that '<' and '>' be balanced within
          // macros and comments. Rather, we check for the matching closing tag.
          if (insideComment) {
            ret.append('>');
            insideComment = !((str.charAt(i - 2) == '-') && (str.charAt(i - 1) == '-'));
          } else if (insideMacroTag) {
            ret.append('>');
            insideMacroTag = !((str.charAt(i - 1) == '%') && (macroQuoteChar == '\u0000'));
          } else if (insideHtmlTag) {
            ret.append('>');

            // only leave HTML tag if quotation marks are balanced
            // within that tag.
            insideHtmlTag = htmlQuoteChar != '\u0000';

            // Check if this is an empty tag so we don't generate an
            // additional </close> tag.
            if (str.charAt(i - 1) == '/') {
              // this is to avoid misinterpreting tags like
              // <a href=http://foo/> as empty
              if (htmlTagMode != TAG_ATT_VAL && htmlTagMode != TAG_ATT_NAME) {
                openTags.pop();
              }
            }

            exiting = entering;
            if (exiting > 0) {
              triggerBreak = !insidePreTag;
            }

          } else {
            ret.append("&gt;");
          }

          // check if we still are inside any kind of tag
          insideTag = insideComment || insideMacroTag || insideHtmlTag;
          insideCloseTag = insideTag;

          break;

        default:
          if (insideHtmlTag && !insideCloseTag) {
            switch (htmlTagMode) {
              case TAG_NAME:
                if (!Character.isLetterOrDigit(c)) {
                  htmlTagMode = TAG_SPACE;
                }
                break;
              case TAG_SPACE:
                if (Character.isLetterOrDigit(c)) {
                  htmlTagMode = TAG_ATT_NAME;
                }
                break;
              case TAG_ATT_NAME:
                if (c == '=') {
                  htmlTagMode = TAG_ATT_VAL;
                } else if (c == ' ') {
                  htmlTagMode = TAG_SPACE;
                }
                break;
              case TAG_ATT_VAL:
                if (Character.isWhitespace(c) && htmlQuoteChar == '\u0000') {
                  htmlTagMode = TAG_SPACE;
                }
                break;
            }
          }
          if (c < 128) {
            ret.append(c);
          } else if ((c >= 128) && (c < 256)) {
            ret.append(transform[c - 128]);
          } else {
            ret.append("&#");
            ret.append((int) c);
            ret.append(";");
          }

          escape = false;
      }
    }

    // if tags were opened but not closed, close them.
    int o = openTags.size();

    if (o > 0) {
      for (int k = 0; k < o; k++) {
        Object tag = openTags.pop();
        if (!emptyTags.contains(tag)) {
          ret.append("</");
          ret.append(tag);
          ret.append(">");
        }
      }
    }

    // add remaining newlines we may have collected
    int swallowBreaks = 0;
    if (paragraphs && entering < BLOCK) {
      ret.insert(paragraphStart, "<p>");
      ret.append("</p>");
      swallowBreaks = 2;
    }

    if (linebreaks > 0) {
      for (int i = linebreaks - 1; i >= 0; i--) {
        if (i >= swallowBreaks && i > exiting) {
          ret.append("<br />");
        }
        ret.append(newLine);
      }
    }
  }
  @NotNull
  private Pattern getPattern(String pattern) {
    if (!Comparing.strEqual(pattern, myPattern)) {
      myCompiledPattern = null;
      myPattern = pattern;
    }
    if (myCompiledPattern == null) {
      boolean allowToLower = true;
      final int eol = pattern.indexOf('\n');
      if (eol != -1) {
        pattern = pattern.substring(0, eol);
      }
      if (pattern.length() >= 80) {
        pattern = pattern.substring(0, 80);
      }

      final @NonNls StringBuffer buffer = new StringBuffer();

      if (containsOnlyUppercaseLetters(pattern)) {
        allowToLower = false;
      }

      if (allowToLower) {
        buffer.append(".*");
      }

      boolean firstIdentifierLetter = true;
      for (int i = 0; i < pattern.length(); i++) {
        final char c = pattern.charAt(i);
        if (Character.isLetterOrDigit(c)) {
          // This logic allows to use uppercase letters only to catch the name like PDM for
          // PsiDocumentManager
          if (Character.isUpperCase(c) || Character.isDigit(c)) {

            if (!firstIdentifierLetter) {
              buffer.append("[^A-Z]*");
            }

            buffer.append("[");
            buffer.append(c);
            if (allowToLower || i == 0) {
              buffer.append('|');
              buffer.append(Character.toLowerCase(c));
            }
            buffer.append("]");
          } else if (Character.isLowerCase(c)) {
            buffer.append('[');
            buffer.append(c);
            buffer.append('|');
            buffer.append(Character.toUpperCase(c));
            buffer.append(']');
          } else {
            buffer.append(c);
          }

          firstIdentifierLetter = false;
        } else if (c == '*') {
          buffer.append(".*");
          firstIdentifierLetter = true;
        } else if (c == '.') {
          buffer.append("\\.");
          firstIdentifierLetter = true;
        } else if (c == ' ') {
          buffer.append("[^A-Z]*\\ ");
          firstIdentifierLetter = true;
        } else {
          firstIdentifierLetter = true;
          // for standard RegExp engine
          // buffer.append("\\u");
          // buffer.append(Integer.toHexString(c + 0x20000).substring(1));

          // for OROMATCHER RegExp engine
          buffer.append("\\x");
          buffer.append(Integer.toHexString(c + 0x20000).substring(3));
        }
      }

      buffer.append(".*");

      try {
        myCompiledPattern = new Perl5Compiler().compile(buffer.toString());
      } catch (MalformedPatternException e) {
        // do nothing
      }
    }

    return myCompiledPattern;
  }
  public void generate(IndentWriter writer) {
    writer.println("Configuration Details");

    try {
      writer.indent();

      writer.println(
          "version=" + Constants.AZUREUS_VERSION + ", subver=" + Constants.AZUREUS_SUBVER);

      writer.println("System Properties");

      try {
        writer.indent();

        Properties props = System.getProperties();

        Iterator it = new TreeSet(props.keySet()).iterator();

        while (it.hasNext()) {

          String key = (String) it.next();

          writer.println(key + "=" + props.get(key));
        }
      } finally {

        writer.exdent();
      }

      writer.println("Environment");

      try {
        writer.indent();

        Map<String, String> env = System.getenv();

        if (env == null) {

          writer.println("Not supported");

        } else {

          Iterator it = new TreeSet(env.keySet()).iterator();

          while (it.hasNext()) {

            String key = (String) it.next();

            writer.println(key + "=" + env.get(key));
          }
        }
      } finally {

        writer.exdent();
      }

      writer.println("Azureus Config");

      ConfigurationDefaults defaults = ConfigurationDefaults.getInstance();

      try {
        writer.indent();

        Set<String> keys =
            new TreeSet<String>(
                new Comparator<String>() {
                  public int compare(String o1, String o2) {
                    return (o1.compareToIgnoreCase(o2));
                  }
                });

        keys.addAll(propertiesMap.keySet());

        Iterator<String> it = keys.iterator();

        while (it.hasNext()) {

          String key = it.next();

          // don't dump crypto stuff

          if (ignoreKeyForDump(key)) {

            continue;
          }

          Object value = propertiesMap.get(key);

          boolean bParamExists = defaults.doesParameterDefaultExist(key.toString());

          if (!bParamExists) {

            key = "[NoDef] " + key;
          } else {

            Object def = defaults.getParameter(key);

            if (def != null && value != null) {

              if (!BEncoder.objectsAreIdentical(def, value)) {

                key = "-> " + key;
              }
            }
          }

          if (value instanceof Long) {

            writer.println(key + "=" + value);

          } else if (value instanceof List) {

            writer.println(
                key + "=" + BDecoder.decodeStrings((List) BEncoder.clone(value)) + "[list]");

          } else if (value instanceof Map) {

            writer.println(
                key + "=" + BDecoder.decodeStrings((Map) BEncoder.clone(value)) + "[map]");

          } else if (value instanceof byte[]) {

            byte[] b = (byte[]) value;

            boolean hex = false;

            for (int i = 0; i < b.length; i++) {

              char c = (char) b[i];

              if (!(Character.isLetterOrDigit(c)
                  || "\\ `¬\"£$%^&*()-_=+[{]};:'@#~,<.>/?'".indexOf(c) != -1)) {

                hex = true;

                break;
              }
            }
            writer.println(
                key + "=" + (hex ? ByteFormatter.nicePrint(b) : bytesToString((byte[]) value)));

          } else {

            writer.println(key + "=" + value + "[unknown]");
          }
        }
      } finally {

        writer.exdent();
      }
    } finally {

      writer.exdent();
    }
  }
  public void dumpConfigChanges(IndentWriter writer) {
    ConfigurationDefaults defaults = ConfigurationDefaults.getInstance();

    Set<String> keys =
        new TreeSet<String>(
            new Comparator<String>() {
              public int compare(String o1, String o2) {
                return (o1.compareToIgnoreCase(o2));
              }
            });

    keys.addAll(propertiesMap.keySet());

    Iterator<String> it = keys.iterator();

    while (it.hasNext()) {

      String key = it.next();

      // don't dump crypto stuff

      if (ignoreKeyForDump(key)) {

        continue;
      }

      Object value = propertiesMap.get(key);

      boolean bParamExists = defaults.doesParameterDefaultExist(key.toString());

      if (bParamExists) {

        Object def = defaults.getParameter(key);

        if (def != null && value != null) {

          if (!BEncoder.objectsAreIdentical(def, value)) {

            if (value instanceof Long) {

              writer.println(key + "=" + value);

            } else if (value instanceof List) {

              writer.println(
                  key + "=" + BDecoder.decodeStrings((List) BEncoder.clone(value)) + "[list]");

            } else if (value instanceof Map) {

              writer.println(
                  key + "=" + BDecoder.decodeStrings((Map) BEncoder.clone(value)) + "[map]");

            } else if (value instanceof byte[]) {

              byte[] b = (byte[]) value;

              boolean hex = false;

              for (int i = 0; i < b.length; i++) {

                char c = (char) b[i];

                if (!(Character.isLetterOrDigit(c)
                    || "\\ `¬\"£$%^&*()-_=+[{]};:'@#~,<.>/?'".indexOf(c) != -1)) {

                  hex = true;

                  break;
                }
              }
              writer.println(
                  key + "=" + (hex ? ByteFormatter.nicePrint(b) : bytesToString((byte[]) value)));

            } else {

              writer.println(key + "=" + value + "[unknown]");
            }
          }
        }
      }
    }
  }
    public void setPattern(String globPattern) {
      char[] gPat = globPattern.toCharArray();
      char[] rPat = new char[gPat.length * 2];
      boolean isWin32 = (File.separatorChar == '\\');
      boolean inBrackets = false;
      int j = 0;

      this.globPattern = globPattern;

      if (isWin32) {
        // On windows, a pattern ending with *.* is equal to ending with *
        int len = gPat.length;
        if (globPattern.endsWith("*.*")) {
          len -= 2;
        }
        for (int i = 0; i < len; i++) {
          switch (gPat[i]) {
            case '*':
              rPat[j++] = '.';
              rPat[j++] = '*';
              break;

            case '?':
              rPat[j++] = '.';
              break;

            case '\\':
              rPat[j++] = '\\';
              rPat[j++] = '\\';
              break;

            default:
              if ("+()^$.{}[]".indexOf(gPat[i]) >= 0) {
                rPat[j++] = '\\';
              }
              rPat[j++] = gPat[i];
              break;
          }
        }
      } else {
        for (int i = 0; i < gPat.length; i++) {
          switch (gPat[i]) {
            case '*':
              if (!inBrackets) {
                rPat[j++] = '.';
              }
              rPat[j++] = '*';
              break;

            case '?':
              rPat[j++] = inBrackets ? '?' : '.';
              break;

            case '[':
              inBrackets = true;
              rPat[j++] = gPat[i];

              if (i < gPat.length - 1) {
                switch (gPat[i + 1]) {
                  case '!':
                  case '^':
                    rPat[j++] = '^';
                    i++;
                    break;

                  case ']':
                    rPat[j++] = gPat[++i];
                    break;
                }
              }
              break;

            case ']':
              rPat[j++] = gPat[i];
              inBrackets = false;
              break;

            case '\\':
              if (i == 0 && gPat.length > 1 && gPat[1] == '~') {
                rPat[j++] = gPat[++i];
              } else {
                rPat[j++] = '\\';
                if (i < gPat.length - 1 && "*?[]".indexOf(gPat[i + 1]) >= 0) {
                  rPat[j++] = gPat[++i];
                } else {
                  rPat[j++] = '\\';
                }
              }
              break;

            default:
              // if ("+()|^$.{}<>".indexOf(gPat[i]) >= 0) {
              if (!Character.isLetterOrDigit(gPat[i])) {
                rPat[j++] = '\\';
              }
              rPat[j++] = gPat[i];
              break;
          }
        }
      }
      this.pattern = Pattern.compile(new String(rPat, 0, j), Pattern.CASE_INSENSITIVE);
    }
  protected boolean generate(TrackerWebPageRequest request, TrackerWebPageResponse response)
      throws IOException {
    InetSocketAddress local_address = request.getLocalAddress();

    if (local_address == null) {

      return (false);
    }

    String host = local_address.getAddress().getHostAddress();

    String url = request.getURL();

    if (TRACE) {
      System.out.println("url: " + url);
    }

    if (!url.startsWith("/TiVoConnect?")) {

      return (false);
    }

    int pos = url.indexOf('?');

    if (pos == -1) {

      return (false);
    }

    String[] bits = url.substring(pos + 1).split("&");

    Map<String, String> args = new HashMap<String, String>();

    for (String bit : bits) {

      String[] x = bit.split("=");

      args.put(x[0], URLDecoder.decode(x[1], "UTF-8"));
    }

    if (TRACE) {
      System.out.println("args: " + args);
    }

    // root folder /TiVoConnect?Command=QueryContainer&Container=%2F

    String command = args.get("Command");

    if (command == null) {

      return (false);
    }

    String reply = null;

    if (command.equals("QueryContainer")) {

      String container = args.get("Container");

      if (container == null) {

        return (false);
      }

      if (container.equals("/")) {

        reply =
            "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
                + NL
                + "<TiVoContainer>"
                + NL
                + "    <Details>"
                + NL
                + "        <Title>"
                + server_name
                + "</Title>"
                + NL
                + "        <ContentType>x-container/tivo-server</ContentType>"
                + NL
                + "        <SourceFormat>x-container/folder</SourceFormat>"
                + NL
                + "        <TotalItems>1</TotalItems>"
                + NL
                + "    </Details>"
                + NL
                + "    <Item>"
                + NL
                + "        <Details>"
                + NL
                + "            <Title>"
                + server_name
                + "</Title>"
                + NL
                + "            <ContentType>x-container/tivo-videos</ContentType>"
                + NL
                + "            <SourceFormat>x-container/folder</SourceFormat>"
                + NL
                + "        </Details>"
                + NL
                + "        <Links>"
                + NL
                + "            <Content>"
                + NL
                + "                <Url>/TiVoConnect?Command=QueryContainer&amp;Container="
                + urlencode("/Content")
                + "</Url>"
                + NL
                + "                <ContentType>x-container/tivo-videos</ContentType>"
                + NL
                + "            </Content>"
                + NL
                + "        </Links>"
                + NL
                + "    </Item>"
                + NL
                + "    <ItemStart>0</ItemStart>"
                + NL
                + "    <ItemCount>1</ItemCount>"
                + NL
                + "</TiVoContainer>";

      } else if (container.startsWith("/Content")) {

        boolean show_categories = getShowCategories();

        String recurse = args.get("Recurse");

        if (recurse != null && recurse.equals("Yes")) {

          show_categories = false;
        }

        TranscodeFileImpl[] tfs = getFiles();

        String category_or_tag = null;

        Map<String, ContainerInfo> categories_or_tags = null;

        if (show_categories) {

          if (container.startsWith("/Content/")) {

            category_or_tag = container.substring(container.lastIndexOf('/') + 1);

          } else {

            categories_or_tags = new HashMap<String, ContainerInfo>();
          }
        }

        // build list of applicable items

        List<ItemInfo> items = new ArrayList<ItemInfo>(tfs.length);

        for (TranscodeFileImpl file : tfs) {

          if (!file.isComplete()) {

            // see if we can set up a stream xcode for this but only if we
            // know the duration and the transcode is in progress (done in setup)

            if (!setupStreamXCode(file)) {

              continue;
            }
          }

          if (category_or_tag != null) {

            boolean hit = false;

            String[] cats = file.getCategories();
            String[] tags = file.getTags(true);

            for (String[] strs : new String[][] {cats, tags}) {

              for (String c : strs) {

                if (c.equals(category_or_tag)) {

                  hit = true;
                }
              }
            }

            if (!hit) {

              continue;
            }
          }

          FileInfo info = new FileInfo(file, host);

          if (info.isOK()) {

            boolean skip = false;

            if (categories_or_tags != null) {

              String[] cats = file.getCategories();
              String[] tags = file.getTags(true);

              if (cats.length > 0 || tags.length > 0) {

                skip = true;

                for (String[] strs : new String[][] {cats, tags}) {

                  for (String s : strs) {

                    ContainerInfo cont = categories_or_tags.get(s);

                    if (cont == null) {

                      items.add(cont = new ContainerInfo(s));

                      categories_or_tags.put(s, cont);
                    }

                    cont.addChild();
                  }
                }
              }
            }

            if (!skip) {

              items.add(info);
            }
          }
        }

        // sort

        String sort_order = args.get("SortOrder");

        if (sort_order != null) {

          String[] keys = Constants.PAT_SPLIT_COMMA.split(sort_order);

          final List<Comparator<ItemInfo>> comparators = new ArrayList<Comparator<ItemInfo>>();
          final List<Boolean> reverses = new ArrayList<Boolean>();

          for (String key : keys) {

            boolean reverse = false;

            if (key.startsWith("!")) {

              reverse = true;

              key = key.substring(1);
            }

            Comparator<ItemInfo> comp = sort_comparators.get(key);

            if (comp != null) {

              comparators.add(comp);
              reverses.add(reverse);
            }
          }

          if (comparators.size() > 0) {

            Collections.sort(
                items,
                new Comparator<ItemInfo>() {
                  public int compare(ItemInfo i1, ItemInfo i2) {
                    for (int i = 0; i < comparators.size(); i++) {

                      Comparator<ItemInfo> comp = comparators.get(i);

                      int res = comp.compare(i1, i2);

                      if (res != 0) {

                        if (reverses.get(i)) {

                          if (res < 0) {

                            res = 1;

                          } else {

                            res = -1;
                          }
                        }

                        return (res);
                      }
                    }

                    return (0);
                  }
                });
          }
        }

        // select items to return

        String item_count = args.get("ItemCount");
        String anchor_offset = args.get("AnchorOffset");
        String anchor = args.get("AnchorItem");

        int num_items;

        if (item_count == null) {

          num_items = items.size();

        } else {

          // can be negative if X items from end

          num_items = Integer.parseInt(item_count);
        }

        int
            anchor_index; // either one before or one after item to be returned depending on count
                          // +ve/-ve

        if (num_items < 0) {

          anchor_index = items.size();

        } else {

          anchor_index = -1;
        }

        if (anchor != null) {

          for (int i = 0; i < items.size(); i++) {

            ItemInfo info = items.get(i);

            if (anchor.equals(info.getLinkURL())) {

              anchor_index = i;
            }
          }
        }

        if (anchor_offset != null) {

          anchor_index += Integer.parseInt(anchor_offset);

          if (anchor_index < -1) {

            anchor_index = -1;

          } else if (anchor_index > items.size()) {

            anchor_index = items.size();
          }
        }

        int start_index;
        int end_index;

        if (num_items > 0) {

          start_index = anchor_index + 1;

          end_index = anchor_index + num_items;

        } else {

          start_index = anchor_index + num_items;

          end_index = anchor_index - 1;
        }

        if (start_index < 0) {

          start_index = 0;
        }

        if (end_index >= items.size()) {

          end_index = items.size() - 1;
        }

        int num_to_return = end_index - start_index + 1;

        if (num_to_return < 0) {

          num_to_return = 0;
        }

        String machine = getMachineName();

        if (machine == null) {

          // default until we find out what it is - can't see any way to get it apart from wait for
          // broadcast

          machine = "TivoHDDVR";
        }

        String header =
            "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
                + NL
                + "<TiVoContainer>"
                + NL
                + "    <Tivos>"
                + NL
                + "      <Tivo>"
                + machine
                + "</Tivo>"
                + NL
                + "    </Tivos>"
                + NL
                + "    <ItemStart>"
                + start_index
                + "</ItemStart>"
                + NL
                + "    <ItemCount>"
                + num_to_return
                + "</ItemCount>"
                + NL
                + "    <Details>"
                + NL
                + "        <Title>"
                + escape(container)
                + "</Title>"
                + NL
                + "        <ContentType>x-container/tivo-videos</ContentType>"
                + NL
                + "        <SourceFormat>x-container/folder</SourceFormat>"
                + NL
                + "        <TotalItems>"
                + items.size()
                + "</TotalItems>"
                + NL
                + "    </Details>"
                + NL;

        reply = header;

        for (int i = start_index; i <= end_index; i++) {

          ItemInfo item = items.get(i);

          if (item instanceof FileInfo) {

            FileInfo file = (FileInfo) item;

            long file_size = file.getTargetSize();

            String title = escape(file.getName());
            String desc = title;

            int MAX_TITLE_LENGTH = 30;

            if (title.length() > MAX_TITLE_LENGTH) {

              // TiVo has problems displaying a truncated title if it has
              // no spaces in it

              String temp = "";

              for (int j = 0; j < title.length(); j++) {

                char c = title.charAt(j);

                if (Character.isLetterOrDigit(c)) {

                  temp += c;
                } else {

                  temp += ' ';
                }
              }

              int space_pos = temp.indexOf(' ');

              if (space_pos == -1 || space_pos > MAX_TITLE_LENGTH) {

                temp = temp.substring(0, 30) + "...";
              }

              title = temp;
            }

            reply +=
                "    <Item>"
                    + NL
                    + "        <Details>"
                    + NL
                    + "            <Title>"
                    + title
                    + "</Title>"
                    + NL
                    + "            <ContentType>video/x-tivo-mpeg</ContentType>"
                    + NL
                    + "            <SourceFormat>video/x-ms-wmv</SourceFormat>"
                    + NL;

            if (file_size > 0) {
              reply += "            <SourceSize>" + file_size + "</SourceSize>" + NL;
            } else {
              long est_size = file.getEstimatedTargetSize();

              if (est_size > 0) {
                reply += "            <SourceSize>" + est_size + "</SourceSize>" + NL;
              }
            }

            reply +=
                "            <Duration>"
                    + file.getDurationMillis()
                    + "</Duration>"
                    + NL
                    + "            <Description>"
                    + desc
                    + "</Description>"
                    + NL
                    + "            <SourceChannel>0</SourceChannel>"
                    + NL
                    + "            <SourceStation></SourceStation>"
                    + NL
                    + "            <SeriesId></SeriesId>"
                    + NL
                    + "            <CaptureDate>"
                    + file.getCaptureDate()
                    + "</CaptureDate>"
                    + NL
                    + "        </Details>"
                    + NL
                    + "        <Links>"
                    + NL
                    + "            <Content>"
                    + NL
                    + "                <ContentType>video/x-tivo-mpeg</ContentType>"
                    + NL
                    + "                    <AcceptsParams>No</AcceptsParams>"
                    + NL
                    + "                    <Url>"
                    + file.getLinkURL()
                    + "</Url>"
                    + NL
                    + "                </Content>"
                    + NL
                    + "                <CustomIcon>"
                    + NL
                    + "                    <ContentType>video/*</ContentType>"
                    + NL
                    + "                    <AcceptsParams>No</AcceptsParams>"
                    + NL
                    + "                    <Url>urn:tivo:image:save-until-i-delete-recording</Url>"
                    + NL
                    + "                </CustomIcon>"
                    + NL
                    + "        </Links>"
                    + NL
                    + "    </Item>"
                    + NL;

          } else {

            ContainerInfo cont = (ContainerInfo) item;

            reply +=
                "    <Item>"
                    + NL
                    + "        <Details>"
                    + NL
                    + "            <Title>"
                    + cont.getName()
                    + "</Title>"
                    + NL
                    + "            <ContentType>x-container/tivo-videos</ContentType>"
                    + NL
                    + "            <SourceFormat>x-container/folder</SourceFormat>"
                    + NL
                    + "            <TotalItems>"
                    + cont.getChildCount()
                    + "</TotalItems>"
                    + NL
                    + "        </Details>"
                    + NL
                    + "        <Links>"
                    + NL
                    + "            <Content>"
                    + NL
                    + "                <Url>"
                    + cont.getLinkURL()
                    + "</Url>"
                    + NL
                    + "                <ContentType>x-container/tivo-videos</ContentType>"
                    + NL
                    + "            </Content>"
                    + NL
                    + "        </Links>"
                    + NL
                    + "    </Item>"
                    + NL;
          }
        }

        String footer = "</TiVoContainer>";

        reply += footer;
      }

    } else if (command.equals("QueryFormats")) {

      String source_format = args.get("SourceFormat");

      if (source_format != null && source_format.startsWith("video")) {

        // /TiVoConnect?Command=QueryFormats&SourceFormat=video%2Fx-tivo-mpeg

        reply =
            "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                + NL
                + "<TiVoFormats><Format>"
                + NL
                + "<ContentType>video/x-tivo-mpeg</ContentType><Description/>"
                + NL
                + "</Format></TiVoFormats>";
      }
    }

    if (reply == null) {

      return (false);
    }

    if (TRACE) {
      System.out.println("->" + reply);
    }

    response.setContentType("text/xml");

    response.getOutputStream().write(reply.getBytes("UTF-8"));

    return (true);
  }
Example #28
0
 /**
  * Returns true if the specified character is a full-text letter or digit.
  *
  * @param ch character to be tested
  * @return result of check
  */
 public static boolean ftChar(final int ch) {
   return ch >= '0' && (ch < 0x80 ? LOD[ch - '0'] : Character.isLetterOrDigit(ch));
 }
 /**
  * Checks to see if the specified character is a delimiter. We consider a character a delimiter if
  * it is anything but a letter or digit.
  *
  * @param c the character to test
  * @return true if it is a delimiter
  */
 private boolean isDelimiter(char c) {
   return !Character.isLetterOrDigit(c);
 }