List of usage examples for java.util Vector remove
public synchronized E remove(int index)
From source file:skoa.helpers.Graficos.java
/** * FUNCIN ESTADSTICA PARA HALLAR LA EVOLUCIN DE DIFERENCIAS. * PORCENTAJE=(v1-v2)/v1*100/* www . j av a 2s . c o m*/ * DIFERENCIA=(v1-v2) * En caso de que no se encuentren los dos valores, y slo haya 1 o ninguno, se obvia esa medicion. * Vamos a comparar segn un intervalo en minutos. Si en ese intervalo, hay + de 1 medicion, se hace la media. * @param i, subopcion: 1=porcentaje y otro=diferencia normal */ private void aplicarFormula(int i) { Vector<String> nombresFicheros2 = new Vector<String>(nombresFicheros); //Copiamos los nombres String freferencia = nombresFicheros2.get(0); //Se coge el 1 fichero de referencia, al que se le irn aadiendo los datos. nombresFicheros2.remove(0); String fcomparar = nombresFicheros2.get(0); compararFicheros(freferencia, fcomparar); //Nombre del fichero resultante: n=tipo-intervalo-x-xx-xx-y-yy-yy String d1, d2, n; n = freferencia.substring(0, 4); //Hasta el segundo '-', es decir coge el tipo de consulta e intervalo //d1=freferencia.substring(freferencia.length()-10, freferencia.length()-4); //La DG del fich referencia (1 columna de valores) //d2=fcomparar.substring(fcomparar.length()-10, fcomparar.length()-4); //La DG del otro fichero (2 columna de valores) d1 = freferencia.substring(freferencia.indexOf(" ") - 6, freferencia.indexOf(" ")); d2 = fcomparar.substring(fcomparar.indexOf(" ") - 6, fcomparar.indexOf(" ")); //System.out.println(d1+"-"+d2+"."); n = n + "-" + d1 + "-" + d2; //Fichero usado para obtener la serie. Es el fichero resultante de aplicarFormulaP() FileReader fr = null; BufferedReader linea = null; String line; //Leemos el fichero unificado.txt con los dos valores y les aplicamos la frmula (V1/V2)*100 File uni = new File(ruta + "unificado.txt"); try { int i1 = 1; fr = new FileReader(uni); linea = new BufferedReader(fr); unidad = ""; while ((line = linea.readLine()) != null) { //Lectura del fichero String v, f, l; float v1 = 0, v2; f = line.substring(0, line.indexOf("\t")); l = line.substring(line.indexOf("\t") + 1); //l tiene hasta los valores. if (l.indexOf("0") == 0) v1 = 0; //El primer valor es un 0. else if (l.indexOf(" ") > 0) { //El 1 valor es distinto de 0, por lo convertimos a int. v = l.substring(0, l.indexOf(" ")); v1 = Float.parseFloat(v); if (i1 == 1) { String aux = l.substring(l.indexOf(" ") + 1); if (aux.indexOf("\t") >= 0) aux = aux.substring(0, aux.indexOf("\t")); unidad = unidad + aux; //i1=0; } } if (l.indexOf("\t") >= 0) { //Si encontramos \t, quiere decir que hay un segundo valor !=0 l = l.substring(l.indexOf("\t") + 1); v = l.substring(0, l.indexOf(" ")); v2 = Float.parseFloat(v); /*if (i1==1){ //unidad=unidad+l.substring(l.indexOf(" ")+1); i1=0; }*/ } else v2 = 0; //Una vez tenemos los valores en v1 y v2, aplicamos la formula. Si el numerador y/o denominador es 0 //entonces el resultado ser directamente 0. En v1, guardamos el resultado (reusamos esta variable) if (v1 == 0 || v2 == 0) v1 = 0; else if (v1 == 0 && v2 == 0) v1 = 0; else { if (i == 1) { //HALLA EL PORCENTAJE. float r = v1 - v2; if (r < 0) r = 0 - r; v1 = (r / v1) * 100; } else v1 = v1 - v2; //HALLA EL VALOR de la diferencia, que puede ser negativo. } guardar(f, v1, n); i1 = 0; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != fr) fr.close(); //Se cierra si todo va bien. } catch (Exception e2) { //Sino salta una excepcion. e2.printStackTrace(); } } if (i == 1) unidad = "%" + "\t" + unidad; else unidad = "ABS" + "\t" + unidad; }
From source file:gate.util.reporting.PRTimeReporter.java
/** * Reads the given file upside down./*w w w . j a v a 2 s . c om*/ * * @param fileToBeRead * An object of type File representing the file to be read. * @param chunkSize * An integer specifying the size of the chunks in which file will be * read. * @return A long value pointing to the start position of the given file * chunk. * @throws BenchmarkReportInputFileFormatException */ private long tail(File fileToBeRead, int chunkSize) throws BenchmarkReportInputFileFormatException { RandomAccessFile raf = null; try { raf = new RandomAccessFile(fileToBeRead, "r"); Vector<String> lastNlines = new Vector<String>(); int delta = 0; long curPos = raf.length() - 1; long fromPos; byte[] bytearray; while (true) { fromPos = curPos - chunkSize; if (fromPos <= 0) { raf.seek(0); bytearray = new byte[(int) curPos]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines)) { if (fromPos < 0) fromPos = 0; } break; } else { raf.seek(fromPos); bytearray = new byte[chunkSize]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines)) { break; } delta = (lastNlines.get(lastNlines.size() - 1)).length(); lastNlines.remove(lastNlines.size() - 1); curPos = fromPos + delta; } } if (fromPos < 0) throw new BenchmarkReportInputFileFormatException( getBenchmarkFile().getAbsolutePath() + " does not contain a marker named " + getLogicalStart() + " indicating logical start of a run."); return fromPos; } catch (IOException e) { e.printStackTrace(); return -1; } finally { IOUtils.closeQuietly(raf); } }
From source file:gate.util.reporting.DocTimeReporter.java
/** * A method for reading the file upside down. * * @param fileToBeRead//from w ww .j ava 2s . c om * An object of the file to be read. * @param chunkSize * An integer specifying the size of the chunks in which file will be * read. * @return A long value pointing to the start position of the given file * chunk. */ private long tail(File fileToBeRead, int chunkSize) throws BenchmarkReportInputFileFormatException { RandomAccessFile raf = null; try { raf = new RandomAccessFile(fileToBeRead, "r"); Vector<String> lastNlines = new Vector<String>(); int delta = 0; long curPos = 0; curPos = raf.length() - 1; long fromPos; byte[] bytearray; while (true) { fromPos = curPos - chunkSize; if (fromPos <= 0) { raf.seek(0); bytearray = new byte[(int) curPos]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines, fromPos)) { if (fromPos < 0) fromPos = 0; } break; } else { raf.seek(fromPos); bytearray = new byte[chunkSize]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines, fromPos)) { break; } delta = lastNlines.get(lastNlines.size() - 1).length(); lastNlines.remove(lastNlines.size() - 1); curPos = fromPos + delta; } } if (fromPos < 0) throw new BenchmarkReportInputFileFormatException( getBenchmarkFile() + " does not contain a marker named " + getLogicalStart() + " indicating logical start of a run."); return fromPos; } catch (IOException e) { e.printStackTrace(); return -1; } finally { IOUtils.closeQuietly(raf); } }
From source file:org.apache.rampart.util.RampartUtil.java
public static void handleEncryptedSignedHeaders(Vector encryptedParts, Vector signedParts, Document doc) { //TODO Is there a more efficient way to do this ? better search algorithm for (int i = 0; i < signedParts.size(); i++) { WSEncryptionPart signedPart = (WSEncryptionPart) signedParts.get(i); //This signed part is not a header if (signedPart.getNamespace() == null || signedPart.getName() == null) { continue; }/* ww w .j av a2 s . c om*/ for (int j = 0; j < encryptedParts.size(); j++) { WSEncryptionPart encryptedPart = (WSEncryptionPart) encryptedParts.get(j); if (encryptedPart.getNamespace() == null || encryptedPart.getName() == null) { continue; } if (signedPart.getName().equals(encryptedPart.getName()) && signedPart.getNamespace().equals(encryptedPart.getNamespace())) { String encDataID = encryptedPart.getEncId(); Element encDataElem = WSSecurityUtil.findElementById(doc.getDocumentElement(), encDataID, null); if (encDataElem != null) { Element encHeader = (Element) encDataElem.getParentNode(); String encHeaderId = encHeader.getAttributeNS(WSConstants.WSU_NS, "Id"); //For some reason the id might not be available // so the part/element with empty/null id won't be recognized afterwards. if (encHeaderId != null && !"".equals(encHeaderId.trim())) { signedParts.remove(signedPart); WSEncryptionPart encHeaderToSign = new WSEncryptionPart(encHeaderId); signedParts.add(encHeaderToSign); } } } } } }
From source file:com.duroty.application.mail.manager.MailManager.java
/** * DOCUMENT ME!// ww w.ja va2 s . c o m * * @param hsession DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param mids DOCUMENT ME! * @param hash DOCUMENT ME! * * @return DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public MailPartObj getAttachment(Session hsession, String repositoryName, String mid, String hash) throws MailException { MailPartObj part = null; try { MimeMessage mime = messageable.getMimeMessage(mid, getUser(hsession, repositoryName)); if (mime != null) { Vector dmailParts = new Vector(); MessageUtilities.decodeContent(mime, new StringBuffer(), dmailParts, true, "<br/>"); while (dmailParts.size() > 0) { MailPart aux = (MailPart) dmailParts.remove(0); if (aux.getId() == Integer.parseInt(hash)) { part = new MailPartObj(); part.setAttachent(IOUtils.toByteArray(aux.getPart().getInputStream())); part.setContentType(aux.getContentType()); part.setId(aux.getId()); part.setName(aux.getName()); part.setSize(aux.getSize()); break; } } } else { throw new MailException("The Attachment is null"); } if (part == null) { throw new MailException("The Attachment is null"); } return part; } catch (Exception ex) { throw new MailException(ex); } catch (java.lang.OutOfMemoryError ex) { System.gc(); throw new MailException(ex); } catch (Throwable ex) { throw new MailException(ex); } finally { GeneralOperations.closeHibernateSession(hsession); System.gc(); } }
From source file:weave.servlets.AdminService.java
/** * getSortedUniqueValues//from ww w.j a v a2 s.c om * * @param values * A list of string values which may contain duplicates. * @param moveEmptyStringToEnd * If set to true and "" is at the front of the list, "" is moved * to the end. * @return A sorted list of unique values found in the given list. */ private List<String> getSortedUniqueValues(List<String> values, boolean moveEmptyStringToEnd) { Set<String> uniqueValues = new HashSet<String>(); uniqueValues.addAll(values); Vector<String> result = new Vector<String>(uniqueValues); Collections.sort(result, String.CASE_INSENSITIVE_ORDER); // if empty string is at beginning of sorted list, move it to the end of // the list if (moveEmptyStringToEnd && result.size() > 0 && result.get(0).equals("")) result.add(result.remove(0)); return result; }
From source file:it.classhidra.core.controller.bsController.java
public static Vector getActionStreams_(String id_action) { Vector _streams_orig = (Vector) getAction_config().get_streams_apply_to_actions().get("*"); //Modifica 20100521 Warning /*/*from w w w .j a v a 2 s .co m*/ try{ _streams = (Vector)util_cloner.clone(_streams_orig); }catch(Exception e){ } */ Vector _streams4action = (Vector) getAction_config().get_streams_apply_to_actions().get(id_action); if (_streams4action == null) return (_streams_orig == null) ? new Vector() : _streams_orig; else { Vector _streams = new Vector(); if (_streams_orig != null) _streams.addAll(_streams_orig); Vector _4add = new Vector(); HashMap _4remove = new HashMap(); for (int i = 0; i < _streams4action.size(); i++) { info_stream currentis = (info_stream) _streams4action.get(i); if (currentis.get_apply_to_action() != null) { info_apply_to_action currentiata = (info_apply_to_action) currentis.get_apply_to_action() .get(id_action); if (currentiata.getExcluded() != null && currentiata.getExcluded().equalsIgnoreCase("true")) _4remove.put(currentis.getName(), currentis.getName()); else _4add.add(currentis); } } _streams.addAll(_4add); if (_4remove.size() > 0) { int i = 0; while (i < _streams.size()) { info_stream currentis = (info_stream) _streams.get(i); if (_4remove.get(currentis.getName()) != null) _streams.remove(i); else i++; } } _streams = new util_sort().sort(_streams, "int_order", "A"); return _streams; } }
From source file:edu.ku.brc.specify.ui.db.ResultSetTableModel.java
@Override //@SuppressWarnings("null") public synchronized void exectionDone(final SQLExecutionProcessor process, final ResultSet resultSet) { if (statusBar != null) { statusBar.incrementValue(getClass().getSimpleName()); }//w ww. j a v a 2 s.com if (resultSet == null || results == null) { log.error("The " + (resultSet == null ? "resultSet" : "results") + " is null."); if (propertyListener != null) { propertyListener.propertyChange(new PropertyChangeEvent(this, "rowCount", null, 0)); } return; } List<ERTICaptionInfo> captions = results.getVisibleCaptionInfo(); // This can do one of two things: // 1) Take multiple columns and create an object and use a DataObjectFormatter to format the object. // 2) Table multiple objects that were derived from the columns and roll those up into a single column's value. // This happens when you get back rows of info where part of the columns are duplicated because you really // want those value to be put into a single column. // // Step One - Is to figure out what type of object needs to be created and what the Columns are // that need to be set into the object so the dataObjFormatter can do its job. // // Step Two - If the objects are being aggregated then the object created from the columns are added to a List // and then last formatted as an "aggregation" try { if (resultSet.next()) { ResultSetMetaData metaData = resultSet.getMetaData(); // Composite boolean hasCompositeObj = false; DataObjSwitchFormatter dataObjFormatter = null; UIFieldFormatterIFace formatter = null; Object compObj = null; // Aggregates ERTICaptionInfo aggCaption = null; ERTICaptionInfo compositeCaption = null; Vector<Object> aggList = null; DataObjectSettable aggSetter = null; Stack<Object> aggListRecycler = null; DataObjectSettable dataSetter = null; // data getter for Aggregate or the Subclass // Loop through the caption to figure out what columns will be displayed. // Watch for Captions with an Aggregator or Composite numColumns = captions.size(); for (ERTICaptionInfo caption : captions) { colNames.addElement(caption.getColLabel()); int inx = caption.getPosIndex() + 1; //log.debug(metaData.getColumnClassName(inx)); Class<?> cls = null; try { cls = Class.forName(metaData.getColumnClassName(inx)); if (cls == Calendar.class || cls == java.sql.Date.class || cls == Date.class) { cls = String.class; } } catch (SQLException ex) { cls = String.class; } classNames.addElement(cls); caption.setColClass(cls); if (caption.getAggregatorName() != null) { //log.debug("The Agg is ["+caption.getAggregatorName()+"] "+caption.getColName()); // Alright we have an aggregator aggList = new Vector<Object>(); aggListRecycler = new Stack<Object>(); aggCaption = caption; aggSetter = DataObjectSettableFactory.get(aggCaption.getAggClass().getName(), FormHelper.DATA_OBJ_SETTER); // Now check to see if we are aggregating the this type of object or a child object of this object // For example Collectors use an Agent as part of the aggregation if (aggCaption.getSubClass() != null) { dataSetter = DataObjectSettableFactory.get(aggCaption.getSubClass().getName(), FormHelper.DATA_OBJ_SETTER); } else { dataSetter = aggSetter; } } else if (caption.getColInfoList() != null) { formatter = caption.getUiFieldFormatter(); if (formatter != null) { compositeCaption = caption; } else { // OK, now aggregation but we will be rolling up multiple columns into a single object for formatting // We need to get the formatter to see what the Class is of the object hasCompositeObj = true; aggCaption = caption; dataObjFormatter = caption.getDataObjFormatter(); if (dataObjFormatter != null) { if (dataObjFormatter.getDataClass() != null) { aggSetter = DataObjectSettableFactory.get( dataObjFormatter.getDataClass().getName(), "edu.ku.brc.af.ui.forms.DataSetterForObj"); } else { log.error("formatterObj.getDataClass() was null for " + caption.getColName()); } } else { log.error("DataObjFormatter was null for " + caption.getColName()); } } } //colNames.addElement(metaData.getColumnName(i)); //System.out.println("**************** " + caption.getColLabel()+ " "+inx+ " " + caption.getColClass().getSimpleName()); } // aggCaption will be non-null for both a Aggregate AND a Composite if (aggCaption != null) { // Here we need to dynamically discover what the column indexes are that we to grab // in order to set them into the created data object for (ERTICaptionInfo.ColInfo colInfo : aggCaption.getColInfoList()) { for (int i = 0; i < metaData.getColumnCount(); i++) { String colName = StringUtils.substringAfterLast(colInfo.getColumnName(), "."); if (colName.equalsIgnoreCase(metaData.getColumnName(i + 1))) { colInfo.setPosition(i); break; } } } // Now check to see if there is an Order Column because the Aggregator // might need it for sorting the Aggregation String ordColName = aggCaption.getOrderCol(); if (StringUtils.isNotEmpty(ordColName)) { String colName = StringUtils.substringAfterLast(ordColName, "."); //log.debug("colName ["+colName+"]"); for (int i = 0; i < metaData.getColumnCount(); i++) { //log.debug("["+colName+"]["+metaData.getColumnName(i+1)+"]"); if (colName.equalsIgnoreCase(metaData.getColumnName(i + 1))) { aggCaption.setOrderColIndex(i); break; } } if (aggCaption.getOrderColIndex() == -1) { log.error("Agg Order Column Index wasn't found [" + ordColName + "]"); } } } if (ids == null) { ids = new Vector<Integer>(); } else { ids.clear(); } // Here is the tricky part. // When we are doing a Composite we are just taking multiple columns and // essentially replace them with a single value from the DataObjFormatter // // But when doing an Aggregation we taking several rows and rolling them up into a single value. // so this code knows when it is doing an aggregation, so it knows to only add a new row to the display-able // results when primary id changes. DataObjFieldFormatMgr dataObjMgr = DataObjFieldFormatMgr.getInstance(); Vector<Object> row = null; boolean firstTime = true; int prevId = Integer.MAX_VALUE; // really can't assume any value but will choose Max int numCols = resultSet.getMetaData().getColumnCount(); do { int id = resultSet.getInt(1); //log.debug("id: "+id+" prevId: "+prevId); // Remember aggCaption is used by both a Aggregation and a Composite if (aggCaption != null && !hasCompositeObj) { if (firstTime) { prevId = id; row = new Vector<Object>(); firstTime = false; cache.add(row); ids.add(id); } else if (id != prevId) { //log.debug("Agg List len: "+aggList.size()); if (row != null && aggList != null) { int aggInx = captions.indexOf(aggCaption); row.remove(aggInx); row.insertElementAt(dataObjMgr.aggregate(aggList, aggCaption.getAggClass()), aggInx); if (aggListRecycler != null) { aggListRecycler.addAll(aggList); } aggList.clear(); row = new Vector<Object>(); cache.add(row); ids.add(id); } prevId = id; } else if (row == null) { row = new Vector<Object>(); cache.add(row); ids.add(id); } } else { row = new Vector<Object>(); cache.add(row); ids.add(id); } // Now for each Caption column get a value for (ERTICaptionInfo caption : captions) { int posIndex = caption.getPosIndex(); if (caption == aggCaption) // Checks to see if we need to take multiple columns and make one column { if (hasCompositeObj) // just doing a Composite { if (aggSetter != null && row != null && dataObjFormatter != null) { if (compObj == null) { compObj = aggCaption.getAggClass().newInstance(); } for (ERTICaptionInfo.ColInfo colInfo : aggCaption.getColInfoList()) { setField(aggSetter, compObj, colInfo.getFieldName(), colInfo.getFieldClass(), resultSet, colInfo.getPosition()); } row.add(DataObjFieldFormatMgr.getInstance().format(compObj, compObj.getClass())); } else if (formatter != null) { int len = compositeCaption.getColInfoList().size(); Object[] val = new Object[len]; int i = 0; for (ERTICaptionInfo.ColInfo colInfo : compositeCaption.getColInfoList()) { int colInx = colInfo.getPosition() + posIndex + 1; if (colInx < numCols) { val[i++] = resultSet.getObject(colInx); } else { //val[i++] = resultSet.getObject(posIndex+1); val[i++] = "(Missing Data)"; } } row.add(formatter.formatToUI(val)); } else { log.error("Aggregator is null! [" + aggCaption.getAggregatorName() + "] or row or aggList"); } } else if (aggSetter != null && row != null && aggList != null) // Doing an Aggregation { Object aggObj; if (aggListRecycler.size() == 0) { aggObj = aggCaption.getAggClass().newInstance(); } else { aggObj = aggListRecycler.pop(); } Object aggSubObj = aggCaption.getSubClass() != null ? aggCaption.getSubClass().newInstance() : null; aggList.add(aggObj); //@SuppressWarnings("unused") //DataObjAggregator aggregator = DataObjFieldFormatMgr.getInstance().getAggregator(aggCaption.getAggregatorName()); //log.debug(" aggCaption.getOrderColIndex() "+ aggCaption.getOrderColIndex()); //aggSetter.setFieldValue(aggObj, aggregator.getOrderFieldName(), resultSet.getObject(aggCaption.getOrderColIndex() + 1)); Object dataObj; if (aggSubObj != null) { aggSetter.setFieldValue(aggObj, aggCaption.getSubClassFieldName(), aggSubObj); dataObj = aggSubObj; } else { dataObj = aggObj; } for (ERTICaptionInfo.ColInfo colInfo : aggCaption.getColInfoList()) { setField(dataSetter, dataObj, colInfo.getFieldName(), colInfo.getFieldClass(), resultSet, colInfo.getPosition()); } row.add("PlaceHolder"); } else if (aggSetter == null || aggList == null) { log.error("Aggregator is null! [" + aggCaption.getAggregatorName() + "] or aggList[" + aggList + "]"); } } else if (row != null) { if (caption.getColName() == null && caption.getColInfoList().size() > 0) { int len = caption.getColInfoList().size(); Object[] val = new Object[len]; for (int i = 0; i < caption.getColInfoList().size(); i++) { int inx = posIndex + 1 + i; val[i] = caption.processValue(resultSet.getObject(inx)); } row.add(caption.getUiFieldFormatter().formatToUI(val)); //col += caption.getColInfoList().size() - 1; } else { Object obj = caption.processValue(resultSet.getObject(posIndex + 1)); row.add(obj); } } } } while (resultSet.next()); // We were always setting the rolled up data when the ID changed // but on the last row we need to do it here manually (so to speak) if (aggCaption != null && aggList != null && aggList.size() > 0 && row != null) { int aggInx = captions.indexOf(aggCaption); row.remove(aggInx); String colStr; if (StringUtils.isNotEmpty(aggCaption.getAggregatorName())) { colStr = DataObjFieldFormatMgr.getInstance().aggregate(aggList, aggCaption.getAggregatorName()); } else { colStr = DataObjFieldFormatMgr.getInstance().aggregate(aggList, aggCaption.getAggClass()); } row.insertElementAt(colStr, aggInx); aggList.clear(); aggListRecycler.clear(); } fireTableStructureChanged(); fireTableDataChanged(); } } catch (Exception ex) { ex.printStackTrace(); } if (propertyListener != null) { propertyListener .propertyChange(new PropertyChangeEvent(this, "rowCount", null, new Integer(cache.size()))); } }
From source file:org.kepler.kar.KARFile.java
/** * This method makes sure that all of the entries of this KARFile are in the * Cache. It caches the entries in the order that their dependencies * dictate./* w ww. j av a2s . c o m*/ * * @throws Exception */ public void cacheKARContents() throws Exception { if (isDebugging) { log.debug("openKAR: " + this.toString()); } try { // get references to all the managers we'll be using LocalRepositoryManager lrm = LocalRepositoryManager.getInstance(); KARCacheManager kcm = KARCacheManager.getInstance(); CacheManager cm = CacheManager.getInstance(); // Make sure the file is in a local repository if (!lrm.isInLocalRepository(getFileLocation())) { log.warn("KAR should be in a Local Repository Folder to be inserted in the cache: " + getFileLocation()); // return; } // Add a row to the KARS_CACHED table boolean inserted = kcm.insertIntoCache(this); if (!inserted) { // This KAR has already been cached, don't do it again return; } // keep two lists while traversing the dependencies, start with all // of the entries (we don't know yet if they are cached or not) // and move them into the cached entries as they are cached (or if // they are already cached) Vector<KAREntry> entries = (Vector<KAREntry>) karEntries(); Hashtable<KeplerLSID, KAREntry> cachedEntries = new Hashtable<KeplerLSID, KAREntry>(); // do one pass through the entries to see if any of them are already // in the cache for (KAREntry entry : entries) { KeplerLSID lsid = entry.getLSID(); // See if this entry is already in the Cache boolean alreadyCached = cm.isContained(lsid); if (alreadyCached) { // add this entry into the cachedEntries list cachedEntries.put(entry.getLSID(), entry); // Insert a row into the KAR_CONTENTS table for this entry File karFile = getFileLocation(); KeplerLSID entryLsid = entry.getLSID(); String entryName = entry.getName(); String entryType = entry.getType(); kcm.insertEntryIntoCache(karFile, entryLsid, entryName, entryType); } } // remove entries that were already cached for (KAREntry entry : cachedEntries.values()) { entries.remove(entry); } // keep cycling through the uncached entries until the list is empty while (entries.size() > 0) { // keep track of the entries cached during this pass Vector<KAREntry> cachedThisPass = new Vector<KAREntry>(entries.size()); // cycle through all of the remaining, uncached entries for (KAREntry entry : entries) { if (isDebugging) log.debug(entry.getName()); // get the dependency list for this entry List<KeplerLSID> depList = entry.getLsidDependencies(); if (depList.size() == 0) { // if there are no dependencies we just cache it boolean success = cache(entry); if (success) { cachedEntries.put(entry.getLSID(), entry); cachedThisPass.add(entry); break; } if (isDebugging) log.debug(success); } else { // if there are dependencies then we check to make sure // that all of the dependencies have already been cached boolean allDependenciesHaveBeenCached = true; for (KeplerLSID lsid : depList) { // if any of the dependencies have not been cached, // set false if (!cm.isContained(lsid)) { allDependenciesHaveBeenCached = false; } } if (allDependenciesHaveBeenCached) { // all dependencies have been cached so it is // OK to cache this entry boolean success = cache(entry); if (success) { cachedEntries.put(entry.getLSID(), entry); cachedThisPass.add(entry); break; } if (isDebugging) log.debug(success); } } } if (cachedThisPass.size() == 0) { // Bad news, nothing is getting cached // This means that there are uncached entries that // have unsatisfied dependencies // break out to avoid infinite loop // Vector<KAREntry> entriesWithBrokenDependencies = entries; break; } // remove any entries that got cached this pass for (KAREntry entry : cachedThisPass) { entries.remove(entry); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.oodt.cas.workflow.gui.perspective.view.impl.DefaultPropView.java
@Override public void refreshView(final ViewState state) { this.removeAll(); tableMenu = new JPopupMenu("TableMenu"); this.add(tableMenu); override = new JMenuItem(OVERRIDE); override.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = DefaultPropView.this.table.getSelectedRow();// rowAtPoint(DefaultPropView.this.table.getMousePosition()); String key = getKey((String) DefaultPropView.this.table.getValueAt(row, 1), state); Metadata staticMet = state.getSelected().getModel().getStaticMetadata(); if (staticMet == null) { staticMet = new Metadata(); }/*w ww . ja v a 2 s.co m*/ if (e.getActionCommand().equals(OVERRIDE)) { if (!staticMet.containsKey(key)) { staticMet.addMetadata(key, (String) DefaultPropView.this.table.getValueAt(row, 2)); String envReplace = (String) DefaultPropView.this.table.getValueAt(row, 3); if (Boolean.valueOf(envReplace)) { staticMet.addMetadata(key + "/envReplace", envReplace); } state.getSelected().getModel().setStaticMetadata(staticMet); DefaultPropView.this.notifyListeners(); } } } }); delete = new JMenuItem(DELETE); delete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = DefaultPropView.this.table.getSelectedRow();// rowAtPoint(DefaultPropView.this.table.getMousePosition()); String key = getKey((String) DefaultPropView.this.table.getValueAt(row, 1), state); Metadata staticMet = state.getSelected().getModel().getStaticMetadata(); if (staticMet == null) { staticMet = new Metadata(); } staticMet.removeMetadata(key); staticMet.removeMetadata(key + "/envReplace"); state.getSelected().getModel().setStaticMetadata(staticMet); DefaultPropView.this.notifyListeners(); } }); tableMenu.add(override); tableMenu.add(delete); if (state.getSelected() != null) { JPanel masterPanel = new JPanel(); masterPanel.setLayout(new BoxLayout(masterPanel, BoxLayout.Y_AXIS)); masterPanel.add(this.getModelIdPanel(state.getSelected(), state)); masterPanel.add(this.getModelNamePanel(state.getSelected(), state)); if (!state.getSelected().getModel().isParentType()) { masterPanel.add(this.getInstanceClassPanel(state.getSelected(), state)); } masterPanel.add(this.getExecutionTypePanel(state.getSelected(), state)); masterPanel.add(this.getPriorityPanel(state)); masterPanel.add(this.getExecusedIds(state.getSelected())); if (state.getSelected().getModel().getExecutionType().equals("condition")) { masterPanel.add(this.getTimeout(state.getSelected(), state)); masterPanel.add(this.getOptional(state.getSelected(), state)); } JScrollPane scrollPane = new JScrollPane(table = this.createTable(state), JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.getHorizontalScrollBar().setUnitIncrement(10); scrollPane.getVerticalScrollBar().setUnitIncrement(10); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.setBorder(new EtchedBorder()); final JLabel metLabel = new JLabel("Static Metadata"); metLabel.setAlignmentX(Component.CENTER_ALIGNMENT); final JLabel extendsLabel = new JLabel("<extends>"); extendsLabel.setFont(new Font("Serif", Font.PLAIN, 10)); extendsLabel.setAlignmentX(Component.CENTER_ALIGNMENT); extendsLabel.addMouseListener(new MouseListener() { private JScrollPane availableScroller; private JScrollPane mineScroller; private JList mineList; private JList availableList; private DefaultListModel mineModel; private DefaultListModel availableModel; public void mouseClicked(MouseEvent e) { final JPopupMenu popup = new JPopupMenu(); popup.setLayout(new BorderLayout()); JPanel main = new JPanel(); main.setLayout(new BoxLayout(main, BoxLayout.X_AXIS)); JPanel mine = new JPanel(); mine.setBorder(new EtchedBorder()); mine.setLayout(new BorderLayout()); JLabel mineLabel = new JLabel("Mine"); mineScroller = new JScrollPane(mineList = createJList(mineModel = new DefaultListModel(), state.getSelected().getModel().getExtendsConfig())); mineScroller.setPreferredSize(new Dimension(250, 80)); mine.add(mineLabel, BorderLayout.NORTH); mine.add(mineScroller, BorderLayout.CENTER); JPanel available = new JPanel(); available.setBorder(new EtchedBorder()); available.setLayout(new BorderLayout()); JLabel availableLabel = new JLabel("Available"); Vector<String> availableGroups = new Vector<String>(state.getGlobalConfigGroups().keySet()); availableGroups.removeAll(state.getSelected().getModel().getExtendsConfig()); availableScroller = new JScrollPane(availableList = this .createJList(availableModel = new DefaultListModel(), availableGroups)); availableScroller.setPreferredSize(new Dimension(250, 80)); available.add(availableLabel, BorderLayout.NORTH); available.add(availableScroller, BorderLayout.CENTER); JPanel buttons = new JPanel(); buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS)); JButton addButton = new JButton("<---"); addButton.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { String selected = availableList.getSelectedValue().toString(); Vector<String> extendsConfig = new Vector<String>( state.getSelected().getModel().getExtendsConfig()); extendsConfig.add(selected); state.getSelected().getModel().setExtendsConfig(extendsConfig); availableModel.remove(availableList.getSelectedIndex()); mineModel.addElement(selected); popup.revalidate(); DefaultPropView.this.notifyListeners(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } }); JButton removeButton = new JButton("--->"); removeButton.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { String selected = mineList.getSelectedValue().toString(); Vector<String> extendsConfig = new Vector<String>( state.getSelected().getModel().getExtendsConfig()); extendsConfig.remove(selected); state.getSelected().getModel().setExtendsConfig(extendsConfig); mineModel.remove(mineList.getSelectedIndex()); availableModel.addElement(selected); popup.revalidate(); DefaultPropView.this.notifyListeners(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } }); buttons.add(addButton); buttons.add(removeButton); main.add(mine); main.add(buttons); main.add(available); popup.add(main, BorderLayout.CENTER); popup.show(extendsLabel, e.getX(), e.getY()); } public void mouseEntered(MouseEvent e) { extendsLabel.setForeground(Color.blue); } public void mouseExited(MouseEvent e) { extendsLabel.setForeground(Color.black); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } private JList createJList(DefaultListModel model, final List<String> list) { for (String value : list) { model.addElement(value); } JList jList = new JList(model); jList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); jList.setLayoutOrientation(JList.VERTICAL); return jList; } }); JLabel metGroupLabel = new JLabel("(Sub-Group: " + (state.getCurrentMetGroup() != null ? state.getCurrentMetGroup() : "<base>") + ")"); metGroupLabel.setAlignmentX(Component.CENTER_ALIGNMENT); JPanel labelPanel = new JPanel(); labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.Y_AXIS)); JPanel top = new JPanel(); top.setLayout(new BoxLayout(top, BoxLayout.Y_AXIS)); top.add(extendsLabel); top.add(metLabel); labelPanel.add(top); labelPanel.add(metGroupLabel); panel.add(labelPanel, BorderLayout.NORTH); panel.add(scrollPane, BorderLayout.CENTER); masterPanel.add(panel); this.add(masterPanel); } else { this.add(new JPanel()); } this.revalidate(); }