@Test
  public void testReplaceWholeWordsOnly() {
    String text = "This is";
    String exp = "This is";
    String actual = MiscUtils.replaceWholeWordOnly(text, "test", "TEST");
    assertEquals("No replace", exp, actual);

    text = "This is a test";
    exp = "This is a TEST";
    actual = MiscUtils.replaceWholeWordOnly(text, "test", "TEST");
    assertEquals("Single replace", exp, actual);

    text = "This is a\ntesting\ttested  \n test";
    exp = "This is a\ntesting\ttested  \n TEST";
    actual = MiscUtils.replaceWholeWordOnly(text, "test", "TEST");
    assertEquals("Only whole word", exp, actual);

    text = "  \n\t ";
    exp = "  \n\t ";
    actual = MiscUtils.replaceWholeWordOnly(text, "test", "TEST");
    assertEquals("No replace (spaces)", exp, actual);

    text = "";
    exp = "";
    actual = MiscUtils.replaceWholeWordOnly(text, "test", "TEST");
    assertEquals("Empty", exp, actual);
  }
Example #2
0
  public String toString() {
    StringBuffer sb = new StringBuffer();
    sb.append("\n----------- START CACHE BLOCK -----------");
    sb.append("\nEntry DN: ").append(entryDN);
    sb.append(" Valid Entry: ").append(isValidEntry);
    sb.append("\nOrganization: ").append(organizationDN);
    sb.append("\nString Attributes: ");
    if ((stringAttributes != null) && (!stringAttributes.isEmpty())) {
      sb.append(MiscUtils.mapSetToString(stringAttributes));
    }
    sb.append("\nByte Attributes: ");
    sb.append(MiscUtils.mapSetToString(byteAttributes));
    sb.append("\nByte Negative Attributes: ");
    if ((byteAttributes != null) && (!byteAttributes.isEmpty())) {
      sb.append(byteAttributes.getNegativeByteAttrClone().toString());
    }
    sb.append("\nCache Entries: ");

    if (cacheEntries != null && !cacheEntries.isEmpty()) {
      Iterator itr = cacheEntries.keySet().iterator();
      while (itr.hasNext()) {
        String principal = (String) itr.next();
        CacheEntry ce = (CacheEntry) cacheEntries.get(principal);
        sb.append("\nPrincipal: ").append(principal);
        sb.append(ce.toString());
      }
    } else {
      sb.append("<empty>");
    }
    sb.append("\n----------- END CACHE BLOCK -----------");
    return sb.toString();
  }
  @Test
  public void testTrimNonPrintableChars() {
    String input;
    String expected;
    String actual;

    // test non-trimming
    input = "Hello\n \t \r\n Justin";
    expected = input;
    actual = MiscUtils.trimNonPrintableChars(input);
    assertEquals(expected, actual);

    // test trimming
    char[] data = {0, 'H', 8, 'e', 'l', 'l', 3, 'o', '\r', '\n'};
    input = new String(data);
    expected = "Hello\r\n";
    actual = MiscUtils.trimNonPrintableChars(input);
    assertEquals(expected, actual);

    char[] data2 = {'H', 'e', 'l', 'l', 0, 3, 'o', '\r', '\n', 8};
    input = new String(data2);
    expected = "Hello\r\n";
    actual = MiscUtils.trimNonPrintableChars(input);
    assertEquals(expected, actual);
  }
  @Test
  public void testHtmlReplaceAll() {
    String regex = "\\s";
    String replacement = "";
    String expected, actual;
    // test all tags
    String text = "<html tag></html>";
    assertEquals(text, MiscUtils.htmlReplaceAll(text, regex, replacement));

    text = "<html tag>Text</html>";
    // test no replacement
    assertEquals(text, MiscUtils.htmlReplaceAll(text, regex, replacement));

    // test replacement
    text = "<html tag>  Text with spaces  </html>";
    expected = "<html tag>Textwithspaces</html>";
    actual = MiscUtils.htmlReplaceAll(text, regex, replacement);
    assertEquals(expected, actual);

    // test replacement with trailing characters
    text += "  not html  ";
    expected += "nothtml";
    actual = MiscUtils.htmlReplaceAll(text, regex, replacement);
    assertEquals(expected, actual);
  }
 /** Tests {@link MiscUtils#copy(Object)} */
 @Test
 public void testCopy() {
   CloneableCopy e = new CloneableCopy("elm");
   CloneableCopy copy = MiscUtils.copy(e);
   assertNotNull(copy);
   assertNotSame(e, copy);
   assertEquals(e, copy);
   assertNull(MiscUtils.copy(null));
 }
 /** Tests {@link MiscUtils#sequenceCount(String, String)}. */
 @Test(timeout = 5000)
 public void testSequenceCount() {
   int count = MiscUtils.sequenceCount("code", "code");
   assertEquals(1, count);
   count = MiscUtils.sequenceCount("code", "de");
   assertEquals(1, count);
   count = MiscUtils.sequenceCount("code", "no");
   assertEquals(0, count);
   count = MiscUtils.sequenceCount("aaaaa", "a");
   assertEquals(5, count);
 }
  @Test
  public void testIntern() {
    String s1 = new String("Test");
    String s2 = new String("Test");

    assertNotSame(s1, s2);
    assertEquals(s1, s2);

    s1 = MiscUtils.intern(s1);
    s2 = MiscUtils.intern(s2);
    assertSame(s1, s2);
  }
Example #8
0
 public static void setDemoFields(GLEventListener demo, GLWindow glWindow, boolean debug) {
   Assert.assertNotNull(demo);
   Assert.assertNotNull(glWindow);
   Window window = glWindow.getInnerWindow();
   if (debug) {
     MiscUtils.setFieldIfExists(demo, "glDebug", true);
     MiscUtils.setFieldIfExists(demo, "glTrace", true);
   }
   if (!MiscUtils.setFieldIfExists(demo, "window", window)) {
     MiscUtils.setFieldIfExists(demo, "glWindow", glWindow);
   }
 }
Example #9
0
  public static boolean isIntLocation(String string) {

    if (string == null) {
      return false;
    }

    String[] split = string.split(",");

    if (split.length != 4 && split.length != 3) {
      return false;
    }

    return MiscUtils.isInt(split[0]) && MiscUtils.isInt(split[1]) && MiscUtils.isInt(split[2]);
  }
  @Test
  public void testGetNextHtmlWord() {
    String text = "This is < html >text</html>";
    String exp = "< html >text</html>";

    int[] expIndices = new int[2];
    expIndices[0] = text.indexOf('<');
    expIndices[1] = text.lastIndexOf('>') + 1;
    int[] actIndices = new int[2];
    String token;
    token = MiscUtils.getNextHtmlWord(text, 0, actIndices);

    assertEquals("Html word", exp, token);
    assertTrue(
        "Html indicies: expIndices="
            + Arrays.toString(expIndices)
            + "; actIndices="
            + Arrays.toString(actIndices),
        Arrays.equals(expIndices, actIndices));

    text = "This is <html />";
    exp = "<html />";
    expIndices[0] = text.indexOf('<');
    expIndices[1] = text.lastIndexOf('>') + 1;

    token = MiscUtils.getNextHtmlWord(text, 0, actIndices);

    assertEquals("Html word", exp, token);
    assertTrue(
        "Html indicies: expIndices="
            + Arrays.toString(expIndices)
            + "; actIndices="
            + Arrays.toString(actIndices),
        Arrays.equals(expIndices, actIndices));

    text = "This is not html\n";
    exp = null;
    expIndices[0] = expIndices[1] = -1;

    token = MiscUtils.getNextHtmlWord(text, 0, actIndices);

    assertEquals("Html word", exp, token);
    assertTrue(
        "Html indicies: expIndices="
            + Arrays.toString(expIndices)
            + "; actIndices="
            + Arrays.toString(actIndices),
        Arrays.equals(expIndices, actIndices));
  }
  @Test
  public void testReplaceDelim() {
    String input = "SimpleTest";
    String oldDelim = "\\s";
    String newDelim = ",";

    assertEquals(input, MiscUtils.replaceDelim(input, oldDelim, newDelim));

    input = "This \n \t is \r\n a  \t sentence  ";
    String exp = "This,is,a,sentence";
    assertEquals(exp, MiscUtils.replaceDelim(input, oldDelim, newDelim));

    input = "";
    assertEquals(input, MiscUtils.replaceDelim(input, oldDelim, newDelim));
  }
Example #12
0
  private static void addClassFiles(String packageName, List<Class<?>> classes)
      throws ClassNotFoundException {
    // This will hold a list of directories matching the packageName
    // There may be more than one if a package is split over multiple paths
    List<String> resources = new ArrayList<String>();
    try {
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      if (loader == null) {
        throw new ClassNotFoundException("Can't get class loader.");
      }
      String path = !MiscUtils.isEmpty(packageName) ? packageName.replace('.', '/') : "/";
      // Ask for all resources for the path
      Enumeration<URL> elms = loader.getResources(path);
      while (elms.hasMoreElements()) {
        resources.add(FileUtils.uriDecodeFile(elms.nextElement().toString()));
      }
    } catch (Exception e) {
      throw new ClassNotFoundException(packageName + " does not appear to be a valid package", e);
    }

    // For every directory identified capture all the .class files
    for (String resourcePath : resources) {
      int jarFileIndex = resourcePath.indexOf("!/");
      // it is a jar file if it contains "!/
      if (jarFileIndex == -1) {
        // Get the list of the files contained in the package
        File directory = new File(resourcePath);
        String[] files = directory.list();
        if (files != null) {
          for (String file : files) {
            // we are only interested in .class files
            if (StringUtils.caseInsensitiveEndsWith(file, ".class")) {
              // removes the .class extension
              String className = file.substring(0, file.length() - 6);
              String path;
              if (!MiscUtils.isEmpty(packageName)) path = packageName + '.' + className;
              else path = className;
              classes.add(Class.forName(path));
            }
          }
        }
      } else {
        // lookup into the jar file
        addJarClassFiles(
            FileUtils.uriDecodeFile(resourcePath.substring(0, jarFileIndex)), packageName, classes);
      }
    }
  }
 @Test
 public void testIsLineTerminated() {
   assertTrue(MiscUtils.isLineTerminated("Justin\n"));
   assertTrue(MiscUtils.isLineTerminated("Justin\r\n"));
   assertTrue(MiscUtils.isLineTerminated("Justin\r"));
   assertTrue(MiscUtils.isLineTerminated("Justin<br>"));
   assertTrue(MiscUtils.isLineTerminated("Justin<br/>"));
   assertFalse(MiscUtils.isLineTerminated("Justin"));
   assertFalse(MiscUtils.isLineTerminated("Jus\ntin"));
   assertFalse(MiscUtils.isLineTerminated("\nJustin"));
   assertFalse(MiscUtils.isLineTerminated("Justin\n "));
 }
    @Override
    public int hashCode() {
      int result = 17;
      result = 31 * result + MiscUtils.safeHashCode(this.value);

      return result;
    }
  @Test // (timeout=2000)
  public void testGetNextWord() {
    List<String> expected = Arrays.asList("word1", "word2", "word3", "word4");
    List<String> actual = new ArrayList<String>();

    String text =
        "\t"
            + expected.get(0)
            + "  "
            + expected.get(1)
            + " \n\n"
            + expected.get(2)
            + "\n \t"
            + expected.get(3)
            + "\n";

    int index = 0;
    StringBuilder str = new StringBuilder();

    while ((index = MiscUtils.getNextWord(text, index, str, "\\s")) < text.length()) {
      // index = ItecoUtil.getNextWord(text, index, str, "\\s");
      String word = str.toString();
      index += word.length();
      actual.add(word);
      str = new StringBuilder();
    }

    assertEquals(expected, actual);
  }
 @Test(timeout = TIMEOUT)
 public void testDeepCopyNestedCollection() {
   ArrayList<ArrayList<?>> elmMatrix = new ArrayList<ArrayList<?>>();
   CloneableCopy elm1 = new CloneableCopy("elm1");
   CloneableCopy elm2 = new CloneableCopy("elm2");
   CloneableCopy elm3 = null;
   ArrayList<CloneableCopy> nested = new ArrayList<CloneableCopy>(2);
   Collections.addAll(nested, elm1, elm2, elm3);
   elmMatrix.add(nested);
   // try adding itself as element
   // elmMatrix.add(elmMatrix);
   ArrayList<ArrayList<?>> copy = MiscUtils.deepCollectionCopy(elmMatrix);
   assertNotNull(copy);
   assertNotSame(elmMatrix, copy);
   assertEquals(elmMatrix, copy);
   assertNotSame(elmMatrix.get(0), copy.get(0));
   // assertNotSame(elmMatrix.get(1),copy.get(1));
   // make sure nested was also copied
   ArrayList<?> nestedCopy = copy.get(0);
   for (int i = 0; i < nestedCopy.size(); ++i) {
     if (nested.get(i) != null) assertNotSame(nestedCopy.get(i), nested.get(i));
     else assertNull(nestedCopy.get(i));
     // assertEquals(nestedCopy.get(i),nested.get(i));
   }
 }
 @Test
 public void testClearStringBuilder() {
   StringBuilder s = new StringBuilder();
   s.append("Testing clear");
   MiscUtils.clearStringBuilder(s);
   assertEquals(0, s.length());
   assertEquals("", s.toString());
 }
  @Test
  public void testFormatTime() {
    long dt;
    String exp, actual;

    dt = 5;

    exp = "5 s";
    actual = MiscUtils.formatTime(dt, TimeUnit.SECONDS, TimeUnit.SECONDS, 0);
    assertEquals(exp, actual);

    dt = (long) 1e6;
    exp = "1.000 ms";

    actual = MiscUtils.formatTime(dt, TimeUnit.NANOSECONDS, TimeUnit.MILLISECONDS, 3);
    assertEquals(exp, actual);
  }
  @Test
  public void testSplit() {
    String input = "SimpleTest";
    String regex = "\\s";
    assertArrayEquals(new String[] {input}, MiscUtils.split(input, regex));

    input = "\t  \nThis \n \t is \r\n a  \t sentence  ";
    String[] exp = {"This", "is", "a", "sentence"};
    assertArrayEquals(exp, MiscUtils.split(input, regex));
    assertArrayEquals(exp, MiscUtils.split(input, regex + "+"));

    input = "";
    assertArrayEquals(new String[0], MiscUtils.split(input, regex));

    input = "  ";
    assertArrayEquals(new String[0], MiscUtils.split(input, regex));
  }
 @Test
 public void testCopySerialize() {
   // serializable but not cloneable
   SerializableCopy exp = new SerializableCopy("test");
   SerializableCopy copy = MiscUtils.copy(exp);
   assertNotSame(exp, copy);
   assertEquals(exp, copy);
 }
  private String testRetainedWhiteSpaceSplit(String expected) {
    StringBuilder str = new StringBuilder(1024);
    List<String> results;

    results = MiscUtils.retainedSpaceSplit(expected);
    for (String s : results) str.append(s);
    return str.toString();
  }
  @Test
  public void testEncodeHtml() {
    String input = "<html><body>&hitme!</body></html>";
    String exp = "&lt;html&gt;&lt;body&gt;&amp;hitme!&lt;/body&gt;&lt;/html&gt;";

    String act = MiscUtils.encodeHtml(input);

    assertEquals(exp, act);
  }
  /** Tests {@link MiscUtils#getLongestLine(String)}. */
  @Test(timeout = 5000)
  public void testGetLongestLine() {
    String text = "Single line";
    String line = text;
    assertEquals("Single Line", line, MiscUtils.getLongestLine(text));

    text = "12345\n123\n1234";
    line = "12345";
    assertEquals("Mult line", line, MiscUtils.getLongestLine(text));

    text = "123\n1234\n12345";
    line = "12345";
    assertEquals("Multi line last", line, MiscUtils.getLongestLine(text));

    text = "\n\n\n123\n\n\n12345\n\n1234\n\n\n";
    line = "12345";
    assertEquals("Multi line padded", line, MiscUtils.getLongestLine(text));
  }
Example #24
0
  protected BottomBarBadge(
      Context context,
      int position,
      final View tabToAddTo, // Rhyming accidentally! That's a Smoove Move!
      int backgroundColor) {
    super(context);

    ViewGroup.LayoutParams params =
        new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

    setLayoutParams(params);
    setGravity(Gravity.CENTER);
    MiscUtils.setTextAppearance(this, R.style.BB_BottomBarBadge_Text);

    int three = MiscUtils.dpToPixel(context, 3);
    ShapeDrawable backgroundCircle = BadgeCircle.make(three * 3, backgroundColor);
    setPadding(three, three, three, three);
    setBackgroundCompat(backgroundCircle);

    FrameLayout container = new FrameLayout(context);
    container.setLayoutParams(params);

    ViewGroup parent = (ViewGroup) tabToAddTo.getParent();
    parent.removeView(tabToAddTo);

    container.setTag(tabToAddTo.getTag());
    container.addView(tabToAddTo);
    container.addView(this);

    parent.addView(container, position);

    container
        .getViewTreeObserver()
        .addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
              @SuppressWarnings("deprecation")
              @Override
              public void onGlobalLayout() {
                adjustPositionAndSize(tabToAddTo);
              }
            });
  }
 /**
  * Test method for {@link com.gamesalutes.utils.MiscUtils#getHtmlMarkupLength(java.lang.String)}.
  */
 @Test
 public void testGetHtmlMarkupLength() {
   String str0 = "<a href=\"test\">";
   String str1 = "test";
   String str2 = "</a>";
   String text = str0 + str1 + str2;
   int expected = str0.length() + str2.length();
   int actual = MiscUtils.getHtmlMarkupLength(text);
   assertEquals("markup length", expected, actual);
 }
 @Test
 public void testWrapTextUsingHtml() {
   String word4 = "test";
   String word3 = "<text>she</text>";
   String word0 = "<text />";
   String word2 = "he";
   String word6 = "<text >desire</text>";
   String text = word4 + " " + word3 + " " + word0 + word2 + " " + word6;
   String exp = word4 + " " + word3 + " " + word0 + "<br>" + word2 + " " + word6;
   String act = MiscUtils.wrapText(text, 10, true, true);
   assertEquals(exp, act);
 }
  @Test
  public void testWrapText() {
    String word5 = "apple";
    String word4 = "keys";
    String word3 = "yes";

    String text = word5 + " " + word4 + " " + word3 + "\n" + word5 + " " + word4;

    String expected = word5 + " " + word4 + "\n" + word3 + "\n" + word5 + " " + word4;

    String actual = MiscUtils.wrapText(text, 10);

    assertEquals(expected, actual);
  }
  @Test
  public void testSplitEscaped() {
    String escape = "\"";
    String regex = "\\s";
    String test = "Simple";
    // simple test
    assertArrayEquals(new String[] {test}, MiscUtils.escapedSplit(test, regex, escape));
    // regular unescaped
    test = "One Two";
    assertArrayEquals(new String[] {"One", "Two"}, MiscUtils.escapedSplit(test, regex, escape));
    // simple escaped
    test = "\"One Two\"";
    assertArrayEquals(new String[] {"One Two"}, MiscUtils.escapedSplit(test, regex, escape));
    // complex escaped
    test = "\"One  Two\" Three  Four";
    assertArrayEquals(
        new String[] {"One  Two", "Three", "Four"}, MiscUtils.escapedSplit(test, regex, escape));

    // more complex escaped
    test = "One\t\"Two Three  Four\nFive\" \"Six Seven\"\" Eight Nine\" Ten  Eleven";
    assertArrayEquals(
        new String[] {"One", "Two Three  Four\nFive", "Six Seven", "Eight Nine", "Ten", "Eleven"},
        MiscUtils.escapedSplit(test, regex, escape));
  }
Example #29
0
  public static IntLocation getIntLocation(String string) {

    if (string == null) {
      MiscUtils.safeLogging("[Serverport] Unable to parse " + string + " as int location");
      return null;
    }

    String[] split = string.split(",");

    if (split.length != 4 && split.length != 3) {
      MiscUtils.safeLogging("[Serverport] Unable to parse " + string + " as int location");
      return null;
    }

    String name;
    if (split.length == 3) {
      name = ((World) MyServer.bukkitServer.getWorlds().get(0)).getName();
    } else {
      name = split[3];
    }

    return new IntLocation(
        MiscUtils.getInt(split[0]), MiscUtils.getInt(split[1]), MiscUtils.getInt(split[2]), name);
  }
 @Test
 public void testDeepCopyArray() {
   CloneableCopy elm1 = new CloneableCopy("elm1");
   CloneableCopy elm2 = new CloneableCopy("elm2");
   CloneableCopy elm3 = null;
   CloneableCopy[] elms = {elm1, elm2, elm3};
   CloneableCopy[] copy = MiscUtils.deepArrayCopy(elms);
   assertNotNull(copy);
   assertNotSame(elms, copy);
   assertArrayEquals(elms, copy);
   for (int i = 0; i < copy.length; ++i) {
     if (elms[i] != null) assertNotSame(elms[i], copy[i]);
     else assertNull(copy[i]);
   }
 }