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

The following examples show how to use java.util.Hashtable#containsKey() . 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
Source File: MoodleRestGroup.java    From MoodleRest with GNU General Public License v2.0 6 votes vote down vote up
public MoodleGroup[] __createGroups(String url, String token, MoodleGroup[] group) throws MoodleRestGroupException, UnsupportedEncodingException, MoodleRestException {
    Hashtable hash=new Hashtable();
    StringBuilder data=new StringBuilder();
    String functionCall=MoodleCallRestWebService.isLegacy()?MoodleServices.MOODLE_GROUP_CREATE_GROUPS.toString():MoodleServices.CORE_GROUP_CREATE_GROUPS.toString();
    data.append(URLEncoder.encode("wstoken", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(token, MoodleServices.ENCODING.toString()));
    data.append("&").append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(functionCall, MoodleServices.ENCODING.toString()));
    for (int i=0;i<group.length;i++) {
        if (group[i]==null) throw new MoodleRestGroupException();
        if (group[i].getCourseId()==null) throw new MoodleRestGroupException(); else data.append("&").append(URLEncoder.encode("groups["+i+"][courseid]", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(""+group[i].getCourseId(), MoodleServices.ENCODING.toString()));
        if (group[i].getName()==null || group[i].getName().equals("")) throw new MoodleRestGroupException(); else data.append("&").append(URLEncoder.encode("groups["+i+"][name]", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(""+group[i].getName(), MoodleServices.ENCODING.toString()));
        if (group[i].getDescription()==null) throw new MoodleRestGroupException(); else data.append("&").append(URLEncoder.encode("groups["+i+"][description]", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(""+group[i].getDescription(), MoodleServices.ENCODING.toString()));
        if (group[i].getEnrolmentKey()==null) throw new MoodleRestGroupException(); else data.append("&").append(URLEncoder.encode("groups["+i+"][enrolmentkey]", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(""+group[i].getEnrolmentKey(), MoodleServices.ENCODING.toString()));
    }
    data.trimToSize();
    NodeList elements=(new MoodleCallRestWebService()).__call(url,data.toString());
    for (int j=0;j<elements.getLength();j+=5) {
        hash.put(elements.item(j+2).getTextContent(), elements.item(j).getTextContent());
    }
    for (int i=0;i<group.length;i++) {
        if (hash.containsKey(group[i].getName()))
            group[i].setId(Long.parseLong((String)(hash.get(group[i].getName()))));
        else
            group[i]=null;
    }
    return group;
}
 
Example 2
Source File: WipoAlphaCorpusReader.java    From jatecs with GNU General Public License v3.0 6 votes vote down vote up
protected Hashtable<String, File> extractValidPaths(File f) {
    Hashtable<String, File> dirs = new Hashtable<String, File>();

    File[] files = f.listFiles(new ValidDirectory());
    if (files.length != 0) {
        for (int i = 0; i < files.length; i++) {
            Hashtable<String, File> validDirs = extractValidPaths(files[i]);
            Iterator<File> it = validDirs.values().iterator();
            while (it.hasNext()) {
                File fi = it.next();
                if (!dirs.containsKey(fi.getAbsolutePath()))
                    dirs.put(fi.getAbsolutePath(), fi);
            }
        }
    } else {
        if (!dirs.containsKey(f.getAbsolutePath()))
            dirs.put(f.getAbsolutePath(), f);
    }

    return dirs;
}
 
Example 3
Source File: LdapClient.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private boolean isBinaryValued(String attrid,
                               Hashtable<String, Boolean> binaryAttrs) {
    String id = attrid.toLowerCase(Locale.ENGLISH);

    return ((id.indexOf(";binary") != -1) ||
        defaultBinaryAttrs.containsKey(id) ||
        ((binaryAttrs != null) && (binaryAttrs.containsKey(id))));
}
 
Example 4
Source File: Game.java    From MET-CS665 with Apache License 2.0 5 votes vote down vote up
/**
 * function to set 4 hidden numbers.
 */

public void setNumbers() {
	Hashtable<Integer, Integer> table = new Hashtable<Integer, Integer>();
	for (int i = 0; i < numbers.length; i++) {
		int number = rand.nextInt(10); // initial one number from 0 to 9
		while (table.containsKey(number)) { // check if this number is already in the array
			number = rand.nextInt(10); // keep getting a new random int
		}
		table.put(number, number); // record this number
		numbers[i] = number;
	}
}
 
Example 5
Source File: DOMUtil.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static boolean isHidden(Node node, Hashtable hiddenNodes) {
    if (node instanceof com.sun.org.apache.xerces.internal.impl.xs.opti.NodeImpl) {
        return ((com.sun.org.apache.xerces.internal.impl.xs.opti.NodeImpl)node).getReadOnly();
    }
    else {
        return hiddenNodes.containsKey(node);
    }
}
 
Example 6
Source File: IdentAuthenticator.java    From j2ssh-maverick with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
  Grants permission only to those users, who connect from one of the
  hosts registered with add(InetRange,Hashtable) and whose names, as
  reported by identd daemon, are listed for the host the connection
  came from.
 */
public ServerAuthenticator startSession(Socket s)
                           throws IOException{

  int ind = getRangeIndex(s.getInetAddress());
  String user = null;

  //System.out.println("getRangeReturned:"+ind);

  if(ind < 0) return null; //Host is not on the list.

  ServerAuthenticatorNone auth = (ServerAuthenticatorNone)
                                 super.startSession(s);

  //System.out.println("super.startSession() returned:"+auth);
  if(auth == null) return null;

  //do the authentication 

  Hashtable<String,Object> user_names = users.elementAt(ind); 

  if(user_names != null){ //If need to do authentication
    Ident ident;
    ident = new Ident(s);
    //If can't obtain user name, fail
    if(!ident.successful) return null;
    //If user name is not listed for this address, fail
    if(!user_names.containsKey(ident.userName)) return null;
    user = ident.userName;
  }
  return new IdentAuthenticator(auth.in,auth.out,user);

}
 
Example 7
Source File: Host.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void buildInformEntries(Hashtable<InetAddress, Vector<String>> dest) {

        JDMHostInform host= (JDMHostInform) jjtGetParent();
        JDMInformInterestedHost hosts= (JDMInformInterestedHost) host.jjtGetParent();
        JDMInformItem inform = (JDMInformItem) hosts.jjtGetParent();
        JDMInformCommunity community = inform.getCommunity();
        String comm = community.getCommunity();

        InetAddress add = null;
        try {
            add = java.net.InetAddress.getByName(getHname());
        } catch(UnknownHostException e) {
            if (SNMP_LOGGER.isLoggable(Level.FINEST)) {
                SNMP_LOGGER.logp(Level.FINEST, Host.class.getName(),
                        "buildTrapEntries",
                        "Cannot create INFORM entry; got exception", e);
            }
            return;
        }

        Vector<String> list = null;
        if (dest.containsKey(add)){
            list = dest.get(add);
            if (!list.contains(comm)){
                list.addElement(comm);
            }
        } else {
            list = new Vector<String>();
            list.addElement(comm);
            dest.put(add,list);
        }
    }
 
Example 8
Source File: Host.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public void buildTrapEntries(Hashtable<InetAddress, Vector<String>> dest) {

        JDMHostTrap host= (JDMHostTrap) jjtGetParent();
        JDMTrapInterestedHost hosts= (JDMTrapInterestedHost) host.jjtGetParent();
        JDMTrapItem trap = (JDMTrapItem) hosts.jjtGetParent();
        JDMTrapCommunity community = trap.getCommunity();
        String comm = community.getCommunity();

        InetAddress add = null;
        try {
            add = java.net.InetAddress.getByName(getHname());
        } catch(UnknownHostException e) {
            if (SNMP_LOGGER.isLoggable(Level.FINEST)) {
                SNMP_LOGGER.logp(Level.FINEST, Host.class.getName(),
                        "buildTrapEntries",
                        "Cannot create TRAP entry; got exception", e);
            }
            return;
        }

        Vector<String> list = null;
        if (dest.containsKey(add)){
            list = dest.get(add);
            if (!list.contains(comm)){
                list.addElement(comm);
            }
        } else {
            list = new Vector<String>();
            list.addElement(comm);
            dest.put(add,list);
        }
    }
 
Example 9
Source File: Host.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void buildInformEntries(Hashtable<InetAddress, Vector<String>> dest) {

        JDMHostInform host= (JDMHostInform) jjtGetParent();
        JDMInformInterestedHost hosts= (JDMInformInterestedHost) host.jjtGetParent();
        JDMInformItem inform = (JDMInformItem) hosts.jjtGetParent();
        JDMInformCommunity community = inform.getCommunity();
        String comm = community.getCommunity();

        InetAddress add = null;
        try {
            add = java.net.InetAddress.getByName(getHname());
        } catch(UnknownHostException e) {
            if (SNMP_LOGGER.isLoggable(Level.FINEST)) {
                SNMP_LOGGER.logp(Level.FINEST, Host.class.getName(),
                        "buildTrapEntries",
                        "Cannot create INFORM entry; got exception", e);
            }
            return;
        }

        Vector<String> list = null;
        if (dest.containsKey(add)){
            list = dest.get(add);
            if (!list.contains(comm)){
                list.addElement(comm);
            }
        } else {
            list = new Vector<String>();
            list.addElement(comm);
            dest.put(add,list);
        }
    }
 
Example 10
Source File: CSV2TMXConverterDialog.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
private int maxColumns() throws IOException {
	int max = 0;
	InputStreamReader input = new InputStreamReader(new FileInputStream(csvPath), encoding);
	BufferedReader buffer = new BufferedReader(input);
	Hashtable<String, Integer> table1 = new Hashtable<String, Integer>();
	String line = buffer.readLine();
	while (line != null) {
		int i = countColumns(line);
		if (table1.containsKey("" + i)) { //$NON-NLS-1$
			int count = table1.get("" + i).intValue() + 1; //$NON-NLS-1$
			table1.put("" + i, new Integer(count)); //$NON-NLS-1$
		} else {
			table1.put("" + i, new Integer(1)); //$NON-NLS-1$
		}
		line = buffer.readLine();
	}
	Enumeration<String> e = table1.keys();
	String key = ""; //$NON-NLS-1$
	while (e.hasMoreElements()) {
		String s = e.nextElement();
		int value = table1.get(s).intValue();
		if (value > max) {
			max = value;
			key = s;
		}
	}
	return Integer.parseInt(key);
}
 
Example 11
Source File: MoodleRestCourse.java    From MoodleRest with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>From Moodle 2.3</p>
 * @param categories
 * @return
 * @throws UnsupportedEncodingException
 * @throws MoodleRestCourseException
 * @throws MoodleRestException
 */
public static MoodleCategory[] createCategories(MoodleCategory[] categories) throws UnsupportedEncodingException, MoodleRestCourseException, MoodleRestException {
  if (MoodleCallRestWebService.isLegacy()) throw new MoodleRestException(MoodleRestException.NO_LEGACY);
  StringBuilder data=new StringBuilder();
  String functionCall=MoodleServices.CORE_COURSE_CREATE_CATEGORIES.toString();
  if (MoodleCallRestWebService.getAuth()==null)
    throw new MoodleRestCourseException();
  else
    data.append(MoodleCallRestWebService.getAuth());
  data.append("&").append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(functionCall, MoodleServices.ENCODING.toString()));
  Hashtable<String, MoodleCategory> catStore=new Hashtable();
  for (int i=0; i<categories.length; i++) {
    if (categories[i].getName()==null) throw new MoodleRestCourseException(MoodleRestException.REQUIRED_PARAMETER+" name"); data.append("&").append(URLEncoder.encode("categories["+i+"][name]", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(""+categories[i].getName(), MoodleServices.ENCODING.toString()));
    if (categories[i].getParent()!=null) data.append("&").append(URLEncoder.encode("categories["+i+"][parent]", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(""+categories[i].getParent(), MoodleServices.ENCODING.toString()));
    if (categories[i].getIdNumber()!=null) data.append("&").append(URLEncoder.encode("categories["+i+"][idnumber]", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(""+categories[i].getIdNumber(), MoodleServices.ENCODING.toString()));
    if (categories[i].getDescription()!=null) data.append("&").append(URLEncoder.encode("categories["+i+"][description]", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(""+categories[i].getDescription(), MoodleServices.ENCODING.toString()));
    if (categories[i].getTheme()!=null) data.append("&").append(URLEncoder.encode("categories["+i+"][theme]", MoodleServices.ENCODING.toString())).append("=").append(URLEncoder.encode(""+categories[i].getTheme(), MoodleServices.ENCODING.toString()));
    catStore.put(categories[i].getName(), categories[i]);
  }
  NodeList elements=MoodleCallRestWebService.call(data.toString());
  long id=-1;
  for (int i=0;i<elements.getLength();i++) {
    String parent=elements.item(i).getParentNode().getParentNode().getParentNode().getParentNode().getNodeName();
    if (parent.equals("KEY"))
      parent=elements.item(i).getParentNode().getParentNode().getParentNode().getParentNode().getAttributes().getNamedItem("name").getNodeValue();
    String content=elements.item(i).getTextContent();
    String nodeName=elements.item(i).getParentNode().getAttributes().getNamedItem("name").getNodeValue();
    if (parent.equals("RESPONSE") && nodeName.equals("id")) {
      id=Long.parseLong(content);
    } else {
      if (parent.equals("RESPONSE") && nodeName.equals("name")) {
        if (catStore.containsKey(content))
          catStore.get(content).setId(id);
      }
    }
  }
  return categories;
}
 
Example 12
Source File: HttpUtils.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
   *
   * Parses a query string passed from the client to the
   * server and builds a <code>HashTable</code> object
   * with key-value pairs.
   * The query string should be in the form of a string
   * packaged by the GET or POST method, that is, it
   * should have key-value pairs in the form <i>key=value</i>,
   * with each pair separated from the next by a &amp; character.
   *
   * <p>A key can appear more than once in the query string
   * with different values. However, the key appears only once in
   * the hashtable, with its value being
   * an array of strings containing the multiple values sent
   * by the query string.
   *
   * <p>The keys and values in the hashtable are stored in their
   * decoded form, so
   * any + characters are converted to spaces, and characters
   * sent in hexadecimal notation (like <i>%xx</i>) are
   * converted to ASCII characters.
   *
   * @param s		a string containing the query to be parsed
   *
   * @return		a <code>HashTable</code> object built
   * 			from the parsed key-value pairs
   *
   * @exception IllegalArgumentException	if the query string
   *						is invalid
   *
   */

static public Hashtable parseQueryString(String s) {

  String valArray[] = null;

  if (s == null) {
    throw new IllegalArgumentException();
  }
  Hashtable ht = new Hashtable();
  StringBuffer sb = new StringBuffer();
  StringTokenizer st = new StringTokenizer(s, "&");
  while (st.hasMoreTokens()) {
    String pair = (String)st.nextToken();
    int pos = pair.indexOf('=');
    if (pos == -1) {
      // XXX
      // should give more detail about the illegal argument
      //throw new IllegalArgumentException();
      throw new IllegalArgumentException
        ("Query name, value pair without '=': '" +pair +"'.");
    }
    String key = parseName(pair.substring(0, pos), sb);
    String val = parseName(pair.substring(pos+1, pair.length()), sb);
    if (ht.containsKey(key)) {
      String oldVals[] = (String []) ht.get(key);
      valArray = new String[oldVals.length + 1];
      for (int i = 0; i < oldVals.length; i++)
        valArray[i] = oldVals[i];
      valArray[oldVals.length] = val;
    } else {
      valArray = new String[1];
      valArray[0] = val;
    }
    ht.put(key, valArray);
  }
  return ht;
}
 
Example 13
Source File: RewardForMissionEndImplementation.java    From malmo with MIT License 5 votes vote down vote up
@Override
public void getReward(MissionInit missionInit, MultidimensionalReward reward) {
    super.getReward(missionInit, reward);
    try {
        Hashtable<String, Object> properties = MalmoMod.getPropertiesForCurrentThread();
        if (properties.containsKey("QuitCode")) {
            float reward_value = parseQuitCode((String) properties.get("QuitCode"));
            reward.add( this.params.getDimension(), reward_value);
        }
    } catch (Exception e) {
    }
}
 
Example 14
Source File: HttpUtils.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 *
 * Parses a query string passed from the client to the
 * server and builds a <code>HashTable</code> object
 * with key-value pairs. 
 * The query string should be in the form of a string
 * packaged by the GET or POST method, that is, it
 * should have key-value pairs in the form <i>key=value</i>,
 * with each pair separated from the next by a &amp; character.
 *
 * <p>A key can appear more than once in the query string
 * with different values. However, the key appears only once in 
 * the hashtable, with its value being
 * an array of strings containing the multiple values sent
 * by the query string.
 * 
 * <p>The keys and values in the hashtable are stored in their
 * decoded form, so
 * any + characters are converted to spaces, and characters
 * sent in hexadecimal notation (like <i>%xx</i>) are
 * converted to ASCII characters.
 *
 * @param s                a string containing the query to be parsed
 *
 * @return                a <code>HashTable</code> object built
 *                         from the parsed key-value pairs
 *
 * @exception IllegalArgumentException        if the query string 
 *                                                is invalid
 *
 */
public static Hashtable<String,String[]> parseQueryString(String s) {

    String valArray[] = null;
    
    if (s == null) {
        throw new IllegalArgumentException();
    }
    Hashtable<String,String[]> ht = new Hashtable<String,String[]>();
    StringBuilder sb = new StringBuilder();
    StringTokenizer st = new StringTokenizer(s, "&");
    while (st.hasMoreTokens()) {
        String pair = st.nextToken();
        int pos = pair.indexOf('=');
        if (pos == -1) {
            // XXX
            // should give more detail about the illegal argument
            throw new IllegalArgumentException();
        }
        String key = parseName(pair.substring(0, pos), sb);
        String val = parseName(pair.substring(pos+1, pair.length()), sb);
        if (ht.containsKey(key)) {
            String oldVals[] = ht.get(key);
            valArray = new String[oldVals.length + 1];
            for (int i = 0; i < oldVals.length; i++) 
                valArray[i] = oldVals[i];
            valArray[oldVals.length] = val;
        } else {
            valArray = new String[1];
            valArray[0] = val;
        }
        ht.put(key, valArray);
    }
    return ht;
}
 
Example 15
Source File: Validator.java    From Hidden-Markov-Model with MIT License 5 votes vote down vote up
public boolean isValidTransitionMatrix(Hashtable<Pair<String, String>, Double> transitionMatrix, Vector<String> states) {
    if (transitionMatrix.size() != states.size() * states.size())
        return false;

    Hashtable<Pair<String, String>, Boolean> frequency = new Hashtable<Pair<String, String>, Boolean>();

    for (Pair<String, String> item : transitionMatrix.keySet()) {
        if (frequency.containsKey(item)) {
            return false;
        }
        frequency.put(item, true);
    }

    Hashtable<Pair<String, String>, Boolean> visited = new Hashtable<Pair<String, String>, Boolean>();

    for (Pair<String, String> first : transitionMatrix.keySet()) {
        double sum = 0.0;
        int entered = 0;
        String state = first.getKey();
        for (Pair<String, String> second: transitionMatrix.keySet()) {
            if (state.equals(second.getKey()) && !visited.containsKey(second)) {
                sum += transitionMatrix.get(second);
                entered++;
                visited.put(second, true);
            }
        }

        if (sum != 1.0 && entered > 0) {
            return false;
        }
    }

    return true;
}
 
Example 16
Source File: ServiceRegistrationImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Check if a bundle uses this service
 *
 * @param b Bundle to check
 * @return true if bundle uses this service
 */
boolean isUsedByBundle(Bundle b) {
  final Hashtable<Bundle, Integer> deps = dependents;
  if (deps != null) {
    boolean res = deps.containsKey(b);
    if (!res) {
      if (prototypeServiceInstances != null) {
        res = prototypeServiceInstances.containsKey(b);
      }
    }
    return res;
  }
  return false;
}
 
Example 17
Source File: Config.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses stanza names and values from configuration file to
 * stanzaTable (Hashtable). Hashtable key would be stanza names,
 * (libdefaults, realms, domain_realms, etc), and the hashtable value
 * would be another hashtable which contains the key-value pairs under
 * a stanza name. The value of this sub-hashtable can be another hashtable
 * containing another sub-sub-section or a vector of strings for
 * final values (even if there is only one value defined).
 * <p>
 * For duplicates section names, the latter overwrites the former. For
 * duplicate value names, the values are in a vector in its appearing order.
 * </ol>
 * Please note that this behavior is Java traditional. and it is
 * not the same as the MIT krb5 behavior, where:<ol>
 * <li>Duplicated root sections will be merged
 * <li>For duplicated sub-sections, the former overwrites the latter
 * <li>Duplicate keys for values are always saved in a vector
 * </ol>
 * @param v the strings in the file, never null, might be empty
 * @throws KrbException if there is a file format error
 */
@SuppressWarnings("unchecked")
private Hashtable<String,Object> parseStanzaTable(List<String> v)
        throws KrbException {
    Hashtable<String,Object> current = stanzaTable;
    for (String line: v) {
        // There are 3 kinds of lines
        // 1. a = b
        // 2. a = {
        // 3. }
        if (line.equals("}")) {
            // Go back to parent, see below
            current = (Hashtable<String,Object>)current.remove(" PARENT ");
            if (current == null) {
                throw new KrbException("Unmatched close brace");
            }
        } else {
            int pos = line.indexOf('=');
            if (pos < 0) {
                throw new KrbException("Illegal config content:" + line);
            }
            String key = line.substring(0, pos).trim();
            String value = trimmed(line.substring(pos+1));
            if (value.equals("{")) {
                Hashtable<String,Object> subTable;
                if (current == stanzaTable) {
                    key = key.toLowerCase(Locale.US);
                }
                subTable = new Hashtable<>();
                current.put(key, subTable);
                // A special entry for its parent. Put whitespaces around,
                // so will never be confused with a normal key
                subTable.put(" PARENT ", current);
                current = subTable;
            } else {
                Vector<String> values;
                if (current.containsKey(key)) {
                    Object obj = current.get(key);
                    // If a key first shows as a section and then a value,
                    // this is illegal. However, we haven't really forbid
                    // first value then section, which the final result
                    // is a section.
                    if (!(obj instanceof Vector)) {
                        throw new KrbException("Key " + key
                                + "used for both value and section");
                    }
                    values = (Vector<String>)current.get(key);
                } else {
                    values = new Vector<String>();
                    current.put(key, values);
                }
                values.add(value);
            }
        }
    }
    if (current != stanzaTable) {
        throw new KrbException("Not closed");
    }
    return current;
}
 
Example 18
Source File: CPUCCTClassContainer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Given this target node, and the array of its source-level children, treat them as follows:
 * 1. The info for a source child who has the same class as this node, is added to this node.
 * Its own children are processed recursively by calling this same method.
 * 2. The first source child whose class is different and was not observed before (not contained
 * in uniqChildCache) is added to uniqChildCache, and to allSourceChildren.
 * 3. All other source children are added to allSourceChildren, but not to uniqChildCache.
 */
protected void processChildren(int dataOfs, int methodNodeOfs, int nChildren, IntVector allSourceChildren,
                               Hashtable uniqChildCache) {
    int thisNodeClassOrPackageId = getMethodIdForNodeOfs(dataOfs);

    int nCalls = 0;
    long time0 = 0;
    long time1 = 0;

    for (int i = 0; i < nChildren; i++) {
        int sourceChildOfs = sourceContainer.getChildOfsForNodeOfs(methodNodeOfs, i);
        int sourceChildClassOrPackageId = methodIdMap.getClassOrPackageIdForMethodId(sourceContainer.getMethodIdForNodeOfs(sourceChildOfs));

        if (sourceChildClassOrPackageId == thisNodeClassOrPackageId) { // A child node has the same class as this node
            nCalls += sourceContainer.getNCallsForNodeOfs(sourceChildOfs);
            time0 += sourceContainer.getSelfTime0ForNodeOfs(sourceChildOfs);

            if (collectingTwoTimeStamps) {
                time1 += sourceContainer.getSelfTime1ForNodeOfs(sourceChildOfs);
            }

            // sourceChild's children logically become this node's children now.
            int nSourceChildChildren = sourceContainer.getNChildrenForNodeOfs(sourceChildOfs);

            if (nSourceChildChildren > 0) {
                this.processChildren(dataOfs, sourceChildOfs, nSourceChildChildren, allSourceChildren, uniqChildCache);
            }
        } else { // A child node belongs to a different class

            Integer key = Integer.valueOf(sourceChildClassOrPackageId);

            if (!uniqChildCache.containsKey(key)) {
                uniqChildCache.put(key, key);
            }

            allSourceChildren.add(sourceChildOfs);
        }
    }

    nCalls += getNCallsForNodeOfs(dataOfs);
    time0 += getSelfTime0ForNodeOfs(dataOfs);

    if (collectingTwoTimeStamps) {
        time1 += getSelfTime1ForNodeOfs(dataOfs);
    }

    setNCallsForNodeOfs(dataOfs, nCalls);
    setSelfTime0ForNodeOfs(dataOfs, time0);

    if (collectingTwoTimeStamps) {
        setSelfTime1ForNodeOfs(dataOfs, time1);
    }
}
 
Example 19
Source File: Config.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses stanza names and values from configuration file to
 * stanzaTable (Hashtable). Hashtable key would be stanza names,
 * (libdefaults, realms, domain_realms, etc), and the hashtable value
 * would be another hashtable which contains the key-value pairs under
 * a stanza name. The value of this sub-hashtable can be another hashtable
 * containing another sub-sub-section or a vector of strings for
 * final values (even if there is only one value defined).
 * <p>
 * For duplicates section names, the latter overwrites the former. For
 * duplicate value names, the values are in a vector in its appearing order.
 * </ol>
 * Please note that this behavior is Java traditional. and it is
 * not the same as the MIT krb5 behavior, where:<ol>
 * <li>Duplicated root sections will be merged
 * <li>For duplicated sub-sections, the former overwrites the latter
 * <li>Duplicate keys for values are always saved in a vector
 * </ol>
 * @param v the strings in the file, never null, might be empty
 * @throws KrbException if there is a file format error
 */
@SuppressWarnings("unchecked")
private Hashtable<String,Object> parseStanzaTable(List<String> v)
        throws KrbException {
    Hashtable<String,Object> current = stanzaTable;
    for (String line: v) {
        // There are 3 kinds of lines
        // 1. a = b
        // 2. a = {
        // 3. }
        if (line.equals("}")) {
            // Go back to parent, see below
            current = (Hashtable<String,Object>)current.remove(" PARENT ");
            if (current == null) {
                throw new KrbException("Unmatched close brace");
            }
        } else {
            int pos = line.indexOf('=');
            if (pos < 0) {
                throw new KrbException("Illegal config content:" + line);
            }
            String key = line.substring(0, pos).trim();
            String value = trimmed(line.substring(pos+1));
            if (value.equals("{")) {
                Hashtable<String,Object> subTable;
                if (current == stanzaTable) {
                    key = key.toLowerCase(Locale.US);
                }
                subTable = new Hashtable<>();
                current.put(key, subTable);
                // A special entry for its parent. Put whitespaces around,
                // so will never be confused with a normal key
                subTable.put(" PARENT ", current);
                current = subTable;
            } else {
                Vector<String> values;
                if (current.containsKey(key)) {
                    Object obj = current.get(key);
                    // If a key first shows as a section and then a value,
                    // this is illegal. However, we haven't really forbid
                    // first value then section, which the final result
                    // is a section.
                    if (!(obj instanceof Vector)) {
                        throw new KrbException("Key " + key
                                + "used for both value and section");
                    }
                    values = (Vector<String>)current.get(key);
                } else {
                    values = new Vector<String>();
                    current.put(key, values);
                }
                values.add(value);
            }
        }
    }
    if (current != stanzaTable) {
        throw new KrbException("Not closed");
    }
    return current;
}
 
Example 20
Source File: CustomerRatingDAO.java    From big-data-lite with MIT License 4 votes vote down vote up
public List<MovieTO> getMoviesByMood(int userId) {
    List<MovieTO> movieList = null;
    String search = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    MovieTO movieTO = null;
    MovieDAO movieDAO = new MovieDAO();
    String title = null;
    Hashtable<String, String> movieHash = new Hashtable<String, String>();

    search =
            "SELECT * FROM " + "(SELECT s.MID2 RESMOVIE,  (c.RATING * s.COR) SCORE " +
            "FROM CUST_RATING c, MOVIE_SIMILARITY s " +
            "WHERE c.MOVIEID = s.MID1 and s.MID2 != c.MOVIEID and c.USERID = ? " +
            "GROUP BY s.MID2, c.RATING * s.COR " +
            "ORDER by SCORE DESC) " + "WHERE ROWNUM <= 20";
    try {
        if (conn != null) {
            //initialize movieList only when connection is successful
            movieList = new ArrayList<MovieTO>();
            stmt = conn.prepareStatement(search);
            stmt.setInt(1, userId);
            rs = stmt.executeQuery();
            while (rs.next()) {
                //Retrieve by column name
                int id = rs.getInt("RESMOVIE");

                //create new object
                movieTO = movieDAO.getMovieById(id);
                if (movieTO != null) {
                    title = movieTO.getTitle();
                    //Make sure movie title doesn't exist before in the movieHash
                    if (!movieHash.containsKey(title)) {
                        movieHash.put(title, title);
                        movieList.add(movieTO);
                    }
                } //if (movieTO != null)
            } //EOF while
        } //EOF if (conn!=null)
    } catch (Exception e) {
        //No Database is running, so can not recommend item-item similarity             
    }
    return movieList;
}