List of usage examples for java.util StringTokenizer hasMoreElements
public boolean hasMoreElements()
From source file:gtu._work.ui.ObnfInsertCreaterUI.java
private void manualDefineDbFieldBtnAction() { String manualDefineText = manualDefineArea.getText(); String manualDefinePkText = StringUtils.defaultString(manualDefinePkArea.getText()); if (StringUtils.isBlank(manualDefineText)) { JCommonUtil._jOptionPane_showMessageDialog_error("?"); return;//from w ww. j a v a 2 s. co m } Set<String> useList = new HashSet<String>(); StringTokenizer tok = new StringTokenizer(manualDefineText); while (tok.hasMoreElements()) { String f = (String) tok.nextElement(); useList.add(f); } Set<String> pkList = new HashSet<String>(); StringTokenizer tok2 = new StringTokenizer(manualDefinePkText); while (tok2.hasMoreElements()) { String f = (String) tok2.nextElement(); pkList.add(f); } Map<String, String> pkMap = new HashMap<String, String>(); Map<String, String> columnMap = new HashMap<String, String>(); DefaultListModel dbFieldListModel = (DefaultListModel) dbFieldList.getModel(); if (dbFieldListModel.isEmpty()) { JCommonUtil._jOptionPane_showMessageDialog_error("\"?ObnfString\""); return; } for (Enumeration<?> enu = dbFieldListModel.elements(); enu.hasMoreElements();) { KeyValue kv = (KeyValue) enu.nextElement(); if (!pkList.isEmpty() && pkList.contains(kv.getKey())) { pkMap.put(kv.getKey(), kv.value); } else if (pkList.isEmpty() && kv.pk) { pkMap.put(kv.getKey(), kv.value); } else { columnMap.put(kv.getKey(), kv.value); } } StringBuffer sb = new StringBuffer(); sb.append("COLUMN=>\n"); this.keepKey(columnMap, useList, sb); JCommonUtil._jOptionPane_showMessageDialog_info(sb); this.putToDbFieldList(pkMap, columnMap); }
From source file:org.ofbiz.core.entity.MemoryHelper.java
public List<GenericValue> findByAnd(ModelEntity modelEntity, Map<String, ?> fields, List<String> orderBy) throws GenericEntityException { Map<GenericEntity, GenericValue> entityCache = cache.get(modelEntity.getEntityName()); if (entityCache == null) { return Collections.emptyList(); }//from w ww. j a v a2 s . c o m ArrayList<GenericValue> result = new ArrayList<GenericValue>(); // according to the javadocs for Collections.synchronizedMap() we need to // synchronize when iterating over the elements of the collection synchronized (entityCache) { for (Map.Entry<GenericEntity, GenericValue> mapEntry : entityCache.entrySet()) { GenericValue value = mapEntry.getValue(); if (isAndMatch(value.fields, fields)) { result.add(value); } } } ComparatorChain comp = new ComparatorChain(); if (orderBy != null) { for (String fieldAndOrder : orderBy) { StringTokenizer stringTokenizer = new StringTokenizer(fieldAndOrder); String field = null; String order = null; if (stringTokenizer.hasMoreElements()) field = stringTokenizer.nextToken(); if (stringTokenizer.hasMoreElements()) order = stringTokenizer.nextToken(); if (field != null) { if (order == null || "ASC".equalsIgnoreCase(order)) comp.addComparator(new OFBizFieldComparator(field)); else comp.addComparator(new ReverseComparator(new OFBizFieldComparator(field))); } } Collections.sort(result, comp); } return result; }
From source file:org.hfoss.posit.android.sync.Communicator.java
/** * /* w w w.j av a 2 s . c o m*/ * Retrieve finds from the server using a Communicator. * * @param serverGuids * @return */ public static boolean getFindsFromServer(Context context, String authKey, String serverGuids) { String guid; int rows = 0; StringTokenizer st = new StringTokenizer(serverGuids, ","); while (st.hasMoreElements()) { guid = st.nextElement().toString(); ContentValues cv = getRemoteFindById(context, authKey, guid); if (cv == null) { return false; // Shouldn't be null--we know its ID } else { Log.i(TAG, cv.toString()); try { // Find out what Find class POSIT is configured for Class<? extends Find> findClass = FindPluginManager.mFindPlugin.getmFindClass(); Log.i(TAG, "Find class = " + findClass.getSimpleName()); // Update the DB Find find = DbHelper.getDbManager(context).getFindByGuid(guid); if (find != null) { Log.i(TAG, "Updating existing find: " + find.getId()); Find updatedFind = findClass.newInstance(); updatedFind.updateObject(cv); // Find updatedFind = (OutsideInFind)find; // ((OutsideInFind) updatedFind).updateObject(cv); updatedFind.setId(find.getId()); rows = DbHelper.getDbManager(context).updateWithoutHistory(updatedFind); } else { // find = new OutsideInFind(); find = findClass.newInstance(); Log.i(TAG, "Inserting new find: " + find.getId()); find.updateObject(cv); // ((OutsideInFind) find).updateObject(cv); Log.i(TAG, "Adding a new find " + find); rows = DbHelper.getDbManager(context).insertWithoutHistory(find); } } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } DbHelper.releaseDbManager(); return rows > 0; }
From source file:org.apache.axis.components.compiler.Javac.java
/** * Parse an individual compiler error message with classic style. * * @param error The error text//w w w . j a v a2 s .c om * @return A messaged <code>CompilerError</code> */ private CompilerError parseClassicError(String error) { StringTokenizer tokens = new StringTokenizer(error, ":"); try { String file = tokens.nextToken(); if (file.length() == 1) { file = new StringBuffer(file).append(":").append(tokens.nextToken()).toString(); } int line = Integer.parseInt(tokens.nextToken()); String last = tokens.nextToken(); // In case the message contains ':', it should be reassembled while (tokens.hasMoreElements()) { last += tokens.nextToken(); } tokens = new StringTokenizer(last.trim(), "\n"); String message = tokens.nextToken(); String context = tokens.nextToken(); String pointer = tokens.nextToken(); int startcolumn = pointer.indexOf("^"); int endcolumn = context.indexOf(" ", startcolumn); if (endcolumn == -1) endcolumn = context.length(); return new CompilerError(srcDir + File.separator + file, true, line, startcolumn, line, endcolumn, message); } catch (NoSuchElementException nse) { return new CompilerError(Messages.getMessage("noMoreTokens", error)); } catch (Exception nse) { return new CompilerError(Messages.getMessage("cantParse", error)); } }
From source file:org.apache.jasper.compiler.Compiler.java
/** * Compile the servlet from .java file to .class file *///w w w . j a v a 2 s.c om private void generateClass(String smap) throws FileNotFoundException, JasperException, Exception { long t1 = System.currentTimeMillis(); String javaEncoding = ctxt.getOptions().getJavaEncoding(); String javaFileName = ctxt.getServletJavaFileName(); String classpath = ctxt.getClassPath(); String sep = System.getProperty("path.separator"); StringBuffer errorReport = new StringBuffer(); boolean success = true; StringBuffer info = new StringBuffer(); info.append("Compile: javaFileName=" + javaFileName + "\n"); info.append(" classpath=" + classpath + "\n"); // Start capturing the System.err output for this thread SystemLogHandler.setThread(); // Initializing javac task getProject(); Javac javac = (Javac) project.createTask("javac"); // Initializing classpath Path path = new Path(project); path.setPath(System.getProperty("java.class.path")); info.append(" cp=" + System.getProperty("java.class.path") + "\n"); StringTokenizer tokenizer = new StringTokenizer(classpath, sep); while (tokenizer.hasMoreElements()) { String pathElement = tokenizer.nextToken(); File repository = new File(pathElement); path.setLocation(repository); info.append(" cp=" + repository + "\n"); } if (log.isDebugEnabled()) log.debug("Using classpath: " + System.getProperty("java.class.path") + sep + classpath); // Initializing sourcepath Path srcPath = new Path(project); srcPath.setLocation(options.getScratchDir()); info.append(" work dir=" + options.getScratchDir() + "\n"); // Initialize and set java extensions String exts = System.getProperty("java.ext.dirs"); if (exts != null) { Path extdirs = new Path(project); extdirs.setPath(exts); javac.setExtdirs(extdirs); info.append(" extension dir=" + exts + "\n"); } // Configure the compiler object javac.setEncoding(javaEncoding); javac.setClasspath(path); javac.setDebug(ctxt.getOptions().getClassDebugInfo()); javac.setSrcdir(srcPath); javac.setOptimize(!ctxt.getOptions().getClassDebugInfo()); javac.setFork(ctxt.getOptions().getFork()); info.append(" srcDir=" + srcPath + "\n"); // Set the Java compiler to use if (options.getCompiler() != null) { javac.setCompiler(options.getCompiler()); info.append(" compiler=" + options.getCompiler() + "\n"); } // Build includes path PatternSet.NameEntry includes = javac.createInclude(); includes.setName(ctxt.getJavaPath()); info.append(" include=" + ctxt.getJavaPath() + "\n"); try { if (ctxt.getOptions().getFork()) { javac.execute(); } else { synchronized (javacLock) { javac.execute(); } } } catch (BuildException e) { log.error("Javac exception ", e); log.error("Env: " + info.toString()); success = false; } errorReport.append(logger.getReport()); // Stop capturing the System.err output for this thread String errorCapture = SystemLogHandler.unsetThread(); if (errorCapture != null) { errorReport.append(System.getProperty("line.separator")); errorReport.append(errorCapture); } if (!ctxt.keepGenerated()) { File javaFile = new File(javaFileName); javaFile.delete(); } if (!success) { log.error("Error compiling file: " + javaFileName + " " + errorReport); errDispatcher.javacError(errorReport.toString(), javaFileName, pageNodes); } long t2 = System.currentTimeMillis(); if (t2 - t1 > 500) { log.debug("Compiled " + javaFileName + " " + (t2 - t1)); } if (ctxt.isPrototypeMode()) { return; } // JSR45 Support if (!options.isSmapSuppressed()) { SmapUtil.installSmap(ctxt.getClassFileName(), smap); } }
From source file:edu.duke.cabig.c3pr.web.ajax.BookRandomizationAjaxFacade.java
private void parseBookRandomization(String bookRandomizations, Epoch tEpoch) throws Exception { try {//from w w w .j av a 2 s . com // we do not create a new instance of bookRandomization, we use the existing instance // which was created in StudyDesignTab.java // based on the randomizationType selected on the study_details page. BookRandomization randomization = null; if (tEpoch.getRandomization() instanceof BookRandomization) { randomization = (BookRandomization) tEpoch.getRandomization(); } else { return; } List<BookRandomizationEntry> breList = randomization.getBookRandomizationEntry(); //clear existing bookEntries breList.clear(); clearStratumGroups(tEpoch); StringTokenizer outer = new StringTokenizer(bookRandomizations, "\n"); String entry; String[] entries; Arm arm; StratumGroup sGroup; BookRandomizationEntry bookRandomizationEntry = null; while (outer.hasMoreElements()) { entry = outer.nextToken(); if (entry.trim().length() > 0) { entries = entry.split(","); bookRandomizationEntry = breList.get(breList.size()); // find the stratum group with this id and set it here even if its null sGroup = getStratumGroupByNumber(tEpoch, entries[0].trim()); bookRandomizationEntry.setStratumGroup(sGroup); sGroup.getBookRandomizationEntry().add(bookRandomizationEntry); // set the position Integer position = null; try { position = Integer.valueOf(entries[1].trim()); } catch (NumberFormatException nfe) { log.debug("Illegal Position Entered."); } bookRandomizationEntry.setPosition(position); // find the arm with this id and set it here even if its null // Empty stratum groups with negetive stratum Group Numbers and arms are checked // for while generating the table and replaced with the string // "Invalid Entry" so the user can see which entries are incorrect. arm = getArmByName(tEpoch, entries[2].trim()); bookRandomizationEntry.setArm(arm); } } } catch (Exception e) { log.error("parseBookRandomizatrion Failed"); log.error(e.getMessage()); throw e; } }
From source file:com.serena.rlc.provider.tfs.TFSBaseServiceProvider.java
@Getter(name = QUEUE_TYPE, displayName = "Queue Type", description = "Get Build Queue Type.") public FieldInfo getQueueTypeFieldValues(String fieldName, List<Field> properties) throws ProviderException { //TODO: queueTypes in provider configuration String queueTypes = "buildController,agentPool"; if (StringUtils.isEmpty(queueTypes)) { return null; }/*from w w w . j a va 2 s . co m*/ StringTokenizer st = new StringTokenizer(queueTypes, ",;"); FieldInfo fieldInfo = new FieldInfo(fieldName); List<FieldValueInfo> values = new ArrayList<>(); FieldValueInfo value; String qType; while (st.hasMoreElements()) { qType = (String) st.nextElement(); qType = qType.trim(); value = new FieldValueInfo(qType, qType); values.add(value); } fieldInfo.setValues(values); return fieldInfo; }
From source file:net.semanticmetadata.lire.solr.LireRequestHandler.java
/** * Actual search implementation based on (i) hash based retrieval and (ii) feature based re-ranking. * * @param rsp//from w w w . j a va2 s . co m * @param searcher * @param hashFieldName the hash field name * @param maximumHits * @param terms * @param queryFeature * @throws IOException * @throws IllegalAccessException * @throws InstantiationException */ private void doSearch(SolrQueryRequest req, SolrQueryResponse rsp, SolrIndexSearcher searcher, String hashFieldName, int maximumHits, List<Term> terms, Query query, LireFeature queryFeature) throws IOException, IllegalAccessException, InstantiationException { // temp feature instance LireFeature tmpFeature = queryFeature.getClass().newInstance(); // Taking the time of search for statistical purposes. time = System.currentTimeMillis(); Filter filter = null; // if the request contains a filter: if (req.getParams().get("fq") != null) { // only filters with [<field>:<value> ]+ are supported StringTokenizer st = new StringTokenizer(req.getParams().get("fq"), " "); LinkedList<Term> filterTerms = new LinkedList<Term>(); while (st.hasMoreElements()) { String[] tmpToken = st.nextToken().split(":"); if (tmpToken.length > 1) { filterTerms.add(new Term(tmpToken[0], tmpToken[1])); } } if (filterTerms.size() > 0) filter = new TermsFilter(filterTerms); } TopDocs docs; // with query only. if (filter == null) { docs = searcher.search(query, numberOfCandidateResults); } else { docs = searcher.search(query, filter, numberOfCandidateResults); } // TopDocs docs = searcher.search(query, new TermsFilter(terms), numberOfCandidateResults); // with TermsFilter and boosting by simple query // TopDocs docs = searcher.search(new ConstantScoreQuery(new TermsFilter(terms)), numberOfCandidateResults); // just with TermsFilter time = System.currentTimeMillis() - time; rsp.add("RawDocsCount", docs.scoreDocs.length + ""); rsp.add("RawDocsSearchTime", time + ""); // re-rank time = System.currentTimeMillis(); TreeSet<SimpleResult> resultScoreDocs = new TreeSet<SimpleResult>(); float maxDistance = -1f; float tmpScore; String featureFieldName = FeatureRegistry.getFeatureFieldName(hashFieldName); // iterating and re-ranking the documents. BinaryDocValues binaryValues = MultiDocValues.getBinaryValues(searcher.getIndexReader(), featureFieldName); // *** # BytesRef bytesRef;// = new BytesRef(); for (int i = 0; i < docs.scoreDocs.length; i++) { // using DocValues to retrieve the field values ... bytesRef = binaryValues.get(docs.scoreDocs[i].doc); tmpFeature.setByteArrayRepresentation(bytesRef.bytes, bytesRef.offset, bytesRef.length); // Getting the document from the index. // This is the slow step based on the field compression of stored fields. // tmpFeature.setByteArrayRepresentation(d.getBinaryValue(name).bytes, d.getBinaryValue(name).offset, d.getBinaryValue(name).length); tmpScore = queryFeature.getDistance(tmpFeature); if (resultScoreDocs.size() < maximumHits) { // todo: There's potential here for a memory saver, think of a clever data structure that can do the trick without creating a new SimpleResult for each result. resultScoreDocs.add( new SimpleResult(tmpScore, searcher.doc(docs.scoreDocs[i].doc), docs.scoreDocs[i].doc)); maxDistance = resultScoreDocs.last().getDistance(); } else if (tmpScore < maxDistance) { // if it is nearer to the sample than at least one of the current set: // remove the last one ... resultScoreDocs.remove(resultScoreDocs.last()); // add the new one ... resultScoreDocs.add( new SimpleResult(tmpScore, searcher.doc(docs.scoreDocs[i].doc), docs.scoreDocs[i].doc)); // and set our new distance border ... maxDistance = resultScoreDocs.last().getDistance(); } } // System.out.println("** Creating response."); time = System.currentTimeMillis() - time; rsp.add("ReRankSearchTime", time + ""); LinkedList list = new LinkedList(); for (Iterator<SimpleResult> it = resultScoreDocs.iterator(); it.hasNext();) { SimpleResult result = it.next(); HashMap m = new HashMap(2); m.put("d", result.getDistance()); // add fields as requested: if (req.getParams().get("fl") == null) { m.put("id", result.getDocument().get("id")); if (result.getDocument().get("title") != null) m.put("title", result.getDocument().get("title")); } else { String fieldsRequested = req.getParams().get("fl"); if (fieldsRequested.contains("score")) { m.put("score", result.getDistance()); } if (fieldsRequested.contains("*")) { // all fields for (IndexableField field : result.getDocument().getFields()) { String tmpField = field.name(); if (result.getDocument().getFields(tmpField).length > 1) { m.put(result.getDocument().getFields(tmpField)[0].name(), result.getDocument().getValues(tmpField)); } else if (result.getDocument().getFields(tmpField).length > 0) { m.put(result.getDocument().getFields(tmpField)[0].name(), result.getDocument().getFields(tmpField)[0].stringValue()); } } } else { StringTokenizer st; if (fieldsRequested.contains(",")) st = new StringTokenizer(fieldsRequested, ","); else st = new StringTokenizer(fieldsRequested, " "); while (st.hasMoreElements()) { String tmpField = st.nextToken(); if (result.getDocument().getFields(tmpField).length > 1) { m.put(result.getDocument().getFields(tmpField)[0].name(), result.getDocument().getValues(tmpField)); } else if (result.getDocument().getFields(tmpField).length > 0) { m.put(result.getDocument().getFields(tmpField)[0].name(), result.getDocument().getFields(tmpField)[0].stringValue()); } } } } // m.put(field, result.getDocument().get(field)); // m.put(field.replace("_ha", "_hi"), result.getDocument().getBinaryValue(field)); list.add(m); } rsp.add("docs", list); // rsp.add("Test-name", "Test-val"); }
From source file:ch.epfl.lsir.xin.algorithm.core.MatrixFactorization.java
@Override public void readModel(String file) { // TODO Auto-generated method stub try {//from w ww.j a va 2 s .com //read user latent factors BufferedReader reader1 = new BufferedReader(new FileReader(file + "_user")); String line = null; int u1 = 0; while ((line = reader1.readLine()) != null) { StringTokenizer tokens = new StringTokenizer(line.trim()); int u2 = 0; while (tokens.hasMoreElements()) { this.userMatrix.set(u1, u2, Double.parseDouble(tokens.nextToken())); u2++; } u1++; } reader1.close(); //read item latent factors BufferedReader reader2 = new BufferedReader(new FileReader(file + "_item")); String line2 = null; int i1 = 0; while ((line2 = reader2.readLine()) != null) { StringTokenizer tokens = new StringTokenizer(line2.trim()); int i2 = 0; while (tokens.hasMoreElements()) { this.itemMatrix.set(i1, i2, Double.parseDouble(tokens.nextToken())); i2++; } i1++; } reader2.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.alfresco.po.share.GroupsPage.java
/** * Get list of group members for any group in groups page * /*from ww w.j av a 2 s.co m*/ * @return List of Users */ public List<UserProfile> getMembersList() { try { List<UserProfile> listOfUsers = new ArrayList<UserProfile>(); List<WebElement> groupMembers = findAndWaitForElements(By.cssSelector(USER_NAMES)); for (WebElement webElement : groupMembers) { UserProfile profile = new UserProfile(); String text = webElement.getText(); StringTokenizer userInfo = new StringTokenizer(text); int userDispalySize = 0; int userInfoSize = userInfo.countTokens(); while (userInfo.hasMoreElements()) { if (userDispalySize == 0) { profile.setfName((String) userInfo.nextElement()); } else if (userDispalySize == 1 && userInfoSize > 2) { profile.setlName((String) userInfo.nextElement()); } else if (userDispalySize == 2 || (userDispalySize == 1 && userInfoSize == 2)) { profile.setUsername((String) userInfo.nextElement()); } userDispalySize++; } listOfUsers.add(profile); } return listOfUsers; } catch (TimeoutException e) { logger.error("Unable to get the list of members : ", e); } throw new PageOperationException("Unable to get the list of members : "); }