List of usage examples for java.util Vector get
public synchronized E get(int index)
From source file:de.mpg.escidoc.pubman.sword.SwordUtil.java
public SWORDEntry createResponseAtom(PubItemVO item, Deposit deposit, boolean valid) { SWORDEntry se = new SWORDEntry(); PubManSwordServer server = new PubManSwordServer(); //This info can only be filled if item was successfully created if (item != null) { Title title = new Title(); title.setContent(item.getMetadata().getTitle().getValue()); se.setTitle(title);//w w w . j ava 2 s .c o m SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); TimeZone utc = TimeZone.getTimeZone("UTC"); sdf.setTimeZone(utc); String milliFormat = sdf.format(new Date()); se.setUpdated(milliFormat); } Summary s = new Summary(); Vector<String> filenames = this.getFileNames(); String filename = ""; for (int i = 0; i < filenames.size(); i++) { if (filename.equals("")) { filename = filenames.get(i); } else { filename = filename + " ," + filenames.get(i); } } s.setContent(filename); se.setSummary(s); Content content = new Content(); content.setSource(""); //Only set content if item was deposited if (!deposit.isNoOp() && item != null && valid) { content.setSource(server.getCoreserviceURL() + "/ir/item/" + item.getVersion().getObjectId()); se.setId(server.getBaseURL() + this.itemPath + item.getVersion().getObjectId()); } se.setContent(content); Source source = new Source(); Generator generator = new Generator(); generator.setContent(server.getBaseURL()); source.setGenerator(generator); se.setSource(source); se.setTreatment(this.treatmentText); se.setNoOp(deposit.isNoOp()); //Add the login name Author author = new Author(); author.setName(deposit.getUsername()); se.addAuthors(author); return se; }
From source file:org.powertac.officecomplexcustomer.customers.Office.java
private void createDominantOperationVectors() { Appliance app = appliances.get(dominantAppliance); Vector<Boolean> op = app.getOperationDaysVector(); for (int i = 0; i < op.size(); i++) { if (op.get(i)) daysDominant++;//from w ww .j av a 2 s. c om else daysNonDominant++; for (int j = 0; j < OfficeComplexConstants.HOURS_OF_DAY; j++) { if (op.get(i)) dominantConsumption[j] += weeklyBaseLoadInHours.get(i).get(j) + weeklyControllableLoadInHours.get(i).get(j) + weeklyWeatherSensitiveLoadInHours.get(i).get(j); else nonDominantConsumption[j] += weeklyBaseLoadInHours.get(i).get(j) + weeklyControllableLoadInHours.get(i).get(j) + weeklyWeatherSensitiveLoadInHours.get(i).get(j); } } for (int j = 0; j < OfficeComplexConstants.HOURS_OF_DAY; j++) { if (daysDominant != 0) dominantConsumption[j] /= daysDominant; if (daysNonDominant != 0) nonDominantConsumption[j] /= daysNonDominant; } /* System.out.println("Household:" + toString()); System.out.println("Dominant Consumption:" + Arrays.toString(dominantConsumption)); System.out.println("Non Dominant Consumption:" + Arrays.toString(nonDominantConsumption)); */ }
From source file:eionet.gdem.qa.XQueryService.java
/** * *//* w w w.j a v a 2 s . co m*/ public Vector analyzeXMLFiles(String schema, String origFile, Vector result) throws GDEMException { LOGGER.info("XML/RPC call for analyze xml: " + origFile); if (result == null) { result = new Vector(); } Vector outputTypes = null; // get all possible xqueries from db String newId = "-1"; // should not be returned with value -1; String file = origFile; Vector queries = listQueries(schema); try { outputTypes = convTypeDao.getConvTypes(); } catch (SQLException sqe) { throw new GDEMException("DB operation failed: " + sqe.toString()); } try { // get the trusted URL from source file adapter file = SourceFileManager.getSourceFileAdapterURL(getTicket(), file, isTrustedMode()); } catch (Exception e) { String err_mess = "File URL is incorrect"; LOGGER.error(err_mess + "; " + e.toString()); throw new GDEMException(err_mess, e); } if (!Utils.isNullVector(queries)) { for (int j = 0; j < queries.size(); j++) { Hashtable query = (Hashtable) queries.get(j); String query_id = String.valueOf(query.get("query_id")); String queryFile = (String) query.get("query"); String contentType = (String) query.get("content_type_id"); String fileExtension = getExtension(outputTypes, contentType); String resultFile = Properties.tmpFolder + File.separatorChar + "gdem_q" + query_id + "_" + System.currentTimeMillis() + "." + fileExtension; try { int queryId = 0; try { queryId = Integer.parseInt(query_id); } catch (NumberFormatException n) { queryId = 0; } // if it is a XQuery script, then append the system folder if (queryId != Constants.JOB_VALIDATION && queryFile.startsWith(Properties.gdemURL + "/" + Constants.QUERIES_FOLDER)) { queryFile = Utils.Replace(queryFile, Properties.gdemURL + "/" + Constants.QUERIES_FOLDER, Properties.queriesFolder + File.separator); } newId = xqJobDao.startXQJob(file, queryFile, resultFile, queryId); } catch (SQLException sqe) { throw new GDEMException("DB operation failed: " + sqe.toString()); } Vector queryResult = new Vector(); queryResult.add(newId); queryResult.add(origFile); result.add(queryResult); } } LOGGER.info("Analyze xml result: " + result.toString()); return result; }
From source file:net.java.sip.communicator.impl.history.HistoryReaderImpl.java
/** * Returns the supplied number of recent messages after the given date * * @param date messages after date//from w w w. j av a 2 s.c o m * @param count messages count * @return QueryResultSet the found records * @throws RuntimeException */ public QueryResultSet<HistoryRecord> findFirstRecordsAfter(Date date, int count) throws RuntimeException { TreeSet<HistoryRecord> result = new TreeSet<HistoryRecord>(new HistoryRecordComparator()); Vector<String> filelist = filterFilesByDate(this.historyImpl.getFileList(), date, null); int leftCount = count; int currentFile = 0; SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); while (leftCount > 0 && currentFile < filelist.size()) { Document doc = this.historyImpl.getDocumentForFile(filelist.get(currentFile)); if (doc == null) { currentFile++; continue; } NodeList nodes = doc.getElementsByTagName("record"); Node node; for (int i = 0; i < nodes.getLength() && leftCount > 0; i++) { node = nodes.item(i); NodeList propertyNodes = node.getChildNodes(); Date timestamp; String ts = node.getAttributes().getNamedItem("timestamp").getNodeValue(); try { timestamp = sdf.parse(ts); } catch (ParseException e) { timestamp = new Date(Long.parseLong(ts)); } if (!isInPeriod(timestamp, date, null)) continue; ArrayList<String> nameVals = new ArrayList<String>(); boolean isRecordOK = true; int len = propertyNodes.getLength(); for (int j = 0; j < len; j++) { Node propertyNode = propertyNodes.item(j); if (propertyNode.getNodeType() == Node.ELEMENT_NODE) { // Get nested TEXT node's value Node nodeValue = propertyNode.getFirstChild(); if (nodeValue != null) { nameVals.add(propertyNode.getNodeName()); nameVals.add(nodeValue.getNodeValue()); } else isRecordOK = false; } } // if we found a broken record - just skip it if (!isRecordOK) continue; String[] propertyNames = new String[nameVals.size() / 2]; String[] propertyValues = new String[propertyNames.length]; for (int j = 0; j < propertyNames.length; j++) { propertyNames[j] = nameVals.get(j * 2); propertyValues[j] = nameVals.get(j * 2 + 1); } HistoryRecord record = new HistoryRecord(propertyNames, propertyValues, timestamp); result.add(record); leftCount--; } currentFile++; } return new OrderedQueryResultSet<HistoryRecord>(result); }
From source file:cl.utfsm.cdbChecker.CDBChecker.java
/** * This method checks for the targetNamespace defined by the schema files and fills the CDBChecker.xsd_targetns with pairs {targetNamespace, XSD filename} * /* w w w . ja v a 2 s . c om*/ * @param xsdFilenames Vector with all the XSD filenames with absolute path. */ protected void getTargetNamespace(Vector<String> xsdFilenames) { String filename; for (int i = 0; i < xsdFilenames.size(); i++) { filename = xsdFilenames.get(i); File file = new File(xsdFilenames.get(i)); if (file.length() != 0) { SP.setContentHandler(new CDBContentHandler(this)); SP.reset(); try { SP.setFeature("http://xml.org/sax/features/validation", false); SP.setFeature("http://apache.org/xml/features/validation/schema", false); SP.setFeature("http://xml.org/sax/features/namespace-prefixes", false); SP.setFeature("http://xml.org/sax/features/namespaces", true); SP.setErrorHandler(new CDBErrorHandler(this)); FileInputStream fis = new FileInputStream(file); InputSource inputSource = new InputSource(fis); inputSource.setSystemId("file:///" + file.getAbsolutePath()); SP.parse(inputSource); fis.close(); } catch (SAXException e) { e.getMessage(); } catch (IOException e) { System.out.println("[IOException] Probably " + filename + " doesn't exists."); } if (targetNamespace != null) { /* GCH * If the targetNamespace has been already registered, * I skip registering it again. * In this way I give priority to definitions that come first. * Since the search order depends on the order int the ACS.cdbPath * property, standard definitions can be overwritten byte newer ones in * the standard search path algorithm. */ if (xsd_targetns.containsKey(targetNamespace)) { /* * If the same targetNamespace appears int files with * the same name, then we are simply overriding the * default version with a new one and we need to warning. * Otherwise, a warning can be useful to discover * inconsistencies. */ String[] newArr = filename.split("/"); String[] oldArr = ((String) xsd_targetns.get(targetNamespace)).split("/"); if (newArr[newArr.length - 1].compareTo(oldArr[oldArr.length - 1]) != 0) { System.out.println("[Warning] The XSD files \"" + xsdFilenames.get(i) + "\" and \"" + xsd_targetns.get(targetNamespace) + "\" have same targetNamespace: \"" + targetNamespace + "\". Skipping this one."); } } else { xsd_targetns.put(targetNamespace, "file:///" + xsdFilenames.get(i)); } } } else { System.out.print(xsdFilenames.get(i) + ": [Warning] file is empty.\n"); } } }
From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.control.MonitorServ.java
/** Start a thread that continually checks for new metrics updates and sends them to * the server admin screen. This thread is needed so that calls to the UI, which are * slow remote calls, do not prolong transaction timing so that transactions can * release market locks ASAP. The dispatcher can add updates to the metricsUpdates * queue *///from w w w . j av a 2 s . co m private void startMetricsUpdateThread() { metricsUpdates = new Vector(); Runnable updater = new Runnable() { public void run() { try { while (!metricsUpdateDone) { MetricsUpdate update = getNextUpdate(); if (update.sessionId == -1) { log.debug("Shutting down auxiliary metrics update thread"); break; } Vector monitors = getMonitors(update.sessionId); if (monitors == null) { log.warn("Cannot update MonitorTransmitters with metrics information for session " + update.sessionId + " -- that session does not exist!"); continue; } for (int i = 0; i < monitors.size(); i++) { MonitorTransmitter ui = (MonitorTransmitter) monitors.get(i); try { ui.updateMetrics(update.iterations, update.numTrans, update.average); } catch (MonitorDisconnectedException e) { log.error( "Failed to establish connection with MonitorTransmitter -- disconnecting from failed monitor"); disconnectMonitor(update.sessionId, ui); } } } } catch (Exception e) { log.error("MonitorServ failed to update admin screen with metrics information", e); } } private synchronized MetricsUpdate getNextUpdate() throws InterruptedException { try { if (metricsUpdateDone) { log.info("metricsUpdate ending... returning from getNextUpdate()..."); return new MetricsUpdate(0, 0, 0, 0.f); } if (!metricsUpdates.isEmpty() && metricsUpdates.size() > 0) return (MetricsUpdate) metricsUpdates.remove(0); else wait(1000); return getNextUpdate(); } catch (Exception e) { log.debug("Metrics updates lost synchronization -- resynchronizing"); return getNextUpdate(); } } }; Thread updateThr = new Thread(updater); updateThr.setDaemon(true); updateThr.start(); }
From source file:com.silverpeas.attachment.importExport.AttachmentImportExport.java
/** * Methode utilisee par la methode importAttachement(String,String,AttachmentDetail) pour creer un * attachement sur la publication creee dans la methode citee. * @param pubId - id de la publication dans laquelle creer l'attachment * @param componentId - id du composant contenant la publication * @param a_Detail - obejt contenant les informations necessaire e la creation de l'attachment * @return AttachmentDetail cree//from w w w .j a v a 2 s . c om */ private AttachmentDetail addAttachmentToPublication(String pubId, String componentId, AttachmentDetail a_Detail, String context, boolean indexIt) { int incrementSuffixe = 0; AttachmentDetail ad_toCreate = null; AttachmentPK atPK = new AttachmentPK(null, componentId); AttachmentPK foreignKey = new AttachmentPK(pubId, componentId); Vector<AttachmentDetail> attachments = AttachmentController.searchAttachmentByCustomerPK(foreignKey); int i = 0; String logicalName = a_Detail.getLogicalName(); String userId = a_Detail.getAuthor(); String updateRule = a_Detail.getImportUpdateRule(); if (!StringUtil.isDefined(updateRule) || "null".equalsIgnoreCase(updateRule)) { updateRule = AttachmentDetail.IMPORT_UPDATE_RULE_ADD; } SilverTrace.info("attachment", "AttachmentImportExport.addAttachmentToPublication()", "root.MSG_GEN_PARAM_VALUE", "updateRule=" + updateRule); // Verification s'il existe un attachment de meme nom, si oui, ajout // d'un // suffixe au nouveau fichier while (i < attachments.size()) { ad_toCreate = attachments.get(i); if (ad_toCreate.getLogicalName().equals(logicalName)) { if ((ad_toCreate.getSize() != a_Detail.getSize()) && AttachmentDetail.IMPORT_UPDATE_RULE_ADD.equalsIgnoreCase(updateRule)) { logicalName = a_Detail.getLogicalName(); int extPosition = logicalName.lastIndexOf('.'); if (extPosition != -1) { logicalName = logicalName.substring(0, extPosition) + "_" + (++incrementSuffixe) + logicalName.substring(extPosition, logicalName.length()); } else { logicalName += "_" + (++incrementSuffixe); } // On reprend la boucle au debut pour verifier que le nom // genere n est pas lui meme un autre nom d'attachment de la publication i = 0; } else {// on efface l'ancien fichier joint et on stoppe la boucle AttachmentController.deleteAttachment(ad_toCreate); break; } } else { i++; } } a_Detail.setLogicalName(logicalName); // On instancie l'objet attachment e creer ad_toCreate = new AttachmentDetail(atPK, a_Detail.getPhysicalName(), a_Detail.getLogicalName(), null, a_Detail.getType(), a_Detail.getSize(), context, new Date(), foreignKey, userId); ad_toCreate.setTitle(a_Detail.getTitle()); ad_toCreate.setInfo(a_Detail.getInfo()); ad_toCreate.setXmlForm(a_Detail.getXmlForm()); AttachmentController.createAttachment(ad_toCreate, indexIt); return ad_toCreate; }
From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.control.MonitorServ.java
/** Works like MetricsUpdates, except for num offers updates */ private void startNumOffersUpdateThread() { numOffersUpdates = new Vector(); Runnable updater = new Runnable() { public void run() { try { while (!numOffersDone) { NumOffersUpdate update = getNextUpdate(); if (update.sessionId == -1) { log.debug("Shutting down auxiliary num offers update thread"); break; }/*from w w w. j a v a 2 s . c o m*/ Vector monitors = getMonitors(update.sessionId); if (monitors == null) { log.warn("Cannot update MonitorTransmitters with num offers information for session " + update.sessionId + " -- that session does not exist!"); continue; } for (int i = 0; i < monitors.size(); i++) { MonitorTransmitter ui = (MonitorTransmitter) monitors.get(i); try { ui.updateNumOffers(update.client, update.numOffers); } catch (MonitorDisconnectedException e) { log.error( "Failed to establish connection with MonitorTransmitter -- disconnecting from failed monitor"); disconnectMonitor(update.sessionId, ui); } } } } catch (Exception e) { log.error("MonitorServ failed to update admin screen with num offers information", e); } } private synchronized NumOffersUpdate getNextUpdate() throws InterruptedException { try { if (numOffersDone) { log.info("numOffersUpdate ending... returning from getNextUpdate()..."); return new NumOffersUpdate(0, 0, 0); } if (!numOffersUpdates.isEmpty() && numOffersUpdates.size() > 0) return (NumOffersUpdate) numOffersUpdates.remove(0); else wait(1000); return getNextUpdate(); } catch (Exception e) { log.debug("Num offers updates lost synchronization -- resynchronizing"); return getNextUpdate(); } } }; Thread updateThr = new Thread(updater); updateThr.setDaemon(true); updateThr.start(); }
From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.control.MonitorServ.java
/** Works like MetricsUpdates, except for Price Chart updates */ private void startPriceChartUpdateThread() { priceChartUpdates = new Vector(); Runnable updater = new Runnable() { public void run() { try { while (!priceChartDone) { PriceChartUpdate pupdate = getNextUpdate(); if (pupdate.sessionId == -1) { log.debug("Shutting down auxiliary price chart update thread"); break; }// w ww. j av a 2s .co m Vector monitors = getMonitors(pupdate.sessionId); if (monitors == null) { log.warn("Cannot update MonitorTransmitters with price chart information for session " + pupdate.sessionId + " -- that session does not exist!"); continue; } for (int i = 0; i < monitors.size(); i++) { MonitorTransmitter ui = (MonitorTransmitter) monitors.get(i); try { ui.updatePriceChart(pupdate.security, pupdate.time, pupdate.price); } catch (MonitorDisconnectedException e) { log.error( "Failed to establish connection with MonitorTransmitter -- disconnecting from failed monitor"); disconnectMonitor(pupdate.sessionId, ui); } } } } catch (Exception e) { log.error("MonitorServ failed to update admin screen with price chart information", e); } } private synchronized PriceChartUpdate getNextUpdate() throws InterruptedException { try { if (priceChartDone) { log.info("priceChartUpdate ending... returning from getNextUpdate()..."); return new PriceChartUpdate(0, "0", 0.f, 0.f); } if (!priceChartUpdates.isEmpty() && priceChartUpdates.size() > 0) return (PriceChartUpdate) priceChartUpdates.remove(0); else wait(1000); return getNextUpdate(); } catch (Exception e) { log.debug("Price chart updates lost synchronization -- resynchronizing"); return getNextUpdate(); } } }; Thread updateThr = new Thread(updater); updateThr.setDaemon(true); updateThr.start(); }
From source file:org.jfree.chart.demo.JFreeChartDemo.java
/** * Creates a tabbed pane containing descriptions of the demo charts. * * @param resources localised resources. * * @return a tabbed pane./*ww w. j av a 2s. c om*/ */ private JTabbedPane createTabbedPane(final ResourceBundle resources) { final Font font = new Font("Dialog", Font.PLAIN, 12); final JTabbedPane tabs = new JTabbedPane(); int tab = 1; final Vector titles = new Vector(0); final String[] tabTitles; String title = null; while (tab > 0) { try { title = resources.getString("tabs." + tab); if (title != null) { titles.add(title); } else { tab = -1; } ++tab; } catch (Exception ex) { tab = -1; } } if (titles.size() == 0) { titles.add("Default"); } tab = titles.size(); this.panels = new JPanel[tab]; tabTitles = new String[tab]; --tab; for (; tab >= 0; --tab) { title = titles.get(tab).toString(); tabTitles[tab] = title; } titles.removeAllElements(); for (int i = 0; i < tabTitles.length; ++i) { this.panels[i] = new JPanel(); this.panels[i].setLayout(new LCBLayout(20)); this.panels[i].setPreferredSize(new Dimension(360, 20)); this.panels[i].setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); tabs.add(tabTitles[i], new JScrollPane(this.panels[i])); } String description; final String buttonText = resources.getString("charts.display"); JButton b1; // Load the CHARTS ... String usage = null; for (int i = 0; i <= CHART_COMMANDS.length - 1; ++i) { try { usage = resources.getString(CHART_COMMANDS[i][2] + ".usage"); } catch (Exception ex) { usage = null; } if ((usage == null) || usage.equalsIgnoreCase("All") || usage.equalsIgnoreCase("Swing")) { title = resources.getString(CHART_COMMANDS[i][2] + ".title"); description = resources.getString(CHART_COMMANDS[i][2] + ".description"); try { tab = Integer.parseInt(resources.getString(CHART_COMMANDS[i][2] + ".tab")); --tab; } catch (Exception ex) { System.err.println("Demo : Error retrieving tab identifier for chart " + CHART_COMMANDS[i][2]); System.err.println("Demo : Error = " + ex.getMessage()); tab = 0; } if ((tab < 0) || (tab >= this.panels.length)) { tab = 0; } System.out.println("Demo : adding " + CHART_COMMANDS[i][0] + " to panel " + tab); this.panels[tab].add(RefineryUtilities.createJLabel(title, font)); this.panels[tab].add(new DescriptionPanel(new JTextArea(description))); b1 = RefineryUtilities.createJButton(buttonText, font); b1.setActionCommand(CHART_COMMANDS[i][0]); b1.addActionListener(this); this.panels[tab].add(b1); } } return tabs; }