Java Code Examples for java.util.Hashtable#clear()

The following examples show how to use java.util.Hashtable#clear() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static void main(String[] args) {

    //create Hashtable object
    Hashtable ht = new Hashtable();

    //add key value pairs to Hashtable
    ht.put("1", "One");
    ht.put("2", "Two");
    ht.put("3", "Three");

    /*
      To remove all values or clear Hashtable use
      void clear method() of Hashtable class. Remove method removes all
      key value pairs contained in Hashtable.
    */

    ht.clear();

    System.out.println("Total key value pairs in Hashtable are : " + ht.size());
  }
 
Example 2
Source Project: ramus   File: Request.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void readParams(final String line,
                               final Hashtable<String, String> params) {
    params.clear();
    final StringTokenizer st = new StringTokenizer(line, "&");
    try {
        while (st.hasMoreTokens()) {
            final StringTokenizer tmp = new StringTokenizer(st.nextToken(),
                    "=");
            final String key = tmp.nextToken();
            final String value = decoderString(tmp.nextToken());
            params.put(key, value);
        }
    } catch (final Exception e) {

    }
}
 
Example 3
public static void main(String[] args) {

        //create Hashtable object
        Hashtable ht = new Hashtable();

        //add key value pairs to Hashtable
        ht.put("1", "One");
        ht.put("2", "Two");
        ht.put("3", "Three");

    /*
      To remove all values or clear Hashtable use
      void clear method() of Hashtable class. Remove method removes all
      key value pairs contained in Hashtable.
    */

        ht.clear();

        System.out.println("Total key value pairs in Hashtable are : " + ht.size());
    }
 
Example 4
/**
 * Tests the format of the MDC portion of the layout to ensure
 * the key-value pairs we put in turn up in the output file.
 * @throws Exception
 */
public void testMDC() throws Exception {
  XMLLayout xmlLayout = new XMLLayout();
  xmlLayout.setProperties(true);
  root.addAppender(new FileAppender(xmlLayout, TEMP, false));

  Hashtable context = MDC.getContext();
  if (context != null) {
      context.clear();
  }
  MDC.put("key1", "val1");
  MDC.put("key2", "val2");

  logger.debug("Hello");
  Transformer.transform(
    TEMP, FILTERED,
    new Filter[] { new LineNumberFilter(),
        new JunitTestRunnerFilter(),
        new XMLTimestampFilter()});
  assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.mdc.1"));
}
 
Example 5
public void testMDCEscaped() throws Exception {
  XMLLayout xmlLayout = new XMLLayout();
  xmlLayout.setProperties(true);
  root.addAppender(new FileAppender(xmlLayout, TEMP, false));

  Hashtable context = MDC.getContext();
  if (context != null) {
      context.clear();
  }
  MDC.put("blahAttribute", "<blah value='blah'>");
  MDC.put("<blahKey value='blah'/>", "blahValue");

  logger.debug("Hello");
  Transformer.transform(
    TEMP, FILTERED,
    new Filter[] { new LineNumberFilter(),
        new JunitTestRunnerFilter(),
        new XMLTimestampFilter() });
  assertTrue(Compare.compare(FILTERED, "witness/xmlLayout.mdc.2"));
}
 
Example 6
Source Project: ramus   File: Request.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String getParams(final String line,
                               final Hashtable<String, String> params) {
    char c;
    int j = line.length();
    params.clear();
    for (int i = 0; i < line.length(); i++) {
        if (line.charAt(i) == ' ') {
            j = i;
            break;
        }
    }
    String res = null;
    for (int i = 0; i < j; i++) {
        c = line.charAt(i);
        if (c == '#') {
            res = line.substring(0, i);
        } else if (c == '?') {
            if (res == null) {
                res = line.substring(0, i);
            }
            readParams(line.substring(i + 1, j), params);
            break;
        }
    }
    if (res == null) {
        res = line.substring(0, j);
    }
    return res;
}
 
Example 7
Source Project: ontopia   File: ReqParamUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testParams2URLQueryUnrestricted() {
  ServletRequest fakeRequest;
  String queryURL;
  Hashtable params = new Hashtable();
  
  // (1) setup servlet mockup environ
  params.clear();
  params.put("foo_bar_42", "Kroyt");
  fakeRequest = new FakeServletRequest(params);
  
  queryURL = params2URLQuery(fakeRequest);
  assertTrue("Generated String is not like expected one (1): '" + queryURL + "'",
             queryURL.equals(""));

  // (2) setup servlet mockup environ
  Map keep = new HashMap();
  keep.put("add_something_42", null);
  params.clear();
  params.put("add_something_42", "langer dumpf backen Garden");
  fakeRequest = new FakeServletRequest(params);
  
  queryURL = params2URLQuery(fakeRequest, keep);
  assertTrue("Generated string is not like expected one (2).",
             queryURL.equals("add_something_42=langer+dumpf+backen+Garden"));

  // (3) setup servlet mockup environ
  keep.clear();
  keep.put("topic_id", null);
  keep.put("topicmap_id", null);
  params.clear();
  params.put("topic_id", "42");
  params.put("topicmap_id", "opera.xtm");
  fakeRequest = new FakeServletRequest(params);
  
  queryURL = params2URLQuery(fakeRequest, keep);
  assertTrue("Generated String is not like expected one (3): '" + queryURL + "'",
             queryURL.equals("topic_id=42&topicmap_id=opera.xtm") ||
             queryURL.equals("topicmap_id=opera.xtm&topic_id=42"));
}
 
Example 8
Source Project: ontopia   File: ReqParamUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testParams2URLQueryRestricted() {
  ServletRequest fakeRequest;
  String queryURL;
  Hashtable params = new Hashtable();
  Map wantedParamNames = new HashMap();
  
  // (1) setup servlet mockup environ
  params.clear();
  params.put("foo_bar_42", "Kr\u00f8yt");
  fakeRequest = new FakeServletRequest(params);
  
  queryURL = params2URLQuery(fakeRequest, wantedParamNames);
  assertTrue("Generated String is not like expected one (1): '" + queryURL + "'",
             queryURL.equals(""));

  // (2) setup servlet mockup environ
  wantedParamNames.put("id", null);
  params.clear();
  params.put("add_something_42", "langer dumpf backen Garden");
  params.put("id", "42");
  fakeRequest = new FakeServletRequest(params);
  
  queryURL = params2URLQuery(fakeRequest, wantedParamNames);
  assertTrue("Generated String is not like expected one (2).",
             queryURL.equals("id=42"));

  // (3) setup servlet mockup environ
  wantedParamNames.put("tm", null);
  params.clear();
  params.put("id", "42");
  params.put("add_something_42", "langer dumpf backen Garden");
  params.put("tm", "opera.xtm");
  fakeRequest = new FakeServletRequest(params);
  
  queryURL = params2URLQuery(fakeRequest, wantedParamNames);
  assertTrue("Generated String is not like expected one (3).",
             queryURL.equals("id=42&tm=opera.xtm") ||
             queryURL.equals("tm=opera.xtm&id=42"));
}
 
Example 9
Source Project: j2objc   File: HashtableTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * java.util.Hashtable#clear()
 */
public void test_clear() {
    // Test for method void java.util.Hashtable.clear()
    Hashtable h = hashtableClone(htfull);
    h.clear();
    assertEquals("Hashtable was not cleared", 0, h.size());
    Enumeration el = h.elements();
    Enumeration keys = h.keys();
    assertTrue("Hashtable improperly cleared", !el.hasMoreElements()
            && !(keys.hasMoreElements()));
}
 
Example 10
Source Project: j2objc   File: HashtableTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * java.util.Hashtable#isEmpty()
 */
public void test_isEmpty() {
    // Test for method boolean java.util.Hashtable.isEmpty()

    assertTrue("isEmpty returned incorrect value", !ht10.isEmpty());
    assertTrue("isEmpty returned incorrect value",
            new java.util.Hashtable().isEmpty());

    final Hashtable ht = new Hashtable();
    ht.put("0", "");
    Thread t1 = new Thread() {
        public void run() {
            while (!ht.isEmpty())
                ;
            ht.put("final", "");
        }
    };
    t1.start();
    for (int i = 1; i < 10000; i++) {
        synchronized (ht) {
            ht.remove(String.valueOf(i - 1));
            ht.put(String.valueOf(i), "");
        }
        int size;
        if ((size = ht.size()) != 1) {
            String result = "Size is not 1: " + size + " " + ht;
            // terminate the thread
            ht.clear();
            fail(result);
        }
    }
    // terminate the thread
    ht.clear();
}
 
Example 11
Source Project: commons-dbcp   File: TestConnectionPool.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * DBCP-128: BasicDataSource.getConnection()
 * Connections don't work as hashtable keys
 */
@Test
public void testHashing() throws Exception {
    final Connection con = getConnection();
    final Hashtable<Connection, String> hash = new Hashtable<>();
    hash.put(con, "test");
    assertEquals("test", hash.get(con));
    assertTrue(hash.containsKey(con));
    assertTrue(hash.contains("test"));
    hash.clear();
    con.close();
}
 
Example 12
void clearURLHandlers() throws Exception {
    final Field handlersFields = URL.class.getDeclaredField("handlers");
    if (handlersFields != null) {
        if (!handlersFields.isAccessible()) {
            handlersFields.setAccessible(true);
        }
        @SuppressWarnings("unchecked")
        final
        Hashtable<String, URLStreamHandler> handlers = (Hashtable<String, URLStreamHandler>) handlersFields
                .get(null);
        if (handlers != null) {
            handlers.clear();
        }
    }
}
 
Example 13
Source Project: netbeans   File: ActivatorTest.java    License: Apache License 2.0 4 votes vote down vote up
public void testProvidesRequiresNeedsParsing() throws Exception {
    Hashtable<String,String> headers = new Hashtable<String,String>();
    assertEquals(Collections.emptySet(), Activator.provides(headers));
    assertEquals(Collections.emptySet(), Activator.requires(headers));
    assertEquals(Collections.emptySet(), Activator.needs(headers));
    headers.put("Bundle-SymbolicName", "org.netbeans.modules.projectui");
    headers.put("OpenIDE-Module-Provides", "org.netbeans.modules.project.uiapi.ActionsFactory,   " +
            "org.netbeans.modules.project.uiapi.OpenProjectsTrampoline,  org.netbeans.modules.project.uiapi.ProjectChooserFactory");
    assertEquals(new TreeSet<String>(Arrays.asList(
            "cnb.org.netbeans.modules.projectui",
            "org.netbeans.modules.project.uiapi.ActionsFactory",
            "org.netbeans.modules.project.uiapi.OpenProjectsTrampoline",
            "org.netbeans.modules.project.uiapi.ProjectChooserFactory"
            )), Activator.provides(headers));
    assertEquals(Collections.emptySet(), Activator.requires(headers));
    assertEquals(Collections.emptySet(), Activator.needs(headers));
    headers.clear();
    headers.put("Require-Bundle", "org.netbeans.api.progress;bundle-version=\"[101.0.0,200)\", " +
            "org.netbeans.spi.quicksearch;bundle-version=\"[1.0.0,100)\"");
    headers.put("OpenIDE-Module-Requires", "org.openide.modules.InstalledFileLocator");
    assertEquals(Collections.emptySet(), Activator.provides(headers));
    assertEquals(new TreeSet<String>(Arrays.asList(
            "cnb.org.netbeans.api.progress",
            "cnb.org.netbeans.spi.quicksearch",
            "org.openide.modules.InstalledFileLocator"
            )), Activator.requires(headers));
    assertEquals(Collections.emptySet(), Activator.needs(headers));
    headers.clear();
    headers.put("OpenIDE-Module-Needs", "org.netbeans.modules.java.preprocessorbridge.spi.JavaSourceUtilImpl");
    assertEquals(Collections.emptySet(), Activator.provides(headers));
    assertEquals(Collections.emptySet(), Activator.requires(headers));
    assertEquals(Collections.singleton("org.netbeans.modules.java.preprocessorbridge.spi.JavaSourceUtilImpl"), Activator.needs(headers));
    headers.clear();
    String os = System.getProperty("os.name");
    System.setProperty("os.name", "Windows 2000");
    try {
        headers.put("Bundle-SymbolicName", "org.openide.modules");
        final TreeSet<String> export = new TreeSet<String>(Arrays.asList(
            "cnb.org.openide.modules",
            "org.openide.modules.os.Windows"
        ));
        if (isJavaFX()) {
            export.add("org.openide.modules.jre.JavaFX");
        }
        assertEquals(export, Activator.provides(headers));
        assertEquals(Collections.emptySet(), Activator.requires(headers));
        assertEquals(Collections.emptySet(), Activator.needs(headers));
    } finally {
        System.setProperty("os.name", os);
    }
}
 
Example 14
Source Project: Rholang   File: Main.java    License: MIT License 4 votes vote down vote up
/** Compute minimum set of character classes needed to disambiguate
  *  edges.  We optimistically assume that every character belongs to
  *  a single character class, and then incrementally split classes
  *  as we see edges that require discrimination between characters in
  *  the class. [CSA, 25-Jul-1999] */
 private void computeClasses(CSpec m_spec) {
   this.original_charset_size = m_spec.m_dtrans_ncols;
   this.ccls = new int[original_charset_size]; // initially all zero.

   int nextcls = 1;
   SparseBitSet clsA = new SparseBitSet(), clsB = new SparseBitSet();
   Hashtable h = new Hashtable();
   
   System.out.print("Working on character classes.");
   for (Enumeration e=m_spec.m_nfa_states.elements(); e.hasMoreElements(); ) {
     CNfa nfa = (CNfa) e.nextElement();
     if (nfa.m_edge==CNfa.EMPTY || nfa.m_edge==CNfa.EPSILON)
continue; // no discriminatory information.
     clsA.clearAll(); clsB.clearAll();
     for (int i=0; i<ccls.length; i++)
if (nfa.m_edge==i || // edge labeled with a character
    nfa.m_edge==CNfa.CCL && nfa.m_set.contains(i)) // set of characters
  clsA.set(ccls[i]);
else
  clsB.set(ccls[i]);
     // now figure out which character classes we need to split.
     clsA.and(clsB); // split the classes which show up on both sides of edge
     System.out.print(clsA.size()==0?".":":");
     if (clsA.size()==0) continue; // nothing to do.
     // and split them.
     h.clear(); // h will map old to new class name
     for (int i=0; i<ccls.length; i++)
if (clsA.get(ccls[i])) // a split class
  if (nfa.m_edge==i ||
      nfa.m_edge==CNfa.CCL && nfa.m_set.contains(i)) { // on A side
    Integer split = new Integer(ccls[i]);
    if (!h.containsKey(split))
      h.put(split, new Integer(nextcls++)); // make new class
    ccls[i] = ((Integer)h.get(split)).intValue();
  }
   }
   System.out.println();
   System.out.println("NFA has "+nextcls+" distinct character classes.");
   
   this.mapped_charset_size = nextcls;
 }
 
Example 15
Source Project: DeviceConnect-Android   File: ServiceInfoImpl.java    License: MIT License 4 votes vote down vote up
synchronized Map<String, byte[]> getProperties() {
    if ((_props == null) && (this.getTextBytes() != null)) {
        Hashtable<String, byte[]> properties = new Hashtable<String, byte[]>();
        try {
            int off = 0;
            while (off < getTextBytes().length) {
                // length of the next key value pair
                int len = getTextBytes()[off++] & 0xFF;
                if ((len == 0) || (off + len > getTextBytes().length)) {
                    properties.clear();
                    break;
                }
                // look for the '='
                int i = 0;
                for (; (i < len) && (getTextBytes()[off + i] != '='); i++) {
                    /* Stub */
                }

                // get the property name
                String name = readUTF(getTextBytes(), off, i);
                if (name == null) {
                    properties.clear();
                    break;
                }
                if (i == len) {
                    properties.put(name, NO_VALUE);
                } else {
                    byte value[] = new byte[len - ++i];
                    System.arraycopy(getTextBytes(), off + i, value, 0, len - i);
                    properties.put(name, value);
                    off += len;
                }
            }
        } catch (Exception exception) {
            // We should get better logging.
            logger.log(Level.WARNING, "Malformed TXT Field ", exception);
        }
        this._props = properties;
    }
    return (_props != null ? _props : Collections.<String, byte[]> emptyMap());
}
 
Example 16
/**
 * Tests problematic characters in multiple fields.
 * @throws Exception if parser can not be constructed
 *  or source is not a valid XML document.
 */
public void testProblemCharacters() throws Exception {
  String problemName = "com.example.bar<>&\"'";
  Logger logger = Logger.getLogger(problemName);
  Level level = new ProblemLevel(problemName);
  Exception ex = new IllegalArgumentException(problemName);
  String threadName = Thread.currentThread().getName();
  Thread.currentThread().setName(problemName);
  NDC.push(problemName);
  Hashtable mdcMap = MDC.getContext();
  if (mdcMap != null) {
      mdcMap.clear();
  }
  MDC.put(problemName, problemName);
  LoggingEvent event =
    new LoggingEvent(
      problemName, logger, level, problemName, ex);
  HTMLLayout layout = (HTMLLayout) createLayout();
  String result = layout.format(event);
  mdcMap = MDC.getContext();
  if (mdcMap != null) {
    mdcMap.clear();
  }

  Thread.currentThread().setName(threadName);

  //
  //  do a little fixup to make output XHTML
  //
  StringBuffer buf = new StringBuffer(
          "<!DOCTYPE table [<!ENTITY nbsp ' '>]><table>");
  buf.append(result);
  buf.append("</table>");
  String doc = buf.toString();
  for(int i = doc.lastIndexOf("<br>");
      i != -1;
      i = doc.lastIndexOf("<br>", i - 1)) {
      buf.replace(i, i + 4, "<br/>");
  }

  parse(buf.toString());
}
 
Example 17
/**
 * Tests problematic characters in multiple fields.
 * @throws Exception if parser can not be constructed or source is not a valid XML document.
 */
public void testProblemCharacters() throws Exception {
  String problemName = "com.example.bar<>&\"'";
  Logger logger = Logger.getLogger(problemName);
  Level level = new ProblemLevel(problemName);
  Exception ex = new IllegalArgumentException(problemName);
  String threadName = Thread.currentThread().getName();
  Thread.currentThread().setName(problemName);
  NDC.push(problemName);
  Hashtable mdcMap = MDC.getContext();
  if (mdcMap != null) {
      mdcMap.clear();
  }
  MDC.put(problemName, problemName);
  LoggingEvent event =
    new LoggingEvent(
      problemName, logger, level, problemName, ex);
  XMLLayout layout = (XMLLayout) createLayout();
  layout.setProperties(true);
  String result = layout.format(event);
  mdcMap = MDC.getContext();
  if (mdcMap != null) {
      mdcMap.clear();
  }
  Thread.currentThread().setName(threadName);

  Element parsedResult = parse(result);
  checkEventElement(parsedResult, event);

  int childElementCount = 0;

  for (
    Node node = parsedResult.getFirstChild(); node != null;
      node = node.getNextSibling()) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      childElementCount++;
      switch(childElementCount) {
          case 1:
          checkMessageElement((Element) node, problemName);
          break;

          case 2:
          checkNDCElement((Element) node, problemName);
          break;

          case 3:
          checkThrowableElement((Element) node, ex);
          break;

          case 4:
          checkPropertiesElement((Element) node, problemName, problemName);
          break;

          default:
          fail("Unexpected element");
          break;
      }

      break;

    case Node.COMMENT_NODE:
      break;

    case Node.TEXT_NODE:

      //  should only be whitespace
      break;

    default:
      fail("Unexpected node type");

      break;
    }
  }
}
 
Example 18
Source Project: ontopia   File: ReqParamUtilsTest.java    License: Apache License 2.0 4 votes vote down vote up
public void testParams2URLQueryNonAscii() {
  ServletRequest fakeRequest;
  String queryURL;
  Hashtable params = new Hashtable();
  Map wantedParamNames = new HashMap();
  wantedParamNames.put("foo_bar_42", null);

  String correct = "foo_bar_42=Kr%C3%B8yt";
  // NOTE: the following is no longer reproducible on 1.3. It looks
  // like Sun has fixed the problem.
  //
  // // need to account for JDK 1.3
  // if (System.getProperty("java.vm.version").startsWith("1.3"))
  //   correct = "foo_bar_42=Kr%C3%B8yt";
  
  // (1) setup servlet mockup environ
  params.clear();
  params.put("foo_bar_42", "Kr\u00f8yt");
  fakeRequest = new FakeServletRequest(params);
  
  queryURL = params2URLQuery(fakeRequest, wantedParamNames);
  assertTrue("Generated string not like expected (1): '" + queryURL + "'",
             queryURL.equals(correct));

  // (2) setup servlet mockup environ
  wantedParamNames.clear();
  wantedParamNames.put("id", null);
  params.clear();
  params.put("add_something_42", "langer dumpf backen Garden");
  params.put("id", "42");
  fakeRequest = new FakeServletRequest(params);
  
  queryURL = params2URLQuery(fakeRequest, wantedParamNames);
  assertTrue("Generated String is not like expected one (2): '" + queryURL + "'",
             queryURL.equals("id=42"));

  // (3) setup servlet mockup environ
  wantedParamNames.put("tm", null);
  params.clear();
  params.put("id", "42");
  params.put("add_something_42", "langer dumpf backen Garden");
  params.put("tm", "opera.xtm");
  fakeRequest = new FakeServletRequest(params);
  
  queryURL = params2URLQuery(fakeRequest, wantedParamNames);
  assertTrue("Generated String is not like expected one (3).",
             queryURL.equals("id=42&tm=opera.xtm") ||
             queryURL.equals("tm=opera.xtm&id=42"));
}
 
Example 19
Source Project: pluotsorbet   File: basic.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void test (TestHarness harness)
{
  // The toString tests have been commented out as they currently
  // print in reverse order from the std JDK.  Uncomment these if
  // we change our implementation to output in the same order.

  Hashtable hash = new Hashtable(13);

  harness.check (hash.toString(), "{}");
  harness.check (hash.isEmpty());

  hash.put(new Integer(1), "one");
  hash.put(new Integer(2), "two");
  hash.put(new Integer(3), "three");
  hash.put(new Integer(4), "four");
  hash.put(new Integer(5), "five");
  // Rehash should have just happened.
  hash.put(new Integer(6), "six");
  hash.put(new Integer(7), "seven");
  // Rehash should have just happened.
  hash.put(new Integer(8), "eight");
  hash.put(new Integer(9), "nine");
  hash.put(new Integer(10), "ten");
  hash.put(new Integer(11), "eleven");
  hash.put(new Integer(12), "twelve");
  hash.put(new Integer(13), "thirteen");
  hash.put(new Integer(14), "fourteen");
  // Rehash should have just happened.
  hash.put(new Integer(15), "fifteen");

  // harness.check (hash.toString());
  harness.check (! hash.isEmpty());
  harness.check (hash.size(), 15);

  Integer key = new Integer(13);
  String val = (String) hash.get(key);
  hash.put(key, val.toUpperCase());
  // harness.check (hash.toString());
  harness.check (hash.size(), 15);

  harness.check (hash.containsKey(key));
  harness.check (! hash.contains("thirteen"));
  harness.check (hash.contains("THIRTEEN"));

  hash.remove(key);
  // harness.check (hash.toString());
  harness.check (hash.size(), 14);

  hash.clear();
  harness.check (hash.toString(), "{}");
  harness.check (hash.size(), 0);
}