List of usage examples for java.util Vector clear
public void clear()
From source file:edu.ku.brc.specify.datamodel.busrules.CollectionObjectBusRules.java
/** * @param catNumPair//from ww w . ja v a2s. co m * @param validate * @param invalidStart * @param nums * @return */ private STATUS processBatchContents(Pair<String, String> catNumPair, boolean validate, boolean invalidStart, Vector<String> nums) { DBFieldInfo CatNumFld = DBTableIdMgr.getInstance().getInfoById(CollectionObject.getClassTableId()) .getFieldByColumnName("CatalogNumber"); final UIFieldFormatterIFace formatter = CatNumFld.getFormatter(); if (!formatter.isIncrementer()) { //XXX this will have been checked earlier, right? //UIRegistry.showLocalizedError(NonIncrementingCatNum); return STATUS.Error; } Vector<String> duplicates = new Vector<String>(); String catNum = catNumPair.getFirst(); if (invalidStart) { duplicates.add(formatter.formatToUI(catNum) + " - " + getResourceString(CatNumInUse)); } Integer collId = AppContextMgr.getInstance().getClassObject(Collection.class).getId(); String coIdSql = "select CollectionObjectID from collectionobject where CollectionMemberID = " + collId + " and CatalogNumber = '"; //XXX comparing catnums ... while (!catNum.equals(catNumPair.getSecond()) && nums.size() <= MAXSERIESSIZE) { catNum = formatter.getNextNumber(catNum, true); //catNum = (String )formatter.formatFromUI(String.valueOf(Integer.valueOf(catNum).intValue() + 1)); if (!validate || BasicSQLUtils.querySingleObj(coIdSql + catNum + "'") == null) { nums.add(catNum); } else { duplicates.add(formatter.formatToUI(catNum) + " - " + getResourceString(CatNumInUse)); } } if (nums.size() > MAXSERIESSIZE || duplicates.size() > 0) { if (nums.size() > MAXSERIESSIZE) { duplicates.clear(); //it may contain irrelevant cat nums } if (duplicates.size() == 0) { UIRegistry.displayErrorDlgLocalized(InvalidEntryMsg, MAXSERIESSIZE); } else { showBatchErrorObjects(duplicates, InvalidEntryTitle, InvalidBatchItems); } return STATUS.Error; } return STATUS.OK; }
From source file:imapi.OnlineDatabaseActions.java
int getUriPairs(String query, String startingUriName, String valueName, String valueType, Vector<DataRecord[]> returnVals) { InputStream answerStream = performDatabaseQuery(query); if (answerStream == null) { return ApiConstants.IMAPIFailCode; }//from ww w .j av a 2 s.com boolean tryToRetrieveLang = false; if (valueType.equals(ApiConstants.Type_Literal)) { tryToRetrieveLang = true; } int ret = readJsonStartingUriAndValuePairs(answerStream, startingUriName, valueName, tryToRetrieveLang, returnVals); if (ret != ApiConstants.IMAPISuccessCode) { returnVals.clear(); return ret; } return ApiConstants.IMAPISuccessCode; }
From source file:edu.ku.brc.specify.tasks.CleanupToolsTask.java
/** * /*from w w w . ja v a 2 s . c o m*/ */ private void updateNames(final Vector<AgentNameCleanupParserDlg.DataItem> dataItemsList) { final String PRC = "PROCESS"; final SimpleGlassPane glassPane = UIRegistry.writeSimpleGlassPaneMsg("Processing agents...", 24); //prgDlg = new ProgressDialog(getResourceString("CLNUP_AG_PRG_TITLE"), true, false); //prgDlg.getProcessProgress().setIndeterminate(true); //prgDlg.setDesc(getResourceString("CLNUP_AG_INIT_MSG")); //UIHelper.centerAndShow(prgDlg); final SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() { double tot = 0; // 1 -> 100 double step = 1.0; int cnt = 0; @Override protected Object doInBackground() throws Exception { step = 100.0 / dataItemsList.size(); Connection conn = null; PreparedStatement pStmt = null; try { String sql = "UPDATE agent SET LastName=?, FirstName=?,MiddleInitial=? WHERE AgentID = ?"; conn = DBConnection.getInstance().createConnection(); pStmt = conn.prepareStatement(sql); for (DataItem di : dataItemsList) { if (di.isIncluded()) { setColumn(pStmt, 1, di.getLastName()); setColumn(pStmt, 2, di.getFirstName()); setColumn(pStmt, 3, di.getMidName()); pStmt.setInt(4, di.getAgentId()); if (pStmt.executeUpdate() != 1) { log.error(String.format("Error updating AgentID %d", di.getAgentId())); } } tot += step; if (((int) tot) > cnt) { cnt = (int) tot; firePropertyChange(PRC, -1, cnt); } } dataItemsList.clear(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (pStmt != null) pStmt.close(); if (conn != null) conn.close(); } catch (SQLException ex) { } } return null; } @Override protected void done() { UIRegistry.clearSimpleGlassPaneMsg(); UIRegistry.showLocalizedMsg("Done."); } }; worker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (PRC.equals(evt.getPropertyName())) { glassPane.setProgress((Integer) evt.getNewValue()); } } }); worker.execute(); }
From source file:playground.meisterk.org.matsim.run.facilities.ShopsOf2005ToFacilities.java
private static void processPickPayOpenTimes(final ActivityFacilitiesImpl facilities) { System.out.println("Setting up Pickpay open times..."); List<String> openTimeLines = null; List<String> addressLines = null; String[] openTokens = null, closeTokens = null; String[] addressTokens = null; Vector<Integer> openNumbers = new Vector<Integer>(); Vector<Integer> closeNumbers = new Vector<Integer>(); TreeMap<String, String> aPickpayOpentime = new TreeMap<String, String>(); String facilityId = null;//w w w . java2 s . co m int addressLinePointer = 1; // ignore header line final String OPEN = "Auf"; final String CLOSE = "Zu"; String openLinePattern = ".*\\s" + OPEN + "\\s.*"; String closeLinePattern = ".*\\s" + CLOSE + "\\s.*"; try { openTimeLines = FileUtils.readLines(new File(pickPayOpenTimesFilename), "UTF-8"); addressLines = FileUtils.readLines(new File(pickPayAdressesFilename), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } // remember relevant lines only String key = null; for (String line : openTimeLines) { if (line.matches(openLinePattern)) { key = line; } else if (line.matches(closeLinePattern)) { if (!aPickpayOpentime.containsKey(key)) { aPickpayOpentime.put(key, line); } } } for (String openLine : aPickpayOpentime.keySet()) { openTokens = openLine.split(ANYTHING_BUT_DIGITS); addressTokens = addressLines.get(addressLinePointer).split(FIELD_DELIM); shopId = new ShopId(PICKPAY, "", addressTokens[1], "", addressTokens[4], addressTokens[5], addressTokens[2]); addressLinePointer++; facilityId = shopId.getShopId(); //System.out.println(facilityId); ActivityFacilityImpl theCurrentPickpay = (ActivityFacilityImpl) facilities.getFacilities() .get(Id.create(facilityId, ActivityFacility.class)); if (theCurrentPickpay != null) { // yeah, we can use the open times ActivityOptionImpl shopping = theCurrentPickpay.createActivityOption(ACTIVITY_TYPE_SHOP); openNumbers.clear(); closeNumbers.clear(); // print out and extract numbers //System.out.print(OPEN + ":\t"); for (String token : openTokens) { if (!token.equals("") && !token.equals(openTokens[0])) { openNumbers.add(Integer.valueOf(token)); //System.out.print(token + "\t"); } } //System.out.println(); closeTokens = aPickpayOpentime.get(openLine).split(ANYTHING_BUT_DIGITS); //System.out.print(CLOSE + ":\t"); for (String token : closeTokens) { if (!token.equals("")) { closeNumbers.add(Integer.valueOf(token)); //System.out.print(token + "\t"); } } //System.out.println(); // now process numbers //String day = "wkday"; Day[] days = Day.values(); int dayPointer = 0; OpeningTimeImpl opentime = null; int openSeconds = 0; int closeSeconds = 0; int previousOpenSeconds = 0; if (openNumbers.size() == closeNumbers.size()) { for (int ii = 0; ii < openNumbers.size(); ii += 2) { openSeconds = openNumbers.get(ii) * 3600 + openNumbers.get(ii + 1) * 60; closeSeconds = closeNumbers.get(ii) * 3600 + closeNumbers.get(ii + 1) * 60; // check if a new day starts if (openSeconds <= previousOpenSeconds) { dayPointer++; } previousOpenSeconds = openSeconds; opentime = new OpeningTimeImpl(days[dayPointer].getAbbrevEnglish(), openSeconds, closeSeconds); shopping.addOpeningTime(opentime); } } else { throw new RuntimeException("openNumbers[] and closeNumbers[] have different size. Aborting..."); } System.out.flush(); } else { System.out.println("A pickpay with id " + facilityId + " does not exist."); } } System.out.println("Setting up Pickpay open times...done."); }
From source file:edu.ku.brc.specify.tasks.subpane.wb.TemplateEditor.java
/** * Adds one or more items from the Schema List to the mapping list. * If a table is selected it adds all unchecked items. *//*from w w w.ja v a 2s .c o m*/ protected void addNewMappingItems() { Object[] objs = fieldList.getSelectedValues(); if (objs != null && objs.length > 0) { Vector<FieldInfo> toAdd = new Vector<FieldInfo>(); for (Object obj : objs) { TableListItemIFace item = (TableListItemIFace) obj; if (!item.isChecked()) { String errMsg = isMappable((FieldInfo) item, null); if (errMsg == null) { toAdd.add((FieldInfo) item); } else { UIRegistry.displayErrorDlg(errMsg); toAdd.clear(); break; } } } for (FieldInfo fld : toAdd) { FieldMappingPanel fmp = addNewMapItem(fld, null); fmp.getArrowLabel().setVisible(true); fmp.getArrowLabel().setIcon(IconManager.getIcon("LinkedRight")); } } }
From source file:edu.ku.brc.ui.UIHelper.java
/** * Helper method for returning data if it is of a particular Class. * Meaning is this data implementing an interface or is it derived from some other class. * @param data the generic data//from w w w . j a va2 s.co m * @param classObj the class in questions * @return the data if it is derived from or implements, can it be cast to */ public static Object getDataForClass(final Object data, Class<?> classObj) { // Short circut if all they are interested in is the generic "Object" if (classObj == Object.class) { return data; } // Check to see if it supports the aggrgation interface if (data instanceof GhostDataAggregatable) { Object newData = ((GhostDataAggregatable) data).getDataForClass(classObj); if (newData != null) { return newData; } } Vector<Class<?>> classes = new Vector<Class<?>>(); // First Check interfaces Class<?>[] theInterfaces = data.getClass().getInterfaces(); for (Class<?> co : theInterfaces) { classes.add(co); } if (classes.contains(classObj)) { return data; } classes.clear(); // Now Check super classes Class<?> superclass = data.getClass().getSuperclass(); while (superclass != null) { classes.addElement(superclass); superclass = superclass.getSuperclass(); } // Wow, it doesn't support anything return null; }
From source file:de.dmarcini.submatix.pclogger.gui.spx42LogGraphPanel.java
/** * Anhand des Alias des Gertes die Tauchgangsliste fllen Project: SubmatixBTForPC Package: de.dmarcini.submatix.pclogger.gui * /*from ww w . ja va 2s . c o m*/ * @author Dirk Marciniak (dirk_marciniak@arcor.de) Stand: 02.07.2012 * @param deviceAlias */ @SuppressWarnings("unchecked") private void fillDiveComboBox(String cDevice) { String device; DateTime dateTime; long javaTime; // device = cDevice; if (device != null) { lg.debug("search dive list for device <" + device + ">..."); releaseGraph(); // Eine Liste der Dives lesen lg.debug("read dive list for device from DB..."); Vector<String[]> entrys = databaseUtil.getDiveListForDeviceLog(device); if (entrys.size() < 1) { lg.info("no dives for device <" + cDevice + "/" + databaseUtil.getAliasForNameConn(device) + "> found in DB."); clearDiveComboBox(); return; } // // Objekt fr das Modell erstellen Vector<String[]> diveEntrys = new Vector<String[]>(); // die erfragten details zurechtrcken // Felder sind: // H_DIVEID, // H_H_DIVENUMBERONSPX // H_STARTTIME, for (Enumeration<String[]> enu = entrys.elements(); enu.hasMoreElements();) { String[] origSet = enu.nextElement(); // zusammenbauen fuer Anzeige String[] elem = new String[3]; // SPX-DiveNumber etwas einrcken, fr vierstellige Anzeige elem[0] = origSet[0]; elem[1] = String.format("%4s", origSet[1]); // Die UTC-Zeit als ASCII/UNIX wieder zu der originalen Zeit fr Java zusammenbauen try { javaTime = Long.parseLong(origSet[2]) * 1000; dateTime = new DateTime(javaTime); elem[2] = dateTime.toString(LangStrings.getString("MainCommGUI.timeFormatterString")); } catch (NumberFormatException ex) { lg.error("Number format exception (value=<" + origSet[1] + ">: <" + ex.getLocalizedMessage() + ">"); elem[1] = "error"; } diveEntrys.add(elem); } // aufrumen entrys.clear(); entrys = null; // die box initialisieren LogListComboBoxModel listBoxModel = new LogListComboBoxModel(diveEntrys); diveSelectComboBox.setModel(listBoxModel); if (diveEntrys.size() > 0) { diveSelectComboBox.setSelectedIndex(0); } } else { lg.debug("no device found...."); } }
From source file:org.apache.axis.wsdl.fromJava.Emitter.java
/** * Create a Message//from www .java 2 s . co m * * @param def Definition, the WSDL definition * @param oper Operation, the wsdl operation * @param desc OperationDesc, the Operation Description * @param bindingOper BindingOperation, corresponding Binding Operation * @throws WSDLException * @throws AxisFault */ protected void writeMessages(Definition def, Operation oper, OperationDesc desc, BindingOperation bindingOper) throws WSDLException, AxisFault { Input input = def.createInput(); Message msg = writeRequestMessage(def, desc, bindingOper); input.setMessage(msg); // Give the input element a name that matches the // message. This is necessary for overloading. // The msg QName is unique. String name = msg.getQName().getLocalPart(); input.setName(name); bindingOper.getBindingInput().setName(name); oper.setInput(input); def.addMessage(msg); if (OperationType.REQUEST_RESPONSE.equals(desc.getMep())) { msg = writeResponseMessage(def, desc, bindingOper); Output output = def.createOutput(); output.setMessage(msg); // Give the output element a name that matches the // message. This is necessary for overloading. // The message QName is unique. name = msg.getQName().getLocalPart(); output.setName(name); bindingOper.getBindingOutput().setName(name); oper.setOutput(output); def.addMessage(msg); } ArrayList exceptions = desc.getFaults(); for (int i = 0; (exceptions != null) && (i < exceptions.size()); i++) { FaultDesc faultDesc = (FaultDesc) exceptions.get(i); msg = writeFaultMessage(def, faultDesc); // Add the fault to the portType Fault fault = def.createFault(); fault.setMessage(msg); fault.setName(faultDesc.getName()); oper.addFault(fault); // Add the fault to the binding BindingFault bFault = def.createBindingFault(); bFault.setName(faultDesc.getName()); SOAPFault soapFault = writeSOAPFault(faultDesc); bFault.addExtensibilityElement(soapFault); bindingOper.addBindingFault(bFault); // Add the fault message if (def.getMessage(msg.getQName()) == null) { def.addMessage(msg); } } // Set the parameter ordering using the parameter names ArrayList parameters = desc.getParameters(); Vector names = new Vector(); for (int i = 0; i < parameters.size(); i++) { ParameterDesc param = (ParameterDesc) parameters.get(i); names.add(param.getName()); } if (names.size() > 0) { if (style == Style.WRAPPED) { names.clear(); } else { oper.setParameterOrdering(names); } } }
From source file:marytts.tools.dbselection.WikipediaMarkupCleaner.java
/*** * Using mwdumper extracts pages from a xmlWikiFile and load them in a mysql DB (it loads the * tables "locale_text", "locale_page" and "locale_revision", where locale is the corresponding * wikipedia language). Once the tables are loaded, extract/clean text from the pages and create * a cleanText table. It also creates a wordList table including frequencies. * @throws Exception//from ww w . ja v a 2s . co m */ void processWikipediaPages() throws Exception { // Load wikipedia pages, extract clean text and create word list. String dateStringIni = "", dateStringEnd = ""; DateFormat fullDate = new SimpleDateFormat("dd_MM_yyyy_HH:mm:ss"); Date dateIni = new Date(); dateStringIni = fullDate.format(dateIni); DBHandler wikiToDB = new DBHandler(locale); // hashMap for the dictionary, HashMap is faster than TreeMap so the list of words will // be kept it in a hashMap. When the process finish the hashMap will be dump in the database. HashMap<String, Integer> wordList; System.out.println("Creating connection to DB server..."); wikiToDB.createDBConnection(mysqlHost, mysqlDB, mysqlUser, mysqlPasswd); // This loading can take a while // create and load TABLES: page, text and revision if (loadWikiTables) { System.out.println( "Creating and loading TABLES: page, text and revision. (The loading can take a while...)"); wikiToDB.loadPagesWithMWDumper(xmlWikiFile, locale, mysqlHost, mysqlDB, mysqlUser, mysqlPasswd); } else { // Checking if tables are already created and loaded in the DB if (wikiToDB.checkWikipediaTables()) System.out.println("TABLES " + locale + "_page, " + locale + "_text and " + locale + "_revision already loaded (WARNING USING EXISTING WIKIPEDIA TABLES)."); else throw new Exception("WikipediaMarkupCleaner: ERROR IN TABLES " + locale + "_page, " + locale + "_text and " + locale + "_revision, they are not CREATED/LOADED."); } System.out.println("\nGetting page IDs"); String pageId[]; pageId = wikiToDB.getIds("page_id", locale + "_page"); System.out.println("Number of page IDs to process: " + pageId.length + "\n"); // create cleanText TABLE if (deleteCleanTextTable) { System.out.println("Creating (deleting if already exist) " + locale + "_cleanText TABLE"); wikiToDB.createWikipediaCleanTextTable(); } else { if (wikiToDB.tableExist(locale + "_cleanText")) System.out.println(locale + "_cleanText TABLE already exist (ADDING TO EXISTING cleanText TABLE)"); else { System.out.println("Creating " + locale + "_cleanText TABLE"); wikiToDB.createWikipediaCleanTextTable(); } } System.out.println("Starting Hashtable for wordList."); int initialCapacity = 200000; wordList = new HashMap<String, Integer>(initialCapacity); String text; PrintWriter pw = null; if (wikiLog != null) pw = new PrintWriter(new FileWriter(new File(wikiLog))); StringBuilder textId = new StringBuilder(); int numPagesUsed = 0; Vector<String> textList; System.out.println("\nStart processing Wikipedia pages.... Start time:" + dateStringIni + "\n"); for (int i = 0; i < pageId.length; i++) { // first filter text = wikiToDB.getTextFromWikiPage(pageId[i], minPageLength, textId, pw); if (text != null) { textList = removeMarkup(text); numPagesUsed++; for (int j = 0; j < textList.size(); j++) { text = textList.get(j); if (text.length() > minTextLength) { // if after cleaning the text is not empty or wikiToDB.insertCleanText(text, pageId[i], textId.toString()); // insert the words in text in wordlist addWordToHashMap(text, wordList); if (debug) System.out.println("Cleanedpage_id[" + i + "]=" + pageId[i] + " textList (" + (j + 1) + "/" + textList.size() + ") length=" + text.length() + " numPagesUsed=" + numPagesUsed + " Wordlist[" + wordList.size() + "] "); if (pw != null) pw.println("CLEANED PAGE page_id[" + i + "]=" + pageId[i] + " textList (" + (j + 1) + "/" + textList.size() + ") length=" + text.length() + " Wordlist[" + wordList.size() + "] " + " NUM_PAGES_USED=" + numPagesUsed + " text:\n\n" + text); } else if (pw != null) pw.println("PAGE NOT USED AFTER CLEANING page_id[" + i + "]=" + pageId[i] + " length=" + text.length()); } // for each text in textList System.out.println("Cleanedpage_id[" + i + "]=" + pageId[i] + " numPagesUsed=" + numPagesUsed + " Wordlist[" + wordList.size() + "] "); textList.clear(); // clear the list of text } } Date dateEnd = new Date(); dateStringEnd = fullDate.format(dateEnd); if (pw != null) { pw.println("Number of PAGES USED=" + numPagesUsed + " Wordlist[" + wordList.size() + "] " + " minPageLength=" + minPageLength + " minTextLength=" + minTextLength + " Start time:" + dateStringIni + " End time:" + dateStringEnd); pw.close(); } // save the wordList in the DB updateWordList(wikiToDB, wordList); wikiToDB.printWordList("./wordlist-freq.txt", "frequency", 0, 0); System.out.println("\nNumber of pages used=" + numPagesUsed + " Wordlist[" + wordList.size() + "] " + " Start time:" + dateStringIni + " End time:" + dateStringEnd); // Once created the cleantext table delete the wikipedia text, page and revision tables. wikiToDB.deleteWikipediaTables(); wikiToDB.closeDBConnection(); }
From source file:org.commoncrawl.service.pagerank.slave.PageRankUtils.java
private static FileSystem buildDistributionOutputStreamVector(boolean useSequenceFile, String fileNamePrefix, File localOutputPath, String remoteOutputPath, int myNodeIndex, int nodeCount, Vector<PRValueOutputStream> outputStreamVector) { Configuration conf = new Configuration(CrawlEnvironment.getHadoopConfig()); conf.setInt("dfs.socket.timeout", 240000); conf.setInt("io.file.buffer.size", 4096 * 20); DistributedFileSystem hdfs = new DistributedFileSystem(); try {/* w w w. j a va 2 s .c o m*/ hdfs.initialize(FileSystem.getDefaultUri(conf), conf); for (int i = 0; i < nodeCount; ++i) { // create output filename String fileName = fileNamePrefix + "-" + NUMBER_FORMAT.format(i); // create stream (local or remote stream, depending on i) // remote path Path remotePath = new Path(remoteOutputPath, fileName); // remove file CrawlEnvironment.getDefaultFileSystem().delete(remotePath, false); if (useSequenceFile) { // recreate it ... outputStreamVector.add(new PRSequenceFileOutputStream(conf, CrawlEnvironment.getDefaultFileSystem(), remotePath)); } else { // recreate it ... outputStreamVector .add(new PROldValueOutputStream(CrawlEnvironment.getDefaultFileSystem(), remotePath)); } } } catch (IOException e) { LOG.error(CCStringUtils.stringifyException(e)); for (PRValueOutputStream streamInfo : outputStreamVector) { try { if (streamInfo != null) { streamInfo.close(true); } } catch (IOException e2) { LOG.error(CCStringUtils.stringifyException(e2)); } outputStreamVector.clear(); } } return hdfs; }