rem
stringlengths
0
477k
add
stringlengths
0
313k
context
stringlengths
6
599k
} else { try { _factory.passivateObject(pair.value); } catch(Exception e) { removeObject=true; }
public synchronized void evict() throws Exception { assertOpen(); if(!_pool.isEmpty()) { ListIterator iter; if (evictLastIndex < 0) { iter = _pool.listIterator(_pool.size()); } else { iter = _pool.listIterator(evictLastIndex); } for(int i=0,m=getNumTests();i<m;i++) { if(!iter.hasPrevious()) { iter = _pool.listIterator(_pool.size()); } else { boolean removeObject = false; ObjectTimestampPair pair = (ObjectTimestampPair)(iter.previous()); long idleTimeMilis = System.currentTimeMillis() - pair.tstamp; if ((_minEvictableIdleTimeMillis > 0) && (idleTimeMilis > _minEvictableIdleTimeMillis)) { removeObject = true; } else if ((_softMinEvictableIdleTimeMillis > 0) && (idleTimeMilis > _softMinEvictableIdleTimeMillis) && (getNumIdle() > getMinIdle())) { removeObject = true; } if(_testWhileIdle && removeObject == false) { boolean active = false; try { _factory.activateObject(pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(pair.value)) { removeObject=true; } else { try { _factory.passivateObject(pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { iter.remove(); _factory.destroyObject(pair.value); } catch(Exception e) { ; // ignored } } } } evictLastIndex = iter.previousIndex(); // resume from here } // if !empty }
if(removeObject) { try { iter.remove(); _factory.destroyObject(pair.value); } catch(Exception e) { ; }
} if(removeObject) { try { iter.remove(); _factory.destroyObject(pair.value); } catch(Exception e) {
public synchronized void evict() throws Exception { assertOpen(); if(!_pool.isEmpty()) { ListIterator iter; if (evictLastIndex < 0) { iter = _pool.listIterator(_pool.size()); } else { iter = _pool.listIterator(evictLastIndex); } for(int i=0,m=getNumTests();i<m;i++) { if(!iter.hasPrevious()) { iter = _pool.listIterator(_pool.size()); } else { boolean removeObject = false; ObjectTimestampPair pair = (ObjectTimestampPair)(iter.previous()); long idleTimeMilis = System.currentTimeMillis() - pair.tstamp; if ((_minEvictableIdleTimeMillis > 0) && (idleTimeMilis > _minEvictableIdleTimeMillis)) { removeObject = true; } else if ((_softMinEvictableIdleTimeMillis > 0) && (idleTimeMilis > _softMinEvictableIdleTimeMillis) && (getNumIdle() > getMinIdle())) { removeObject = true; } if(_testWhileIdle && removeObject == false) { boolean active = false; try { _factory.activateObject(pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(pair.value)) { removeObject=true; } else { try { _factory.passivateObject(pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { iter.remove(); _factory.destroyObject(pair.value); } catch(Exception e) { ; // ignored } } } } evictLastIndex = iter.previousIndex(); // resume from here } // if !empty }
return _numTestsPerEvictionRun;
return Math.min(_numTestsPerEvictionRun, _pool.size());
private int getNumTests() { if(_numTestsPerEvictionRun >= 0) { return _numTestsPerEvictionRun; } else { return(int)(Math.ceil((double)_pool.size()/Math.abs((double)_numTestsPerEvictionRun))); } }
catch (Exception e) {
catch (Throwable e) {
public Object borrowObject() throws Exception { long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { ObjectTimestampPair pair = null; synchronized(this) { assertOpen(); // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(_pool.removeFirst()); } catch(NoSuchElementException e) { ; /* ignored */ } // otherwise if(null == pair) { // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) if(_maxActive < 0 || _numActive < _maxActive) { // allow new object to be created } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException("Pool exhausted"); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { wait(_maxWait); } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("WhenExhaustedAction property " + _whenExhaustedAction + " not recognized."); } } } _numActive++; } // end synchronized // create new object when needed if(null == pair) { try { Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); newlyCreated = true; } catch (Exception e) { // object cannot be created synchronized(this) { _numActive--; notifyAll(); } throw e; } } // activate & validate the object try { _factory.activateObject(pair.value); if(_testOnBorrow && !_factory.validateObject(pair.value)) { throw new Exception("ValidateObject failed"); } return pair.value; } catch (Exception e) { // object cannot be activated or is invalid synchronized(this) { _numActive--; notifyAll(); } try { _factory.destroyObject(pair.value); } catch (Exception e2) { // cannot destroy broken object } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } }
throw e;
if (e instanceof Exception) { throw (Exception) e; } else if (e instanceof Error) { throw (Error) e; } else { throw new Exception(e); }
public Object borrowObject() throws Exception { long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { ObjectTimestampPair pair = null; synchronized(this) { assertOpen(); // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(_pool.removeFirst()); } catch(NoSuchElementException e) { ; /* ignored */ } // otherwise if(null == pair) { // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) if(_maxActive < 0 || _numActive < _maxActive) { // allow new object to be created } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException("Pool exhausted"); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { wait(_maxWait); } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("WhenExhaustedAction property " + _whenExhaustedAction + " not recognized."); } } } _numActive++; } // end synchronized // create new object when needed if(null == pair) { try { Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); newlyCreated = true; } catch (Exception e) { // object cannot be created synchronized(this) { _numActive--; notifyAll(); } throw e; } } // activate & validate the object try { _factory.activateObject(pair.value); if(_testOnBorrow && !_factory.validateObject(pair.value)) { throw new Exception("ValidateObject failed"); } return pair.value; } catch (Exception e) { // object cannot be activated or is invalid synchronized(this) { _numActive--; notifyAll(); } try { _factory.destroyObject(pair.value); } catch (Exception e2) { // cannot destroy broken object } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } }
catch (Exception e2) {
catch (Throwable e2) {
public Object borrowObject() throws Exception { long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { ObjectTimestampPair pair = null; synchronized(this) { assertOpen(); // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(_pool.removeFirst()); } catch(NoSuchElementException e) { ; /* ignored */ } // otherwise if(null == pair) { // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) if(_maxActive < 0 || _numActive < _maxActive) { // allow new object to be created } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException("Pool exhausted"); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { wait(_maxWait); } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("WhenExhaustedAction property " + _whenExhaustedAction + " not recognized."); } } } _numActive++; } // end synchronized // create new object when needed if(null == pair) { try { Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); newlyCreated = true; } catch (Exception e) { // object cannot be created synchronized(this) { _numActive--; notifyAll(); } throw e; } } // activate & validate the object try { _factory.activateObject(pair.value); if(_testOnBorrow && !_factory.validateObject(pair.value)) { throw new Exception("ValidateObject failed"); } return pair.value; } catch (Exception e) { // object cannot be activated or is invalid synchronized(this) { _numActive--; notifyAll(); } try { _factory.destroyObject(pair.value); } catch (Exception e2) { // cannot destroy broken object } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } }
throw new NoSuchElementException();
throw new NoSuchElementException("Pool exhausted");
public Object borrowObject() throws Exception { long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { ObjectTimestampPair pair = null; synchronized(this) { assertOpen(); // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(_pool.removeFirst()); } catch(NoSuchElementException e) { ; /* ignored */ } // otherwise if(null == pair) { // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) if(_maxActive < 0 || _numActive < _maxActive) { // allow new object to be created } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { wait(_maxWait); } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } _numActive++; } // end synchronized // create new object when needed if(null == pair) { try { Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); newlyCreated = true; } catch (Exception e) { // object cannot be created synchronized(this) { _numActive--; notifyAll(); } throw e; } } // activate & validate the object try { _factory.activateObject(pair.value); if(_testOnBorrow && !_factory.validateObject(pair.value)) { throw new Exception("validateObject failed"); } return pair.value; } catch (Exception e) { // object cannot be activated or is invalid synchronized(this) { _numActive--; notifyAll(); } try { _factory.destroyObject(pair.value); } catch (Exception e2) { // cannot destroy broken object } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } }
throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized.");
throw new IllegalArgumentException("WhenExhaustedAction property " + _whenExhaustedAction + " not recognized.");
public Object borrowObject() throws Exception { long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { ObjectTimestampPair pair = null; synchronized(this) { assertOpen(); // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(_pool.removeFirst()); } catch(NoSuchElementException e) { ; /* ignored */ } // otherwise if(null == pair) { // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) if(_maxActive < 0 || _numActive < _maxActive) { // allow new object to be created } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { wait(_maxWait); } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } _numActive++; } // end synchronized // create new object when needed if(null == pair) { try { Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); newlyCreated = true; } catch (Exception e) { // object cannot be created synchronized(this) { _numActive--; notifyAll(); } throw e; } } // activate & validate the object try { _factory.activateObject(pair.value); if(_testOnBorrow && !_factory.validateObject(pair.value)) { throw new Exception("validateObject failed"); } return pair.value; } catch (Exception e) { // object cannot be activated or is invalid synchronized(this) { _numActive--; notifyAll(); } try { _factory.destroyObject(pair.value); } catch (Exception e2) { // cannot destroy broken object } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } }
throw new Exception("validateObject failed");
throw new Exception("ValidateObject failed");
public Object borrowObject() throws Exception { long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { ObjectTimestampPair pair = null; synchronized(this) { assertOpen(); // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(_pool.removeFirst()); } catch(NoSuchElementException e) { ; /* ignored */ } // otherwise if(null == pair) { // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) if(_maxActive < 0 || _numActive < _maxActive) { // allow new object to be created } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { wait(_maxWait); } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } _numActive++; } // end synchronized // create new object when needed if(null == pair) { try { Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); newlyCreated = true; } catch (Exception e) { // object cannot be created synchronized(this) { _numActive--; notifyAll(); } throw e; } } // activate & validate the object try { _factory.activateObject(pair.value); if(_testOnBorrow && !_factory.validateObject(pair.value)) { throw new Exception("validateObject failed"); } return pair.value; } catch (Exception e) { // object cannot be activated or is invalid synchronized(this) { _numActive--; notifyAll(); } try { _factory.destroyObject(pair.value); } catch (Exception e2) { // cannot destroy broken object } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } }
} else if(_testWhileIdle) {
} if(_testWhileIdle && removeObject == false) {
public synchronized void evict() throws Exception { assertOpen(); if(!_pool.isEmpty()) { ListIterator iter; if (evictLastIndex < 0) { iter = _pool.listIterator(_pool.size()); } else { iter = _pool.listIterator(evictLastIndex); } for(int i=0,m=getNumTests();i<m;i++) { if(!iter.hasPrevious()) { iter = _pool.listIterator(_pool.size()); } else { boolean removeObject = false; ObjectTimestampPair pair = (ObjectTimestampPair)(iter.previous()); long idleTimeMilis = System.currentTimeMillis() - pair.tstamp; if ((_minEvictableIdleTimeMillis > 0) && (idleTimeMilis > _minEvictableIdleTimeMillis)) { removeObject = true; } else if ((_softMinEvictableIdleTimeMillis > 0) && (idleTimeMilis > _softMinEvictableIdleTimeMillis) && (getNumIdle() > getMinIdle())) { removeObject = true; } else if(_testWhileIdle) { boolean active = false; try { _factory.activateObject(pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(pair.value)) { removeObject=true; } else { try { _factory.passivateObject(pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { iter.remove(); _factory.destroyObject(pair.value); } catch(Exception e) { ; // ignored } } } } evictLastIndex = iter.previousIndex(); // resume from here } // if !empty }
if (children.size() == 1 && children.get(0).getUserObject() != null) {
if (children.size() == 1 && children.get(0).getUserObject() instanceof Example) {
CodeTabSheet(final TabFolder tf, final Panel panel, final EventTabSheet eventTab) { super("Source Code"); final TextArea ta = new TextArea(); ta.getStyle().getFont().setFamily(Font.Family.MONOSPACE); ta.setPosition(GAP, GAP); addPropertyChangeListener(Main.SIZE_ARY, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent ev) { if (getInnerHeight() > 20 && getInnerWidth() > 20) { ta.setSize(getInnerWidth() - GAP * 2, getInnerHeight() - GAP * 2); } } }); tf.addPropertyChangeListener(TabFolder.PROPERTY_CURRENT_INDEX, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent ev) { if (((Integer)ev.getNewValue()) == tf.getChildren().indexOf(CodeTabSheet.this)) { List<Component> children = panel.getChildren(); if (!children.isEmpty()) { if (children.size() == 1 && children.get(0).getUserObject() != null) { Example example = (Example)children.get(0).getUserObject(); ta.setText(example.getSourceCode()); } else { StringBuilder sb = new StringBuilder(); for (int i = 0, cnt = children.size(); i < cnt; i++) { Component comp = children.get(i); if (comp instanceof RadioButton && i == 0) sb.append("RadioButton.Group rbg = new RadioButton.Group();\r\n"); String var = i == 0 ? "comp" : "comp" + i; getSourceCode(sb, var, comp, eventTab.getCheckedEventDetails()); if (comp instanceof RadioButton) sb.append("rbg.add(").append(var).append(");\r\n"); } ta.setText(sb.toString()); } } } } }); getChildren().add(ta); }
if (children.size() == 1 && children.get(0).getUserObject() != null) {
if (children.size() == 1 && children.get(0).getUserObject() instanceof Example) {
public void propertyChange(PropertyChangeEvent ev) { if (((Integer)ev.getNewValue()) == tf.getChildren().indexOf(CodeTabSheet.this)) { List<Component> children = panel.getChildren(); if (!children.isEmpty()) { if (children.size() == 1 && children.get(0).getUserObject() != null) { Example example = (Example)children.get(0).getUserObject(); ta.setText(example.getSourceCode()); } else { StringBuilder sb = new StringBuilder(); for (int i = 0, cnt = children.size(); i < cnt; i++) { Component comp = children.get(i); if (comp instanceof RadioButton && i == 0) sb.append("RadioButton.Group rbg = new RadioButton.Group();\r\n"); String var = i == 0 ? "comp" : "comp" + i; getSourceCode(sb, var, comp, eventTab.getCheckedEventDetails()); if (comp instanceof RadioButton) sb.append("rbg.add(").append(var).append(");\r\n"); } ta.setText(sb.toString()); } } } }
if (prop.isValidFor(comp)) {
if (prop.isValidFor(comp.getClass())) {
static void getSourceCode(StringBuilder sb, String var, Component comp, List<EventDetail> led) { String tab = " "; String compType = Main.getSimpleClassName(comp.getClass()); sb.append(compType).append(' ').append(var).append(" = new ").append(compType).append('('); boolean textComp = comp instanceof TextComponent; if (textComp) sb.append('"').append(((TextComponent)comp).getText()).append('"'); sb.append(");\r\n"); sb.append(var).append(".setBounds(") .append(Property.X.getValue(comp)).append(", ") .append(Property.Y.getValue(comp)).append(", ") .append(Property.WIDTH.getValue(comp)).append(", ") .append(Property.HEIGHT.getValue(comp)).append(");\r\n"); if (comp instanceof TabFolder) { for (TabSheet ts : ((TabFolder)comp).getChildren()) { sb.append(var).append(".getChildren().add(new TabSheet("); sb.append('"').append(ts.getText()).append('"'); if (ts.getImage().length() > 0) sb.append(", \"").append(ts.getImage()).append('"'); sb.append("));\r\n"); } } for (Property prop : Property.values()) { if (prop.isValidFor(comp)) { String name = prop.getName(); if (name == PROPERTY_X || name == PROPERTY_Y || name == PROPERTY_WIDTH || name == PROPERTY_HEIGHT) continue; if (textComp && name == PROPERTY_TEXT) continue; Object defaultValue = prop.getDefaultValue(comp); Object value = prop.getValue(comp); if (defaultValue == value || (defaultValue != null && defaultValue.equals(value)) || (value != null && value.equals(defaultValue))) continue; Class type = prop.getType(); sb.append(var).append('.'); if (prop.isStyleProperty()) { String styleGroup = Main.getSimpleClassName(prop.getObjectType()); String styleName = prop.getName().substring(styleGroup.length()); sb.append("getStyle().get").append(styleGroup).append("().set").append(styleName); } else { sb.append("set").append(Character.toUpperCase(prop.getName().charAt(0))).append(prop.getName().substring(1)); } sb.append('('); if (type == String.class) { sb.append('"').append(value).append('"'); } else if (type.isPrimitive()) { sb.append(value); } else { sb.append(Main.getSimpleClassName(type).replace('$', '.')).append('.').append(value.toString().toUpperCase()); } sb.append(");\r\n"); } } if (comp instanceof DropDownGridBox || comp instanceof GridBox) { sb.append("\r\n//ADD COLUMNS AND ROWS TO THE GRID, JAVA 5 MAY USE VARARG CONSTRUCTORS\r\n"); GridBox gb; String gbVar; if (comp instanceof DropDownGridBox) { gb = ((DropDownGridBox)comp).getComponent(); gbVar = "gb"; sb.append("GridBox ").append(gbVar).append(" = ").append(var).append(".getComponent();\r\n"); } else { gb = (GridBox)comp; gbVar = var; } final String colVar = "col"; sb.append("GridBox.Column ").append(colVar).append(";\r\n"); List<GridBox> genList = new ArrayList<GridBox>(); genList.add(gb); int gbVarNum = 0; while (genList.size() > 0) { if (gbVarNum != 0) { gbVar = "gb" + gbVarNum; sb.append("GridBox ").append(gbVar).append(" = ").append("new GridBox();\r\n"); } genGridBox(sb, genList, gbVar, colVar); gbVarNum++; } } else if (comp instanceof Tree || comp instanceof Menu) { String itemClass = comp instanceof Tree ? "Tree.Item" : "Menu.Item"; List<String> imgs = new ArrayList<String>(); String rootVar = "root"; sb.append("\r\n//ADD ITEMS TO THE HIERARCHY\r\n"); HierarchyComponent.Item root = ((HierarchyComponent)comp).getRootItem(); sb.append(itemClass).append(' ').append(rootVar).append(" = ").append(var).append(".getRootItem();\r\n"); if (root.getText().length() > 0) sb.append(rootVar).append(".setText(\"").append(root.getText()).append("\");\r\n"); if (root.getImage().length() > 0) sb.append(rootVar).append(".setImage(").append(getImageVar(imgs, root.getImage())).append(");\r\n"); if (root instanceof Tree.Item && ((Tree.Item)root).isExpanded()) sb.append(rootVar).append(".setExpanded(true);\r\n"); int itemNum = 1; if (root.hasChildren()) genBranch(itemClass, rootVar, sb, root, itemNum, imgs); for (int i = imgs.size(); --i >= 0;) { sb.insert(0, "String IMG" + (i + 1) + " = \"" + imgs.get(i) + "\";\r\n"); } } if (!led.isEmpty()) { for (EventDetail ed : led) { String ln = Main.getSimpleClassName(ed.listener); sb.append("\r\n"); sb.append(var).append(".add").append(ln).append('('); if (ed.subType != null) sb.append('"').append(ed.subType).append('"').append(", "); sb.append("new ").append(ln).append("() {\r\n"); sb.append(tab).append("public void ").append(ed.getMethodName()).append('(').append(Main.getSimpleClassName(ed.event)).append(" ev) {\r\n"); sb.append(tab).append(tab).append("//ADD CODE HERE TO HANDLE EVENT\r\n"); sb.append(tab).append("}\r\n"); sb.append("});\r\n"); } } }
return ((Reference)super.borrow()).get();
return ((LenderReference)super.borrow()).get();
public Object borrow() { return ((Reference)super.borrow()).get(); }
super.repay(new SoftReference(obj));
super.repay(new SoftLenderReference(obj));
public void repay(final Object obj) { super.repay(new SoftReference(obj)); }
this(factory,GenericObjectPool.DEFAULT_MAX_ACTIVE,GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION,GenericObjectPool.DEFAULT_MAX_WAIT,GenericObjectPool.DEFAULT_MAX_IDLE,GenericObjectPool.DEFAULT_TEST_ON_BORROW,GenericObjectPool.DEFAULT_TEST_ON_RETURN,GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN,GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,GenericObjectPool.DEFAULT_TEST_WHILE_IDLE);
this(factory,GenericObjectPool.DEFAULT_MAX_ACTIVE,GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION,GenericObjectPool.DEFAULT_MAX_WAIT,GenericObjectPool.DEFAULT_MAX_IDLE,GenericObjectPool.DEFAULT_MIN_IDLE,GenericObjectPool.DEFAULT_TEST_ON_BORROW,GenericObjectPool.DEFAULT_TEST_ON_RETURN,GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN,GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,GenericObjectPool.DEFAULT_TEST_WHILE_IDLE);
public GenericObjectPoolFactory(PoolableObjectFactory factory) { this(factory,GenericObjectPool.DEFAULT_MAX_ACTIVE,GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION,GenericObjectPool.DEFAULT_MAX_WAIT,GenericObjectPool.DEFAULT_MAX_IDLE,GenericObjectPool.DEFAULT_TEST_ON_BORROW,GenericObjectPool.DEFAULT_TEST_ON_RETURN,GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN,GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,GenericObjectPool.DEFAULT_TEST_WHILE_IDLE); }
return new GenericObjectPool(_factory,_maxActive,_whenExhaustedAction,_maxWait,_maxIdle,_testOnBorrow,_testOnReturn,_timeBetweenEvictionRunsMillis,_numTestsPerEvictionRun,_minEvictableIdleTimeMillis,_testWhileIdle);
return new GenericObjectPool(_factory,_maxActive,_whenExhaustedAction,_maxWait,_maxIdle,_minIdle,_testOnBorrow,_testOnReturn,_timeBetweenEvictionRunsMillis,_numTestsPerEvictionRun,_minEvictableIdleTimeMillis,_testWhileIdle);
public ObjectPool createPool() { return new GenericObjectPool(_factory,_maxActive,_whenExhaustedAction,_maxWait,_maxIdle,_testOnBorrow,_testOnReturn,_timeBetweenEvictionRunsMillis,_numTestsPerEvictionRun,_minEvictableIdleTimeMillis,_testWhileIdle); }
if(_maxActive > 0 && _numActive < _maxActive) {
if(_maxActive <= 0 || _numActive < _maxActive) {
public synchronized Object borrowObject() throws Exception { long starttime = System.currentTimeMillis(); for(;;) { ObjectTimestampPair pair = null; // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(_pool.removeFirst()); } catch(NoSuchElementException e) { /* ignored */ } // otherwise if(null == pair) { // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) if(_maxActive > 0 && _numActive < _maxActive) { Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { wait(_maxWait); } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } _factory.activateObject(pair.value); if(_testOnBorrow && !_factory.validateObject(pair.value)) { try { _factory.passivateObject(pair.value); } catch(Exception e) { ; // ignored, we're throwing it out anyway } _factory.destroyObject(pair.value); } else { _numActive++; return pair.value; } } }
if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object"); }
public synchronized Object borrowObject(Object key) throws Exception { long starttime = System.currentTimeMillis(); for(;;) { CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key,pool); _poolList.add(key); } ObjectTimestampPair pair = null; // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(pool.removeFirst()); if(null != pair) { _totalIdle--; } } catch(NoSuchElementException e) { /* ignored */ } // otherwise if(null == pair) { // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) int active = 0; Integer act = (Integer)(_activeMap.get(key)); if(null != act) { active = act.intValue(); } if(_maxActive <= 0 || active < _maxActive) { Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { wait(_maxWait); } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } _factory.activateObject(key,pair.value); if(_testOnBorrow && !_factory.validateObject(key,pair.value)) { _factory.destroyObject(key,pair.value); } else { Integer active = (Integer)(_activeMap.get(key)); if(null == active) { _activeMap.put(key,new Integer(1)); } else { _activeMap.put(key,new Integer(active.intValue() + 1)); } _totalActive++; return pair.value; } } }
_logger.info( "Intend to take the shortest path between: " + (String)_nextVertex.getUserDatum( LABEL_KEY ) + " ==> " + (String)e.getDest().getUserDatum( LABEL_KEY ) + " (from: " + (String)e.getSource().getUserDatum( LABEL_KEY ) + "), using " + _shortestPathToVertex.size() + " hops." );
_logger.info( "Intend to take the shortest path between: " + (String)_nextVertex.getUserDatum( LABEL_KEY ) + " and " + (String)e.getDest().getUserDatum( LABEL_KEY ) + " (from: " + (String)e.getSource().getUserDatum( LABEL_KEY ) + "), using " + _shortestPathToVertex.size() + " hops." );
private void executeMethod( boolean optimize ) throws FoundNoEdgeException { DirectedSparseEdge edge = null; Object[] outEdges = null; if ( _nextVertex.containsUserDatumKey( BACK_KEY ) && _history. size() >= 3 ) { Float probability = (Float)_nextVertex.getUserDatum( BACK_KEY ); int index = _radomGenerator.nextInt( 100 ); if ( index < ( probability.floatValue() * 100 ) ) { String str = (String)_history.removeLast(); _logger.debug( "Remove from history: " + str ); String nodeLabel = (String)_history.getLast(); _logger.debug( "Reversing a vertex. From: " + (String)_nextVertex.getUserDatum( LABEL_KEY ) + ", to: " + nodeLabel ); Object[] vertices = _graph.getVertices().toArray(); for ( int i = 0; i < vertices.length; i++ ) { DirectedSparseVertex vertex = (DirectedSparseVertex)vertices[ i ]; if ( nodeLabel == (String)vertex.getUserDatum( LABEL_KEY ) ) { try { _nextVertex = vertex; String label = "PressBackButton"; _logger.debug( "Invoke method for edge: \"" + label + "\"" ); invokeMethod( label ); label = nodeLabel; _logger.debug( "Invoke method for vertex: \"" + label + "\"" ); invokeMethod( label ); } catch( GoBackToPreviousVertexException e ) { throw new RuntimeException( "An GoBackToPreviousVertexException was thrown where it should not be thrown." ); } return; } } throw new RuntimeException( "An attempt was made to reverse to vertex: " + nodeLabel + ", and did not find it." ); } } _logger.debug( "Vertex = " + (String)_nextVertex.getUserDatum( LABEL_KEY ) ); outEdges = _nextVertex.getOutEdges().toArray(); _logger.debug( "Number of outgoing edges = " + outEdges.length ); outEdges = shuffle( outEdges ); if ( _shortestPathToVertex == null && _runUntilAllEdgesVisited == true ) { Vector unvisitedEdges = returnUnvisitedEdge(); if ( unvisitedEdges.size() == 0) { _logger.debug( "All edges has been visited!" ); return; } _logger.info( "Found " + unvisitedEdges.size() + " unvisited edges." ); Object[] shuffledList = shuffle( unvisitedEdges.toArray() ); DirectedSparseEdge e = (DirectedSparseEdge)shuffledList[ 0 ]; if ( e == null ) { throw new RuntimeException( "Found an empty edge!" ); } _logger.info( "Selecting edge: " + getCompleteEdgeName( e ) ); _shortestPathToVertex = new DijkstraShortestPath( _graph ).getPath( _nextVertex, e.getSource() ); _shortestPathToVertex.add( e ); _logger.info( "Intend to take the shortest path between: " + (String)_nextVertex.getUserDatum( LABEL_KEY ) + " ==> " + (String)e.getDest().getUserDatum( LABEL_KEY ) + " (from: " + (String)e.getSource().getUserDatum( LABEL_KEY ) + "), using " + _shortestPathToVertex.size() + " hops." ); String paths = ""; for (Iterator iter = _shortestPathToVertex.iterator(); iter.hasNext();) { DirectedSparseEdge item = (DirectedSparseEdge) iter.next(); paths += " ==> " + getCompleteEdgeName( item ); } _logger.info( paths ); } if ( _shortestPathToVertex != null && _shortestPathToVertex.size() > 0 ) { edge = (DirectedSparseEdge)_shortestPathToVertex.get( 0 ); _shortestPathToVertex.remove( 0 ); _logger.debug( "Removed edge: " + getCompleteEdgeName( edge ) + " from the shortest path list, " + _shortestPathToVertex.size() + " hops remaining." ); if ( _shortestPathToVertex.size() == 0 ) { _shortestPathToVertex = null; } } else if ( optimize ) { // Look for an edge that has not been visited yet. for ( int i = 0; i < outEdges.length; i++ ) { edge = (DirectedSparseEdge)outEdges[ i ]; Integer vistited = (Integer)edge.getUserDatum( VISITED_KEY ); if ( vistited.intValue() == 0 ) { if ( _rejectedEdge == edge ) { // This edge has been rejected, because some condition was not fullfilled. // Try with the next edge in the for-loop. // _rejectedEdge has to be set to null, because it can be valid next time. _rejectedEdge = null; } else { _logger.debug( "Found an edge which has not been visited yet: " + getCompleteEdgeName( edge ) ); break; } } edge = null; } if ( edge == null ) { _logger.debug( "All edges has been visited (" + outEdges.length + ")" ); edge = getWeightedEdge( _nextVertex ); } } else { edge = getWeightedEdge( _nextVertex ); } if ( edge == null ) { throw new RuntimeException( "Did not find any edge." ); } _logger.debug( "Edge = \"" + getCompleteEdgeName( edge ) + "\"" ); _prevVertex = _nextVertex; _nextVertex = (DirectedSparseVertex)edge.getDest(); try { String label = (String)edge.getUserDatum( LABEL_KEY ); _logger.debug( "Invoke method for edge: \"" + label + "\"" ); invokeMethod( label ); Integer vistited = (Integer)edge.getUserDatum( VISITED_KEY ); vistited = new Integer( vistited.intValue() + 1 ); edge.setUserDatum( VISITED_KEY, vistited, UserData.SHARED ); label = (String)edge.getDest().getUserDatum( LABEL_KEY ); _logger.debug( "Invoke method for vertex: \"" + label + "\"" ); invokeMethod( label ); vistited = (Integer)edge.getDest().getUserDatum( VISITED_KEY ); vistited = new Integer( vistited.intValue() + 1 ); edge.getDest().setUserDatum( VISITED_KEY, vistited, UserData.SHARED ); if ( ((String)edge.getDest().getUserDatum( LABEL_KEY )).equals( "Stop" ) ) { _logger.debug( "Clearing the history" ); _history.clear(); } if ( edge.containsUserDatumKey( NO_HISTORY ) == false ) { _logger.debug( "Add to history: " + getCompleteEdgeName( edge ) ); _history.add( (String)edge.getDest().getUserDatum( LABEL_KEY ) ); } } catch( GoBackToPreviousVertexException e ) { _logger.debug( "The edge: " + getCompleteEdgeName( edge ) + " can not be run due to unfullfilled conditions." ); _logger.debug( "Trying from vertex: " + (String)_prevVertex.getUserDatum( LABEL_KEY ) + " again." ); _rejectedEdge = edge; _nextVertex = _prevVertex; } }
String paths = "";
String paths = "The route is: ";
private void executeMethod( boolean optimize ) throws FoundNoEdgeException { DirectedSparseEdge edge = null; Object[] outEdges = null; if ( _nextVertex.containsUserDatumKey( BACK_KEY ) && _history. size() >= 3 ) { Float probability = (Float)_nextVertex.getUserDatum( BACK_KEY ); int index = _radomGenerator.nextInt( 100 ); if ( index < ( probability.floatValue() * 100 ) ) { String str = (String)_history.removeLast(); _logger.debug( "Remove from history: " + str ); String nodeLabel = (String)_history.getLast(); _logger.debug( "Reversing a vertex. From: " + (String)_nextVertex.getUserDatum( LABEL_KEY ) + ", to: " + nodeLabel ); Object[] vertices = _graph.getVertices().toArray(); for ( int i = 0; i < vertices.length; i++ ) { DirectedSparseVertex vertex = (DirectedSparseVertex)vertices[ i ]; if ( nodeLabel == (String)vertex.getUserDatum( LABEL_KEY ) ) { try { _nextVertex = vertex; String label = "PressBackButton"; _logger.debug( "Invoke method for edge: \"" + label + "\"" ); invokeMethod( label ); label = nodeLabel; _logger.debug( "Invoke method for vertex: \"" + label + "\"" ); invokeMethod( label ); } catch( GoBackToPreviousVertexException e ) { throw new RuntimeException( "An GoBackToPreviousVertexException was thrown where it should not be thrown." ); } return; } } throw new RuntimeException( "An attempt was made to reverse to vertex: " + nodeLabel + ", and did not find it." ); } } _logger.debug( "Vertex = " + (String)_nextVertex.getUserDatum( LABEL_KEY ) ); outEdges = _nextVertex.getOutEdges().toArray(); _logger.debug( "Number of outgoing edges = " + outEdges.length ); outEdges = shuffle( outEdges ); if ( _shortestPathToVertex == null && _runUntilAllEdgesVisited == true ) { Vector unvisitedEdges = returnUnvisitedEdge(); if ( unvisitedEdges.size() == 0) { _logger.debug( "All edges has been visited!" ); return; } _logger.info( "Found " + unvisitedEdges.size() + " unvisited edges." ); Object[] shuffledList = shuffle( unvisitedEdges.toArray() ); DirectedSparseEdge e = (DirectedSparseEdge)shuffledList[ 0 ]; if ( e == null ) { throw new RuntimeException( "Found an empty edge!" ); } _logger.info( "Selecting edge: " + getCompleteEdgeName( e ) ); _shortestPathToVertex = new DijkstraShortestPath( _graph ).getPath( _nextVertex, e.getSource() ); _shortestPathToVertex.add( e ); _logger.info( "Intend to take the shortest path between: " + (String)_nextVertex.getUserDatum( LABEL_KEY ) + " ==> " + (String)e.getDest().getUserDatum( LABEL_KEY ) + " (from: " + (String)e.getSource().getUserDatum( LABEL_KEY ) + "), using " + _shortestPathToVertex.size() + " hops." ); String paths = ""; for (Iterator iter = _shortestPathToVertex.iterator(); iter.hasNext();) { DirectedSparseEdge item = (DirectedSparseEdge) iter.next(); paths += " ==> " + getCompleteEdgeName( item ); } _logger.info( paths ); } if ( _shortestPathToVertex != null && _shortestPathToVertex.size() > 0 ) { edge = (DirectedSparseEdge)_shortestPathToVertex.get( 0 ); _shortestPathToVertex.remove( 0 ); _logger.debug( "Removed edge: " + getCompleteEdgeName( edge ) + " from the shortest path list, " + _shortestPathToVertex.size() + " hops remaining." ); if ( _shortestPathToVertex.size() == 0 ) { _shortestPathToVertex = null; } } else if ( optimize ) { // Look for an edge that has not been visited yet. for ( int i = 0; i < outEdges.length; i++ ) { edge = (DirectedSparseEdge)outEdges[ i ]; Integer vistited = (Integer)edge.getUserDatum( VISITED_KEY ); if ( vistited.intValue() == 0 ) { if ( _rejectedEdge == edge ) { // This edge has been rejected, because some condition was not fullfilled. // Try with the next edge in the for-loop. // _rejectedEdge has to be set to null, because it can be valid next time. _rejectedEdge = null; } else { _logger.debug( "Found an edge which has not been visited yet: " + getCompleteEdgeName( edge ) ); break; } } edge = null; } if ( edge == null ) { _logger.debug( "All edges has been visited (" + outEdges.length + ")" ); edge = getWeightedEdge( _nextVertex ); } } else { edge = getWeightedEdge( _nextVertex ); } if ( edge == null ) { throw new RuntimeException( "Did not find any edge." ); } _logger.debug( "Edge = \"" + getCompleteEdgeName( edge ) + "\"" ); _prevVertex = _nextVertex; _nextVertex = (DirectedSparseVertex)edge.getDest(); try { String label = (String)edge.getUserDatum( LABEL_KEY ); _logger.debug( "Invoke method for edge: \"" + label + "\"" ); invokeMethod( label ); Integer vistited = (Integer)edge.getUserDatum( VISITED_KEY ); vistited = new Integer( vistited.intValue() + 1 ); edge.setUserDatum( VISITED_KEY, vistited, UserData.SHARED ); label = (String)edge.getDest().getUserDatum( LABEL_KEY ); _logger.debug( "Invoke method for vertex: \"" + label + "\"" ); invokeMethod( label ); vistited = (Integer)edge.getDest().getUserDatum( VISITED_KEY ); vistited = new Integer( vistited.intValue() + 1 ); edge.getDest().setUserDatum( VISITED_KEY, vistited, UserData.SHARED ); if ( ((String)edge.getDest().getUserDatum( LABEL_KEY )).equals( "Stop" ) ) { _logger.debug( "Clearing the history" ); _history.clear(); } if ( edge.containsUserDatumKey( NO_HISTORY ) == false ) { _logger.debug( "Add to history: " + getCompleteEdgeName( edge ) ); _history.add( (String)edge.getDest().getUserDatum( LABEL_KEY ) ); } } catch( GoBackToPreviousVertexException e ) { _logger.debug( "The edge: " + getCompleteEdgeName( edge ) + " can not be run due to unfullfilled conditions." ); _logger.debug( "Trying from vertex: " + (String)_prevVertex.getUserDatum( LABEL_KEY ) + " again." ); _rejectedEdge = edge; _nextVertex = _prevVertex; } }
paths += " ==> " + getCompleteEdgeName( item );
paths += getCompleteEdgeName( item ) + " ==> ";
private void executeMethod( boolean optimize ) throws FoundNoEdgeException { DirectedSparseEdge edge = null; Object[] outEdges = null; if ( _nextVertex.containsUserDatumKey( BACK_KEY ) && _history. size() >= 3 ) { Float probability = (Float)_nextVertex.getUserDatum( BACK_KEY ); int index = _radomGenerator.nextInt( 100 ); if ( index < ( probability.floatValue() * 100 ) ) { String str = (String)_history.removeLast(); _logger.debug( "Remove from history: " + str ); String nodeLabel = (String)_history.getLast(); _logger.debug( "Reversing a vertex. From: " + (String)_nextVertex.getUserDatum( LABEL_KEY ) + ", to: " + nodeLabel ); Object[] vertices = _graph.getVertices().toArray(); for ( int i = 0; i < vertices.length; i++ ) { DirectedSparseVertex vertex = (DirectedSparseVertex)vertices[ i ]; if ( nodeLabel == (String)vertex.getUserDatum( LABEL_KEY ) ) { try { _nextVertex = vertex; String label = "PressBackButton"; _logger.debug( "Invoke method for edge: \"" + label + "\"" ); invokeMethod( label ); label = nodeLabel; _logger.debug( "Invoke method for vertex: \"" + label + "\"" ); invokeMethod( label ); } catch( GoBackToPreviousVertexException e ) { throw new RuntimeException( "An GoBackToPreviousVertexException was thrown where it should not be thrown." ); } return; } } throw new RuntimeException( "An attempt was made to reverse to vertex: " + nodeLabel + ", and did not find it." ); } } _logger.debug( "Vertex = " + (String)_nextVertex.getUserDatum( LABEL_KEY ) ); outEdges = _nextVertex.getOutEdges().toArray(); _logger.debug( "Number of outgoing edges = " + outEdges.length ); outEdges = shuffle( outEdges ); if ( _shortestPathToVertex == null && _runUntilAllEdgesVisited == true ) { Vector unvisitedEdges = returnUnvisitedEdge(); if ( unvisitedEdges.size() == 0) { _logger.debug( "All edges has been visited!" ); return; } _logger.info( "Found " + unvisitedEdges.size() + " unvisited edges." ); Object[] shuffledList = shuffle( unvisitedEdges.toArray() ); DirectedSparseEdge e = (DirectedSparseEdge)shuffledList[ 0 ]; if ( e == null ) { throw new RuntimeException( "Found an empty edge!" ); } _logger.info( "Selecting edge: " + getCompleteEdgeName( e ) ); _shortestPathToVertex = new DijkstraShortestPath( _graph ).getPath( _nextVertex, e.getSource() ); _shortestPathToVertex.add( e ); _logger.info( "Intend to take the shortest path between: " + (String)_nextVertex.getUserDatum( LABEL_KEY ) + " ==> " + (String)e.getDest().getUserDatum( LABEL_KEY ) + " (from: " + (String)e.getSource().getUserDatum( LABEL_KEY ) + "), using " + _shortestPathToVertex.size() + " hops." ); String paths = ""; for (Iterator iter = _shortestPathToVertex.iterator(); iter.hasNext();) { DirectedSparseEdge item = (DirectedSparseEdge) iter.next(); paths += " ==> " + getCompleteEdgeName( item ); } _logger.info( paths ); } if ( _shortestPathToVertex != null && _shortestPathToVertex.size() > 0 ) { edge = (DirectedSparseEdge)_shortestPathToVertex.get( 0 ); _shortestPathToVertex.remove( 0 ); _logger.debug( "Removed edge: " + getCompleteEdgeName( edge ) + " from the shortest path list, " + _shortestPathToVertex.size() + " hops remaining." ); if ( _shortestPathToVertex.size() == 0 ) { _shortestPathToVertex = null; } } else if ( optimize ) { // Look for an edge that has not been visited yet. for ( int i = 0; i < outEdges.length; i++ ) { edge = (DirectedSparseEdge)outEdges[ i ]; Integer vistited = (Integer)edge.getUserDatum( VISITED_KEY ); if ( vistited.intValue() == 0 ) { if ( _rejectedEdge == edge ) { // This edge has been rejected, because some condition was not fullfilled. // Try with the next edge in the for-loop. // _rejectedEdge has to be set to null, because it can be valid next time. _rejectedEdge = null; } else { _logger.debug( "Found an edge which has not been visited yet: " + getCompleteEdgeName( edge ) ); break; } } edge = null; } if ( edge == null ) { _logger.debug( "All edges has been visited (" + outEdges.length + ")" ); edge = getWeightedEdge( _nextVertex ); } } else { edge = getWeightedEdge( _nextVertex ); } if ( edge == null ) { throw new RuntimeException( "Did not find any edge." ); } _logger.debug( "Edge = \"" + getCompleteEdgeName( edge ) + "\"" ); _prevVertex = _nextVertex; _nextVertex = (DirectedSparseVertex)edge.getDest(); try { String label = (String)edge.getUserDatum( LABEL_KEY ); _logger.debug( "Invoke method for edge: \"" + label + "\"" ); invokeMethod( label ); Integer vistited = (Integer)edge.getUserDatum( VISITED_KEY ); vistited = new Integer( vistited.intValue() + 1 ); edge.setUserDatum( VISITED_KEY, vistited, UserData.SHARED ); label = (String)edge.getDest().getUserDatum( LABEL_KEY ); _logger.debug( "Invoke method for vertex: \"" + label + "\"" ); invokeMethod( label ); vistited = (Integer)edge.getDest().getUserDatum( VISITED_KEY ); vistited = new Integer( vistited.intValue() + 1 ); edge.getDest().setUserDatum( VISITED_KEY, vistited, UserData.SHARED ); if ( ((String)edge.getDest().getUserDatum( LABEL_KEY )).equals( "Stop" ) ) { _logger.debug( "Clearing the history" ); _history.clear(); } if ( edge.containsUserDatumKey( NO_HISTORY ) == false ) { _logger.debug( "Add to history: " + getCompleteEdgeName( edge ) ); _history.add( (String)edge.getDest().getUserDatum( LABEL_KEY ) ); } } catch( GoBackToPreviousVertexException e ) { _logger.debug( "The edge: " + getCompleteEdgeName( edge ) + " can not be run due to unfullfilled conditions." ); _logger.debug( "Trying from vertex: " + (String)_prevVertex.getUserDatum( LABEL_KEY ) + " again." ); _rejectedEdge = edge; _nextVertex = _prevVertex; } }
paths += " Done!";
private void executeMethod( boolean optimize ) throws FoundNoEdgeException { DirectedSparseEdge edge = null; Object[] outEdges = null; if ( _nextVertex.containsUserDatumKey( BACK_KEY ) && _history. size() >= 3 ) { Float probability = (Float)_nextVertex.getUserDatum( BACK_KEY ); int index = _radomGenerator.nextInt( 100 ); if ( index < ( probability.floatValue() * 100 ) ) { String str = (String)_history.removeLast(); _logger.debug( "Remove from history: " + str ); String nodeLabel = (String)_history.getLast(); _logger.debug( "Reversing a vertex. From: " + (String)_nextVertex.getUserDatum( LABEL_KEY ) + ", to: " + nodeLabel ); Object[] vertices = _graph.getVertices().toArray(); for ( int i = 0; i < vertices.length; i++ ) { DirectedSparseVertex vertex = (DirectedSparseVertex)vertices[ i ]; if ( nodeLabel == (String)vertex.getUserDatum( LABEL_KEY ) ) { try { _nextVertex = vertex; String label = "PressBackButton"; _logger.debug( "Invoke method for edge: \"" + label + "\"" ); invokeMethod( label ); label = nodeLabel; _logger.debug( "Invoke method for vertex: \"" + label + "\"" ); invokeMethod( label ); } catch( GoBackToPreviousVertexException e ) { throw new RuntimeException( "An GoBackToPreviousVertexException was thrown where it should not be thrown." ); } return; } } throw new RuntimeException( "An attempt was made to reverse to vertex: " + nodeLabel + ", and did not find it." ); } } _logger.debug( "Vertex = " + (String)_nextVertex.getUserDatum( LABEL_KEY ) ); outEdges = _nextVertex.getOutEdges().toArray(); _logger.debug( "Number of outgoing edges = " + outEdges.length ); outEdges = shuffle( outEdges ); if ( _shortestPathToVertex == null && _runUntilAllEdgesVisited == true ) { Vector unvisitedEdges = returnUnvisitedEdge(); if ( unvisitedEdges.size() == 0) { _logger.debug( "All edges has been visited!" ); return; } _logger.info( "Found " + unvisitedEdges.size() + " unvisited edges." ); Object[] shuffledList = shuffle( unvisitedEdges.toArray() ); DirectedSparseEdge e = (DirectedSparseEdge)shuffledList[ 0 ]; if ( e == null ) { throw new RuntimeException( "Found an empty edge!" ); } _logger.info( "Selecting edge: " + getCompleteEdgeName( e ) ); _shortestPathToVertex = new DijkstraShortestPath( _graph ).getPath( _nextVertex, e.getSource() ); _shortestPathToVertex.add( e ); _logger.info( "Intend to take the shortest path between: " + (String)_nextVertex.getUserDatum( LABEL_KEY ) + " ==> " + (String)e.getDest().getUserDatum( LABEL_KEY ) + " (from: " + (String)e.getSource().getUserDatum( LABEL_KEY ) + "), using " + _shortestPathToVertex.size() + " hops." ); String paths = ""; for (Iterator iter = _shortestPathToVertex.iterator(); iter.hasNext();) { DirectedSparseEdge item = (DirectedSparseEdge) iter.next(); paths += " ==> " + getCompleteEdgeName( item ); } _logger.info( paths ); } if ( _shortestPathToVertex != null && _shortestPathToVertex.size() > 0 ) { edge = (DirectedSparseEdge)_shortestPathToVertex.get( 0 ); _shortestPathToVertex.remove( 0 ); _logger.debug( "Removed edge: " + getCompleteEdgeName( edge ) + " from the shortest path list, " + _shortestPathToVertex.size() + " hops remaining." ); if ( _shortestPathToVertex.size() == 0 ) { _shortestPathToVertex = null; } } else if ( optimize ) { // Look for an edge that has not been visited yet. for ( int i = 0; i < outEdges.length; i++ ) { edge = (DirectedSparseEdge)outEdges[ i ]; Integer vistited = (Integer)edge.getUserDatum( VISITED_KEY ); if ( vistited.intValue() == 0 ) { if ( _rejectedEdge == edge ) { // This edge has been rejected, because some condition was not fullfilled. // Try with the next edge in the for-loop. // _rejectedEdge has to be set to null, because it can be valid next time. _rejectedEdge = null; } else { _logger.debug( "Found an edge which has not been visited yet: " + getCompleteEdgeName( edge ) ); break; } } edge = null; } if ( edge == null ) { _logger.debug( "All edges has been visited (" + outEdges.length + ")" ); edge = getWeightedEdge( _nextVertex ); } } else { edge = getWeightedEdge( _nextVertex ); } if ( edge == null ) { throw new RuntimeException( "Did not find any edge." ); } _logger.debug( "Edge = \"" + getCompleteEdgeName( edge ) + "\"" ); _prevVertex = _nextVertex; _nextVertex = (DirectedSparseVertex)edge.getDest(); try { String label = (String)edge.getUserDatum( LABEL_KEY ); _logger.debug( "Invoke method for edge: \"" + label + "\"" ); invokeMethod( label ); Integer vistited = (Integer)edge.getUserDatum( VISITED_KEY ); vistited = new Integer( vistited.intValue() + 1 ); edge.setUserDatum( VISITED_KEY, vistited, UserData.SHARED ); label = (String)edge.getDest().getUserDatum( LABEL_KEY ); _logger.debug( "Invoke method for vertex: \"" + label + "\"" ); invokeMethod( label ); vistited = (Integer)edge.getDest().getUserDatum( VISITED_KEY ); vistited = new Integer( vistited.intValue() + 1 ); edge.getDest().setUserDatum( VISITED_KEY, vistited, UserData.SHARED ); if ( ((String)edge.getDest().getUserDatum( LABEL_KEY )).equals( "Stop" ) ) { _logger.debug( "Clearing the history" ); _history.clear(); } if ( edge.containsUserDatumKey( NO_HISTORY ) == false ) { _logger.debug( "Add to history: " + getCompleteEdgeName( edge ) ); _history.add( (String)edge.getDest().getUserDatum( LABEL_KEY ) ); } } catch( GoBackToPreviousVertexException e ) { _logger.debug( "The edge: " + getCompleteEdgeName( edge ) + " can not be run due to unfullfilled conditions." ); _logger.debug( "Trying from vertex: " + (String)_prevVertex.getUserDatum( LABEL_KEY ) + " again." ); _rejectedEdge = edge; _nextVertex = _prevVertex; } }
private void parseFile( String fileName )
private SparseGraph parseFile( String fileName )
private void parseFile( String fileName ) { try { _logger.info( "Parsing file: " + fileName ); _doc = _parser.build( fileName ); // Parse all vertices (nodes) Iterator iter = _doc.getDescendants( new ElementFilter( "node" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; if ( element.getAttributeValue( "yfiles.foldertype" ) != null ) { _logger.debug( "Excluded node: " + element.getAttributeValue( "yfiles.foldertype" ) ); continue; } _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "NodeLabel" ) ); while ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { Element nodeLabel = (Element)o2; _logger.debug( "Full name: " + nodeLabel.getQualifiedName() ); _logger.debug( "Name: " + nodeLabel.getTextTrim() ); DirectedSparseVertex v = (DirectedSparseVertex) _graph.addVertex( new DirectedSparseVertex() ); v.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); v.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); v.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); String str = nodeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label; if ( m.find( )) { label = m.group( 1 ); v.addUserDatum( LABEL_KEY, label, UserData.SHARED ); } else { throw new RuntimeException( "Label must be defined." ); } _logger.debug( "Added node: " + v.getUserDatum( LABEL_KEY ) ); // If no merge is defined, find it... // If defined, it means that when merging graphs, this specific vertex will not be merged. p = Pattern.compile( "(no merge)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { v.addUserDatum( NO_MERGE, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found no merge for edge: " + label ); } // NOTE: Only for html applications // In browsers, the usage of the 'Back'-button can be used. // If defined, with a value value, which depicts the probability for the edge // to be executed, tha back-button will be pressed in the browser. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(back=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find( ) ) { Float probability; String value = m.group( 2 ); try { probability = Float.valueOf( value.trim() ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", back is not a correct float value: " + error.toString() ); } v.addUserDatum( BACK_KEY, probability, UserData.SHARED ); } } } } } Object[] vertices = _graph.getVertices().toArray(); // Parse all edges (arrows or transtitions) iter = _doc.getDescendants( new ElementFilter( "edge" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "EdgeLabel" ) ); Element edgeLabel = null; if ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { edgeLabel = (Element)o2; _logger.debug( "Full name: " + edgeLabel.getQualifiedName() ); _logger.debug( "Name: " + edgeLabel.getTextTrim() ); } } _logger.debug( "source: " + element.getAttributeValue( "source" ) ); _logger.debug( "target: " + element.getAttributeValue( "target" ) ); DirectedSparseVertex source = null; DirectedSparseVertex dest = null; for ( int i = 0; i < vertices.length; i++ ) { DirectedSparseVertex vertex = (DirectedSparseVertex)vertices[ i ]; // Find source vertex if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "source" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { source = vertex; } if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "target" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { dest = vertex; } } if ( source == null ) { String msg = "Could not find starting node for edge. Name: " + element.getAttributeValue( "source" ); _logger.error( msg ); throw new RuntimeException( msg ); } if ( dest == null ) { String msg = "Could not find end node for edge. Name: " + element.getAttributeValue( "target" ); _logger.error( msg ); throw new RuntimeException( msg ); } DirectedSparseEdge e = new DirectedSparseEdge( source, dest ); _graph.addEdge( e ); e.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); e.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); if ( edgeLabel != null ) { String str = edgeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label = null; if ( m.find() ) { label = m.group( 1 ); e.addUserDatum( LABEL_KEY, label, UserData.SHARED ); _logger.debug( "Found label= " + label + " for edge id: " + edgeLabel.getQualifiedName() ); } else { throw new RuntimeException( "Label for edge must be defined." ); } // If weight is defined, find it... // weight must be associated with a value, which depicts the probability for the edge // to be executed. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(weight=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { Float weight; String value = m.group( 2 ); try { weight = Float.valueOf( value.trim() ); _logger.debug( "Found weight= " + weight + " for edge: " + label ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", weight is not a correct float value: " + error.toString() ); } e.addUserDatum( WEIGHT_KEY, weight, UserData.SHARED ); } // If No_history is defined, find it... // If defined, it means that when executing this edge, it shall not // be added to the history list of passed edgses. p = Pattern.compile( "(No_history)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { e.addUserDatum( NO_HISTORY, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found No_history for edge: " + label ); } // If condition used defined, find it... p = Pattern.compile( "(if: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); HashMap conditions = null; while ( m.find( ) ) { if ( conditions == null ) { conditions = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); conditions.put( variable, state ); _logger.debug( "Condition: " + variable + " = " + state ); } if ( conditions != null ) { e.addUserDatum( CONDITION_KEY, conditions, UserData.SHARED ); } // If state are defined, find them... HashMap states = null; p = Pattern.compile( "(state: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( states == null ) { states = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); states.put( variable, state ); _logger.debug( "State: " + variable + " = " + state ); } if ( states != null ) { e.addUserDatum( STATE_KEY, states, UserData.SHARED ); } // If string variables are defined, find them... HashMap variables = null; p = Pattern.compile( "(string: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); String variable = m.group( 3 ); variables.put( variableLabel, variable ); _logger.debug( "String variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(integer: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Integer variable = Integer.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Integer variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(float: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Float variable = Float.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Float variable: " + variableLabel + " = " + variable ); } if ( variables != null ) { e.addUserDatum( VARIABLE_KEY, variables, UserData.SHARED ); } } e.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); _logger.debug( "Adderade edge: \"" + e.getUserDatum( LABEL_KEY ) + "\"" ); } } } catch ( JDOMException e ) { _logger.error( e ); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } catch ( IOException e ) { e.printStackTrace(); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } }
DirectedSparseVertex v = (DirectedSparseVertex) _graph.addVertex( new DirectedSparseVertex() );
DirectedSparseVertex v = (DirectedSparseVertex) graph.addVertex( new DirectedSparseVertex() );
private void parseFile( String fileName ) { try { _logger.info( "Parsing file: " + fileName ); _doc = _parser.build( fileName ); // Parse all vertices (nodes) Iterator iter = _doc.getDescendants( new ElementFilter( "node" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; if ( element.getAttributeValue( "yfiles.foldertype" ) != null ) { _logger.debug( "Excluded node: " + element.getAttributeValue( "yfiles.foldertype" ) ); continue; } _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "NodeLabel" ) ); while ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { Element nodeLabel = (Element)o2; _logger.debug( "Full name: " + nodeLabel.getQualifiedName() ); _logger.debug( "Name: " + nodeLabel.getTextTrim() ); DirectedSparseVertex v = (DirectedSparseVertex) _graph.addVertex( new DirectedSparseVertex() ); v.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); v.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); v.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); String str = nodeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label; if ( m.find( )) { label = m.group( 1 ); v.addUserDatum( LABEL_KEY, label, UserData.SHARED ); } else { throw new RuntimeException( "Label must be defined." ); } _logger.debug( "Added node: " + v.getUserDatum( LABEL_KEY ) ); // If no merge is defined, find it... // If defined, it means that when merging graphs, this specific vertex will not be merged. p = Pattern.compile( "(no merge)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { v.addUserDatum( NO_MERGE, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found no merge for edge: " + label ); } // NOTE: Only for html applications // In browsers, the usage of the 'Back'-button can be used. // If defined, with a value value, which depicts the probability for the edge // to be executed, tha back-button will be pressed in the browser. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(back=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find( ) ) { Float probability; String value = m.group( 2 ); try { probability = Float.valueOf( value.trim() ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", back is not a correct float value: " + error.toString() ); } v.addUserDatum( BACK_KEY, probability, UserData.SHARED ); } } } } } Object[] vertices = _graph.getVertices().toArray(); // Parse all edges (arrows or transtitions) iter = _doc.getDescendants( new ElementFilter( "edge" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "EdgeLabel" ) ); Element edgeLabel = null; if ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { edgeLabel = (Element)o2; _logger.debug( "Full name: " + edgeLabel.getQualifiedName() ); _logger.debug( "Name: " + edgeLabel.getTextTrim() ); } } _logger.debug( "source: " + element.getAttributeValue( "source" ) ); _logger.debug( "target: " + element.getAttributeValue( "target" ) ); DirectedSparseVertex source = null; DirectedSparseVertex dest = null; for ( int i = 0; i < vertices.length; i++ ) { DirectedSparseVertex vertex = (DirectedSparseVertex)vertices[ i ]; // Find source vertex if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "source" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { source = vertex; } if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "target" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { dest = vertex; } } if ( source == null ) { String msg = "Could not find starting node for edge. Name: " + element.getAttributeValue( "source" ); _logger.error( msg ); throw new RuntimeException( msg ); } if ( dest == null ) { String msg = "Could not find end node for edge. Name: " + element.getAttributeValue( "target" ); _logger.error( msg ); throw new RuntimeException( msg ); } DirectedSparseEdge e = new DirectedSparseEdge( source, dest ); _graph.addEdge( e ); e.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); e.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); if ( edgeLabel != null ) { String str = edgeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label = null; if ( m.find() ) { label = m.group( 1 ); e.addUserDatum( LABEL_KEY, label, UserData.SHARED ); _logger.debug( "Found label= " + label + " for edge id: " + edgeLabel.getQualifiedName() ); } else { throw new RuntimeException( "Label for edge must be defined." ); } // If weight is defined, find it... // weight must be associated with a value, which depicts the probability for the edge // to be executed. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(weight=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { Float weight; String value = m.group( 2 ); try { weight = Float.valueOf( value.trim() ); _logger.debug( "Found weight= " + weight + " for edge: " + label ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", weight is not a correct float value: " + error.toString() ); } e.addUserDatum( WEIGHT_KEY, weight, UserData.SHARED ); } // If No_history is defined, find it... // If defined, it means that when executing this edge, it shall not // be added to the history list of passed edgses. p = Pattern.compile( "(No_history)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { e.addUserDatum( NO_HISTORY, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found No_history for edge: " + label ); } // If condition used defined, find it... p = Pattern.compile( "(if: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); HashMap conditions = null; while ( m.find( ) ) { if ( conditions == null ) { conditions = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); conditions.put( variable, state ); _logger.debug( "Condition: " + variable + " = " + state ); } if ( conditions != null ) { e.addUserDatum( CONDITION_KEY, conditions, UserData.SHARED ); } // If state are defined, find them... HashMap states = null; p = Pattern.compile( "(state: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( states == null ) { states = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); states.put( variable, state ); _logger.debug( "State: " + variable + " = " + state ); } if ( states != null ) { e.addUserDatum( STATE_KEY, states, UserData.SHARED ); } // If string variables are defined, find them... HashMap variables = null; p = Pattern.compile( "(string: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); String variable = m.group( 3 ); variables.put( variableLabel, variable ); _logger.debug( "String variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(integer: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Integer variable = Integer.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Integer variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(float: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Float variable = Float.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Float variable: " + variableLabel + " = " + variable ); } if ( variables != null ) { e.addUserDatum( VARIABLE_KEY, variables, UserData.SHARED ); } } e.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); _logger.debug( "Adderade edge: \"" + e.getUserDatum( LABEL_KEY ) + "\"" ); } } } catch ( JDOMException e ) { _logger.error( e ); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } catch ( IOException e ) { e.printStackTrace(); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } }
p = Pattern.compile( "(no merge)", Pattern.MULTILINE );
p = Pattern.compile( "(NO_MERGE)", Pattern.MULTILINE );
private void parseFile( String fileName ) { try { _logger.info( "Parsing file: " + fileName ); _doc = _parser.build( fileName ); // Parse all vertices (nodes) Iterator iter = _doc.getDescendants( new ElementFilter( "node" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; if ( element.getAttributeValue( "yfiles.foldertype" ) != null ) { _logger.debug( "Excluded node: " + element.getAttributeValue( "yfiles.foldertype" ) ); continue; } _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "NodeLabel" ) ); while ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { Element nodeLabel = (Element)o2; _logger.debug( "Full name: " + nodeLabel.getQualifiedName() ); _logger.debug( "Name: " + nodeLabel.getTextTrim() ); DirectedSparseVertex v = (DirectedSparseVertex) _graph.addVertex( new DirectedSparseVertex() ); v.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); v.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); v.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); String str = nodeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label; if ( m.find( )) { label = m.group( 1 ); v.addUserDatum( LABEL_KEY, label, UserData.SHARED ); } else { throw new RuntimeException( "Label must be defined." ); } _logger.debug( "Added node: " + v.getUserDatum( LABEL_KEY ) ); // If no merge is defined, find it... // If defined, it means that when merging graphs, this specific vertex will not be merged. p = Pattern.compile( "(no merge)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { v.addUserDatum( NO_MERGE, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found no merge for edge: " + label ); } // NOTE: Only for html applications // In browsers, the usage of the 'Back'-button can be used. // If defined, with a value value, which depicts the probability for the edge // to be executed, tha back-button will be pressed in the browser. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(back=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find( ) ) { Float probability; String value = m.group( 2 ); try { probability = Float.valueOf( value.trim() ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", back is not a correct float value: " + error.toString() ); } v.addUserDatum( BACK_KEY, probability, UserData.SHARED ); } } } } } Object[] vertices = _graph.getVertices().toArray(); // Parse all edges (arrows or transtitions) iter = _doc.getDescendants( new ElementFilter( "edge" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "EdgeLabel" ) ); Element edgeLabel = null; if ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { edgeLabel = (Element)o2; _logger.debug( "Full name: " + edgeLabel.getQualifiedName() ); _logger.debug( "Name: " + edgeLabel.getTextTrim() ); } } _logger.debug( "source: " + element.getAttributeValue( "source" ) ); _logger.debug( "target: " + element.getAttributeValue( "target" ) ); DirectedSparseVertex source = null; DirectedSparseVertex dest = null; for ( int i = 0; i < vertices.length; i++ ) { DirectedSparseVertex vertex = (DirectedSparseVertex)vertices[ i ]; // Find source vertex if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "source" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { source = vertex; } if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "target" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { dest = vertex; } } if ( source == null ) { String msg = "Could not find starting node for edge. Name: " + element.getAttributeValue( "source" ); _logger.error( msg ); throw new RuntimeException( msg ); } if ( dest == null ) { String msg = "Could not find end node for edge. Name: " + element.getAttributeValue( "target" ); _logger.error( msg ); throw new RuntimeException( msg ); } DirectedSparseEdge e = new DirectedSparseEdge( source, dest ); _graph.addEdge( e ); e.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); e.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); if ( edgeLabel != null ) { String str = edgeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label = null; if ( m.find() ) { label = m.group( 1 ); e.addUserDatum( LABEL_KEY, label, UserData.SHARED ); _logger.debug( "Found label= " + label + " for edge id: " + edgeLabel.getQualifiedName() ); } else { throw new RuntimeException( "Label for edge must be defined." ); } // If weight is defined, find it... // weight must be associated with a value, which depicts the probability for the edge // to be executed. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(weight=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { Float weight; String value = m.group( 2 ); try { weight = Float.valueOf( value.trim() ); _logger.debug( "Found weight= " + weight + " for edge: " + label ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", weight is not a correct float value: " + error.toString() ); } e.addUserDatum( WEIGHT_KEY, weight, UserData.SHARED ); } // If No_history is defined, find it... // If defined, it means that when executing this edge, it shall not // be added to the history list of passed edgses. p = Pattern.compile( "(No_history)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { e.addUserDatum( NO_HISTORY, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found No_history for edge: " + label ); } // If condition used defined, find it... p = Pattern.compile( "(if: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); HashMap conditions = null; while ( m.find( ) ) { if ( conditions == null ) { conditions = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); conditions.put( variable, state ); _logger.debug( "Condition: " + variable + " = " + state ); } if ( conditions != null ) { e.addUserDatum( CONDITION_KEY, conditions, UserData.SHARED ); } // If state are defined, find them... HashMap states = null; p = Pattern.compile( "(state: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( states == null ) { states = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); states.put( variable, state ); _logger.debug( "State: " + variable + " = " + state ); } if ( states != null ) { e.addUserDatum( STATE_KEY, states, UserData.SHARED ); } // If string variables are defined, find them... HashMap variables = null; p = Pattern.compile( "(string: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); String variable = m.group( 3 ); variables.put( variableLabel, variable ); _logger.debug( "String variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(integer: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Integer variable = Integer.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Integer variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(float: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Float variable = Float.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Float variable: " + variableLabel + " = " + variable ); } if ( variables != null ) { e.addUserDatum( VARIABLE_KEY, variables, UserData.SHARED ); } } e.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); _logger.debug( "Adderade edge: \"" + e.getUserDatum( LABEL_KEY ) + "\"" ); } } } catch ( JDOMException e ) { _logger.error( e ); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } catch ( IOException e ) { e.printStackTrace(); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } }
_logger.debug( "Found no merge for edge: " + label );
_logger.debug( "Found NO_MERGE for edge: " + label );
private void parseFile( String fileName ) { try { _logger.info( "Parsing file: " + fileName ); _doc = _parser.build( fileName ); // Parse all vertices (nodes) Iterator iter = _doc.getDescendants( new ElementFilter( "node" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; if ( element.getAttributeValue( "yfiles.foldertype" ) != null ) { _logger.debug( "Excluded node: " + element.getAttributeValue( "yfiles.foldertype" ) ); continue; } _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "NodeLabel" ) ); while ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { Element nodeLabel = (Element)o2; _logger.debug( "Full name: " + nodeLabel.getQualifiedName() ); _logger.debug( "Name: " + nodeLabel.getTextTrim() ); DirectedSparseVertex v = (DirectedSparseVertex) _graph.addVertex( new DirectedSparseVertex() ); v.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); v.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); v.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); String str = nodeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label; if ( m.find( )) { label = m.group( 1 ); v.addUserDatum( LABEL_KEY, label, UserData.SHARED ); } else { throw new RuntimeException( "Label must be defined." ); } _logger.debug( "Added node: " + v.getUserDatum( LABEL_KEY ) ); // If no merge is defined, find it... // If defined, it means that when merging graphs, this specific vertex will not be merged. p = Pattern.compile( "(no merge)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { v.addUserDatum( NO_MERGE, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found no merge for edge: " + label ); } // NOTE: Only for html applications // In browsers, the usage of the 'Back'-button can be used. // If defined, with a value value, which depicts the probability for the edge // to be executed, tha back-button will be pressed in the browser. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(back=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find( ) ) { Float probability; String value = m.group( 2 ); try { probability = Float.valueOf( value.trim() ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", back is not a correct float value: " + error.toString() ); } v.addUserDatum( BACK_KEY, probability, UserData.SHARED ); } } } } } Object[] vertices = _graph.getVertices().toArray(); // Parse all edges (arrows or transtitions) iter = _doc.getDescendants( new ElementFilter( "edge" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "EdgeLabel" ) ); Element edgeLabel = null; if ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { edgeLabel = (Element)o2; _logger.debug( "Full name: " + edgeLabel.getQualifiedName() ); _logger.debug( "Name: " + edgeLabel.getTextTrim() ); } } _logger.debug( "source: " + element.getAttributeValue( "source" ) ); _logger.debug( "target: " + element.getAttributeValue( "target" ) ); DirectedSparseVertex source = null; DirectedSparseVertex dest = null; for ( int i = 0; i < vertices.length; i++ ) { DirectedSparseVertex vertex = (DirectedSparseVertex)vertices[ i ]; // Find source vertex if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "source" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { source = vertex; } if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "target" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { dest = vertex; } } if ( source == null ) { String msg = "Could not find starting node for edge. Name: " + element.getAttributeValue( "source" ); _logger.error( msg ); throw new RuntimeException( msg ); } if ( dest == null ) { String msg = "Could not find end node for edge. Name: " + element.getAttributeValue( "target" ); _logger.error( msg ); throw new RuntimeException( msg ); } DirectedSparseEdge e = new DirectedSparseEdge( source, dest ); _graph.addEdge( e ); e.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); e.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); if ( edgeLabel != null ) { String str = edgeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label = null; if ( m.find() ) { label = m.group( 1 ); e.addUserDatum( LABEL_KEY, label, UserData.SHARED ); _logger.debug( "Found label= " + label + " for edge id: " + edgeLabel.getQualifiedName() ); } else { throw new RuntimeException( "Label for edge must be defined." ); } // If weight is defined, find it... // weight must be associated with a value, which depicts the probability for the edge // to be executed. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(weight=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { Float weight; String value = m.group( 2 ); try { weight = Float.valueOf( value.trim() ); _logger.debug( "Found weight= " + weight + " for edge: " + label ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", weight is not a correct float value: " + error.toString() ); } e.addUserDatum( WEIGHT_KEY, weight, UserData.SHARED ); } // If No_history is defined, find it... // If defined, it means that when executing this edge, it shall not // be added to the history list of passed edgses. p = Pattern.compile( "(No_history)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { e.addUserDatum( NO_HISTORY, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found No_history for edge: " + label ); } // If condition used defined, find it... p = Pattern.compile( "(if: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); HashMap conditions = null; while ( m.find( ) ) { if ( conditions == null ) { conditions = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); conditions.put( variable, state ); _logger.debug( "Condition: " + variable + " = " + state ); } if ( conditions != null ) { e.addUserDatum( CONDITION_KEY, conditions, UserData.SHARED ); } // If state are defined, find them... HashMap states = null; p = Pattern.compile( "(state: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( states == null ) { states = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); states.put( variable, state ); _logger.debug( "State: " + variable + " = " + state ); } if ( states != null ) { e.addUserDatum( STATE_KEY, states, UserData.SHARED ); } // If string variables are defined, find them... HashMap variables = null; p = Pattern.compile( "(string: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); String variable = m.group( 3 ); variables.put( variableLabel, variable ); _logger.debug( "String variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(integer: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Integer variable = Integer.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Integer variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(float: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Float variable = Float.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Float variable: " + variableLabel + " = " + variable ); } if ( variables != null ) { e.addUserDatum( VARIABLE_KEY, variables, UserData.SHARED ); } } e.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); _logger.debug( "Adderade edge: \"" + e.getUserDatum( LABEL_KEY ) + "\"" ); } } } catch ( JDOMException e ) { _logger.error( e ); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } catch ( IOException e ) { e.printStackTrace(); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } }
Object[] vertices = _graph.getVertices().toArray();
Object[] vertices = graph.getVertices().toArray();
private void parseFile( String fileName ) { try { _logger.info( "Parsing file: " + fileName ); _doc = _parser.build( fileName ); // Parse all vertices (nodes) Iterator iter = _doc.getDescendants( new ElementFilter( "node" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; if ( element.getAttributeValue( "yfiles.foldertype" ) != null ) { _logger.debug( "Excluded node: " + element.getAttributeValue( "yfiles.foldertype" ) ); continue; } _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "NodeLabel" ) ); while ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { Element nodeLabel = (Element)o2; _logger.debug( "Full name: " + nodeLabel.getQualifiedName() ); _logger.debug( "Name: " + nodeLabel.getTextTrim() ); DirectedSparseVertex v = (DirectedSparseVertex) _graph.addVertex( new DirectedSparseVertex() ); v.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); v.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); v.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); String str = nodeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label; if ( m.find( )) { label = m.group( 1 ); v.addUserDatum( LABEL_KEY, label, UserData.SHARED ); } else { throw new RuntimeException( "Label must be defined." ); } _logger.debug( "Added node: " + v.getUserDatum( LABEL_KEY ) ); // If no merge is defined, find it... // If defined, it means that when merging graphs, this specific vertex will not be merged. p = Pattern.compile( "(no merge)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { v.addUserDatum( NO_MERGE, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found no merge for edge: " + label ); } // NOTE: Only for html applications // In browsers, the usage of the 'Back'-button can be used. // If defined, with a value value, which depicts the probability for the edge // to be executed, tha back-button will be pressed in the browser. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(back=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find( ) ) { Float probability; String value = m.group( 2 ); try { probability = Float.valueOf( value.trim() ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", back is not a correct float value: " + error.toString() ); } v.addUserDatum( BACK_KEY, probability, UserData.SHARED ); } } } } } Object[] vertices = _graph.getVertices().toArray(); // Parse all edges (arrows or transtitions) iter = _doc.getDescendants( new ElementFilter( "edge" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "EdgeLabel" ) ); Element edgeLabel = null; if ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { edgeLabel = (Element)o2; _logger.debug( "Full name: " + edgeLabel.getQualifiedName() ); _logger.debug( "Name: " + edgeLabel.getTextTrim() ); } } _logger.debug( "source: " + element.getAttributeValue( "source" ) ); _logger.debug( "target: " + element.getAttributeValue( "target" ) ); DirectedSparseVertex source = null; DirectedSparseVertex dest = null; for ( int i = 0; i < vertices.length; i++ ) { DirectedSparseVertex vertex = (DirectedSparseVertex)vertices[ i ]; // Find source vertex if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "source" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { source = vertex; } if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "target" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { dest = vertex; } } if ( source == null ) { String msg = "Could not find starting node for edge. Name: " + element.getAttributeValue( "source" ); _logger.error( msg ); throw new RuntimeException( msg ); } if ( dest == null ) { String msg = "Could not find end node for edge. Name: " + element.getAttributeValue( "target" ); _logger.error( msg ); throw new RuntimeException( msg ); } DirectedSparseEdge e = new DirectedSparseEdge( source, dest ); _graph.addEdge( e ); e.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); e.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); if ( edgeLabel != null ) { String str = edgeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label = null; if ( m.find() ) { label = m.group( 1 ); e.addUserDatum( LABEL_KEY, label, UserData.SHARED ); _logger.debug( "Found label= " + label + " for edge id: " + edgeLabel.getQualifiedName() ); } else { throw new RuntimeException( "Label for edge must be defined." ); } // If weight is defined, find it... // weight must be associated with a value, which depicts the probability for the edge // to be executed. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(weight=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { Float weight; String value = m.group( 2 ); try { weight = Float.valueOf( value.trim() ); _logger.debug( "Found weight= " + weight + " for edge: " + label ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", weight is not a correct float value: " + error.toString() ); } e.addUserDatum( WEIGHT_KEY, weight, UserData.SHARED ); } // If No_history is defined, find it... // If defined, it means that when executing this edge, it shall not // be added to the history list of passed edgses. p = Pattern.compile( "(No_history)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { e.addUserDatum( NO_HISTORY, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found No_history for edge: " + label ); } // If condition used defined, find it... p = Pattern.compile( "(if: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); HashMap conditions = null; while ( m.find( ) ) { if ( conditions == null ) { conditions = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); conditions.put( variable, state ); _logger.debug( "Condition: " + variable + " = " + state ); } if ( conditions != null ) { e.addUserDatum( CONDITION_KEY, conditions, UserData.SHARED ); } // If state are defined, find them... HashMap states = null; p = Pattern.compile( "(state: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( states == null ) { states = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); states.put( variable, state ); _logger.debug( "State: " + variable + " = " + state ); } if ( states != null ) { e.addUserDatum( STATE_KEY, states, UserData.SHARED ); } // If string variables are defined, find them... HashMap variables = null; p = Pattern.compile( "(string: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); String variable = m.group( 3 ); variables.put( variableLabel, variable ); _logger.debug( "String variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(integer: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Integer variable = Integer.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Integer variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(float: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Float variable = Float.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Float variable: " + variableLabel + " = " + variable ); } if ( variables != null ) { e.addUserDatum( VARIABLE_KEY, variables, UserData.SHARED ); } } e.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); _logger.debug( "Adderade edge: \"" + e.getUserDatum( LABEL_KEY ) + "\"" ); } } } catch ( JDOMException e ) { _logger.error( e ); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } catch ( IOException e ) { e.printStackTrace(); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } }
_graph.addEdge( e );
graph.addEdge( e );
private void parseFile( String fileName ) { try { _logger.info( "Parsing file: " + fileName ); _doc = _parser.build( fileName ); // Parse all vertices (nodes) Iterator iter = _doc.getDescendants( new ElementFilter( "node" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; if ( element.getAttributeValue( "yfiles.foldertype" ) != null ) { _logger.debug( "Excluded node: " + element.getAttributeValue( "yfiles.foldertype" ) ); continue; } _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "NodeLabel" ) ); while ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { Element nodeLabel = (Element)o2; _logger.debug( "Full name: " + nodeLabel.getQualifiedName() ); _logger.debug( "Name: " + nodeLabel.getTextTrim() ); DirectedSparseVertex v = (DirectedSparseVertex) _graph.addVertex( new DirectedSparseVertex() ); v.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); v.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); v.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); String str = nodeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label; if ( m.find( )) { label = m.group( 1 ); v.addUserDatum( LABEL_KEY, label, UserData.SHARED ); } else { throw new RuntimeException( "Label must be defined." ); } _logger.debug( "Added node: " + v.getUserDatum( LABEL_KEY ) ); // If no merge is defined, find it... // If defined, it means that when merging graphs, this specific vertex will not be merged. p = Pattern.compile( "(no merge)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { v.addUserDatum( NO_MERGE, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found no merge for edge: " + label ); } // NOTE: Only for html applications // In browsers, the usage of the 'Back'-button can be used. // If defined, with a value value, which depicts the probability for the edge // to be executed, tha back-button will be pressed in the browser. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(back=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find( ) ) { Float probability; String value = m.group( 2 ); try { probability = Float.valueOf( value.trim() ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", back is not a correct float value: " + error.toString() ); } v.addUserDatum( BACK_KEY, probability, UserData.SHARED ); } } } } } Object[] vertices = _graph.getVertices().toArray(); // Parse all edges (arrows or transtitions) iter = _doc.getDescendants( new ElementFilter( "edge" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "EdgeLabel" ) ); Element edgeLabel = null; if ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { edgeLabel = (Element)o2; _logger.debug( "Full name: " + edgeLabel.getQualifiedName() ); _logger.debug( "Name: " + edgeLabel.getTextTrim() ); } } _logger.debug( "source: " + element.getAttributeValue( "source" ) ); _logger.debug( "target: " + element.getAttributeValue( "target" ) ); DirectedSparseVertex source = null; DirectedSparseVertex dest = null; for ( int i = 0; i < vertices.length; i++ ) { DirectedSparseVertex vertex = (DirectedSparseVertex)vertices[ i ]; // Find source vertex if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "source" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { source = vertex; } if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "target" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { dest = vertex; } } if ( source == null ) { String msg = "Could not find starting node for edge. Name: " + element.getAttributeValue( "source" ); _logger.error( msg ); throw new RuntimeException( msg ); } if ( dest == null ) { String msg = "Could not find end node for edge. Name: " + element.getAttributeValue( "target" ); _logger.error( msg ); throw new RuntimeException( msg ); } DirectedSparseEdge e = new DirectedSparseEdge( source, dest ); _graph.addEdge( e ); e.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); e.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); if ( edgeLabel != null ) { String str = edgeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label = null; if ( m.find() ) { label = m.group( 1 ); e.addUserDatum( LABEL_KEY, label, UserData.SHARED ); _logger.debug( "Found label= " + label + " for edge id: " + edgeLabel.getQualifiedName() ); } else { throw new RuntimeException( "Label for edge must be defined." ); } // If weight is defined, find it... // weight must be associated with a value, which depicts the probability for the edge // to be executed. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(weight=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { Float weight; String value = m.group( 2 ); try { weight = Float.valueOf( value.trim() ); _logger.debug( "Found weight= " + weight + " for edge: " + label ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", weight is not a correct float value: " + error.toString() ); } e.addUserDatum( WEIGHT_KEY, weight, UserData.SHARED ); } // If No_history is defined, find it... // If defined, it means that when executing this edge, it shall not // be added to the history list of passed edgses. p = Pattern.compile( "(No_history)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { e.addUserDatum( NO_HISTORY, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found No_history for edge: " + label ); } // If condition used defined, find it... p = Pattern.compile( "(if: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); HashMap conditions = null; while ( m.find( ) ) { if ( conditions == null ) { conditions = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); conditions.put( variable, state ); _logger.debug( "Condition: " + variable + " = " + state ); } if ( conditions != null ) { e.addUserDatum( CONDITION_KEY, conditions, UserData.SHARED ); } // If state are defined, find them... HashMap states = null; p = Pattern.compile( "(state: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( states == null ) { states = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); states.put( variable, state ); _logger.debug( "State: " + variable + " = " + state ); } if ( states != null ) { e.addUserDatum( STATE_KEY, states, UserData.SHARED ); } // If string variables are defined, find them... HashMap variables = null; p = Pattern.compile( "(string: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); String variable = m.group( 3 ); variables.put( variableLabel, variable ); _logger.debug( "String variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(integer: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Integer variable = Integer.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Integer variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(float: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Float variable = Float.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Float variable: " + variableLabel + " = " + variable ); } if ( variables != null ) { e.addUserDatum( VARIABLE_KEY, variables, UserData.SHARED ); } } e.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); _logger.debug( "Adderade edge: \"" + e.getUserDatum( LABEL_KEY ) + "\"" ); } } } catch ( JDOMException e ) { _logger.error( e ); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } catch ( IOException e ) { e.printStackTrace(); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } }
return graph;
private void parseFile( String fileName ) { try { _logger.info( "Parsing file: " + fileName ); _doc = _parser.build( fileName ); // Parse all vertices (nodes) Iterator iter = _doc.getDescendants( new ElementFilter( "node" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; if ( element.getAttributeValue( "yfiles.foldertype" ) != null ) { _logger.debug( "Excluded node: " + element.getAttributeValue( "yfiles.foldertype" ) ); continue; } _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "NodeLabel" ) ); while ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { Element nodeLabel = (Element)o2; _logger.debug( "Full name: " + nodeLabel.getQualifiedName() ); _logger.debug( "Name: " + nodeLabel.getTextTrim() ); DirectedSparseVertex v = (DirectedSparseVertex) _graph.addVertex( new DirectedSparseVertex() ); v.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); v.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); v.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); String str = nodeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label; if ( m.find( )) { label = m.group( 1 ); v.addUserDatum( LABEL_KEY, label, UserData.SHARED ); } else { throw new RuntimeException( "Label must be defined." ); } _logger.debug( "Added node: " + v.getUserDatum( LABEL_KEY ) ); // If no merge is defined, find it... // If defined, it means that when merging graphs, this specific vertex will not be merged. p = Pattern.compile( "(no merge)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { v.addUserDatum( NO_MERGE, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found no merge for edge: " + label ); } // NOTE: Only for html applications // In browsers, the usage of the 'Back'-button can be used. // If defined, with a value value, which depicts the probability for the edge // to be executed, tha back-button will be pressed in the browser. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(back=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find( ) ) { Float probability; String value = m.group( 2 ); try { probability = Float.valueOf( value.trim() ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", back is not a correct float value: " + error.toString() ); } v.addUserDatum( BACK_KEY, probability, UserData.SHARED ); } } } } } Object[] vertices = _graph.getVertices().toArray(); // Parse all edges (arrows or transtitions) iter = _doc.getDescendants( new ElementFilter( "edge" ) ); while ( iter.hasNext() ) { Object o = iter.next(); if ( o instanceof Element ) { Element element = (Element)o; _logger.debug( "id: " + element.getAttributeValue( "id" ) ); Iterator iter2 = element.getDescendants( new ElementFilter( "EdgeLabel" ) ); Element edgeLabel = null; if ( iter2.hasNext() ) { Object o2 = iter2.next(); if ( o2 instanceof Element ) { edgeLabel = (Element)o2; _logger.debug( "Full name: " + edgeLabel.getQualifiedName() ); _logger.debug( "Name: " + edgeLabel.getTextTrim() ); } } _logger.debug( "source: " + element.getAttributeValue( "source" ) ); _logger.debug( "target: " + element.getAttributeValue( "target" ) ); DirectedSparseVertex source = null; DirectedSparseVertex dest = null; for ( int i = 0; i < vertices.length; i++ ) { DirectedSparseVertex vertex = (DirectedSparseVertex)vertices[ i ]; // Find source vertex if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "source" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { source = vertex; } if ( vertex.getUserDatum( ID_KEY ).equals( element.getAttributeValue( "target" ) ) && vertex.getUserDatum( FILE_KEY ).equals( fileName ) ) { dest = vertex; } } if ( source == null ) { String msg = "Could not find starting node for edge. Name: " + element.getAttributeValue( "source" ); _logger.error( msg ); throw new RuntimeException( msg ); } if ( dest == null ) { String msg = "Could not find end node for edge. Name: " + element.getAttributeValue( "target" ); _logger.error( msg ); throw new RuntimeException( msg ); } DirectedSparseEdge e = new DirectedSparseEdge( source, dest ); _graph.addEdge( e ); e.addUserDatum( ID_KEY, element.getAttributeValue( "id" ), UserData.SHARED ); e.addUserDatum( FILE_KEY, fileName, UserData.SHARED ); if ( edgeLabel != null ) { String str = edgeLabel.getTextTrim(); Pattern p = Pattern.compile( "(.*)", Pattern.MULTILINE ); Matcher m = p.matcher( str ); String label = null; if ( m.find() ) { label = m.group( 1 ); e.addUserDatum( LABEL_KEY, label, UserData.SHARED ); _logger.debug( "Found label= " + label + " for edge id: " + edgeLabel.getQualifiedName() ); } else { throw new RuntimeException( "Label for edge must be defined." ); } // If weight is defined, find it... // weight must be associated with a value, which depicts the probability for the edge // to be executed. // A value of 0.05 is the same as 5% chance of going down this road. p = Pattern.compile( "(weight=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { Float weight; String value = m.group( 2 ); try { weight = Float.valueOf( value.trim() ); _logger.debug( "Found weight= " + weight + " for edge: " + label ); } catch ( NumberFormatException error ) { throw new RuntimeException( "For label: " + label + ", weight is not a correct float value: " + error.toString() ); } e.addUserDatum( WEIGHT_KEY, weight, UserData.SHARED ); } // If No_history is defined, find it... // If defined, it means that when executing this edge, it shall not // be added to the history list of passed edgses. p = Pattern.compile( "(No_history)", Pattern.MULTILINE ); m = p.matcher( str ); if ( m.find() ) { e.addUserDatum( NO_HISTORY, m.group( 1 ), UserData.SHARED ); _logger.debug( "Found No_history for edge: " + label ); } // If condition used defined, find it... p = Pattern.compile( "(if: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); HashMap conditions = null; while ( m.find( ) ) { if ( conditions == null ) { conditions = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); conditions.put( variable, state ); _logger.debug( "Condition: " + variable + " = " + state ); } if ( conditions != null ) { e.addUserDatum( CONDITION_KEY, conditions, UserData.SHARED ); } // If state are defined, find them... HashMap states = null; p = Pattern.compile( "(state: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( states == null ) { states = new HashMap(); } String variable = m.group( 2 ); Boolean state = Boolean.valueOf( m.group( 3 ) ); states.put( variable, state ); _logger.debug( "State: " + variable + " = " + state ); } if ( states != null ) { e.addUserDatum( STATE_KEY, states, UserData.SHARED ); } // If string variables are defined, find them... HashMap variables = null; p = Pattern.compile( "(string: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); String variable = m.group( 3 ); variables.put( variableLabel, variable ); _logger.debug( "String variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(integer: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Integer variable = Integer.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Integer variable: " + variableLabel + " = " + variable ); } // If integer variables are defined, find them... p = Pattern.compile( "(float: (.*)=(.*))", Pattern.MULTILINE ); m = p.matcher( str ); while ( m.find( ) ) { if ( variables == null ) { variables = new HashMap(); } String variableLabel = m.group( 2 ); Float variable = Float.valueOf( m.group( 3 ) ); variables.put( variableLabel, variable ); _logger.debug( "Float variable: " + variableLabel + " = " + variable ); } if ( variables != null ) { e.addUserDatum( VARIABLE_KEY, variables, UserData.SHARED ); } } e.addUserDatum( VISITED_KEY, new Integer( 0 ), UserData.SHARED ); _logger.debug( "Adderade edge: \"" + e.getUserDatum( LABEL_KEY ) + "\"" ); } } } catch ( JDOMException e ) { _logger.error( e ); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } catch ( IOException e ) { e.printStackTrace(); throw new RuntimeException( "Kunde inte skanna filen: " + fileName ); } }
parseFile( _graphmlFileName );
_graph = parseFile( _graphmlFileName );
private void readFiles() { File file = new File( _graphmlFileName ); if ( file.isFile() ) { parseFile( _graphmlFileName ); } else if ( file.isDirectory() ) { // Only accpets files which suffix is .graphml FilenameFilter filter = new FilenameFilter() { public boolean accept( File dir, String name ) { return name.endsWith( ".graphml" ); } }; File [] allChildren = file.listFiles( filter ); for ( int i = 0; i < allChildren.length; ++i ) { parseFile( allChildren[ i ].getAbsolutePath() ); } mergeVertices(); } else { throw new RuntimeException( "\"" + _graphmlFileName + "\" is not a file or a directory. Please specify a valid .graphml file or a directory containing .graphml files" ); } }
parseFile( allChildren[ i ].getAbsolutePath() );
_graphList.add( parseFile( allChildren[ i ].getAbsolutePath() ) );
private void readFiles() { File file = new File( _graphmlFileName ); if ( file.isFile() ) { parseFile( _graphmlFileName ); } else if ( file.isDirectory() ) { // Only accpets files which suffix is .graphml FilenameFilter filter = new FilenameFilter() { public boolean accept( File dir, String name ) { return name.endsWith( ".graphml" ); } }; File [] allChildren = file.listFiles( filter ); for ( int i = 0; i < allChildren.length; ++i ) { parseFile( allChildren[ i ].getAbsolutePath() ); } mergeVertices(); } else { throw new RuntimeException( "\"" + _graphmlFileName + "\" is not a file or a directory. Please specify a valid .graphml file or a directory containing .graphml files" ); } }
mergeVertices();
analyseSubGraphs();
private void readFiles() { File file = new File( _graphmlFileName ); if ( file.isFile() ) { parseFile( _graphmlFileName ); } else if ( file.isDirectory() ) { // Only accpets files which suffix is .graphml FilenameFilter filter = new FilenameFilter() { public boolean accept( File dir, String name ) { return name.endsWith( ".graphml" ); } }; File [] allChildren = file.listFiles( filter ); for ( int i = 0; i < allChildren.length; ++i ) { parseFile( allChildren[ i ].getAbsolutePath() ); } mergeVertices(); } else { throw new RuntimeException( "\"" + _graphmlFileName + "\" is not a file or a directory. Please specify a valid .graphml file or a directory containing .graphml files" ); } }
Indexer id = Indexer.getIndexer( _graph );
Indexer id = Indexer.getAndUpdateIndexer( _graph );
public void writeGraph( String mergedGraphml_ ) { StringBuffer sourceFile = new StringBuffer(); try { FileWriter file = new FileWriter( mergedGraphml_ ); sourceFile.append( "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" ); sourceFile.append( "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns/graphml\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns/graphml http://www.yworks.com/xml/schema/graphml/1.0/ygraphml.xsd\" xmlns:y=\"http://www.yworks.com/xml/graphml\">\n" ); sourceFile.append( " <key id=\"d0\" for=\"node\" yfiles.type=\"nodegraphics\"/>\n" ); sourceFile.append( " <key id=\"d1\" for=\"edge\" yfiles.type=\"edgegraphics\"/>\n" ); sourceFile.append( " <graph id=\"G\" edgedefault=\"directed\">\n" ); int numVertices = _graph.getVertices().size(); Indexer id = Indexer.getIndexer( _graph ); for ( int i = 0; i < numVertices; i++ ) { Vertex v = (Vertex) id.getVertex(i); int vId = i+1; sourceFile.append( " <node id=\"n" + vId + "\">\n" ); sourceFile.append( " <data key=\"d0\" >\n" ); sourceFile.append( " <y:ShapeNode >\n" ); sourceFile.append( " <y:Geometry x=\"241.875\" y=\"158.701171875\" width=\"95.0\" height=\"30.0\"/>\n" ); sourceFile.append( " <y:Fill color=\"#CCCCFF\" transparent=\"false\"/>\n" ); sourceFile.append( " <y:BorderStyle type=\"line\" width=\"1.0\" color=\"#000000\" />\n" ); sourceFile.append( " <y:NodeLabel x=\"1.5\" y=\"5.6494140625\" width=\"92.0\" height=\"18.701171875\" visible=\"true\" alignment=\"center\" fontFamily=\"Dialog\" fontSize=\"12\" fontStyle=\"plain\" textColor=\"#000000\" modelName=\"internal\" modelPosition=\"c\" autoSizePolicy=\"content\">" + v.getUserDatum( LABEL_KEY ) + "</y:NodeLabel>\n" ); sourceFile.append( " <y:Shape type=\"rectangle\"/>\n" ); sourceFile.append( " </y:ShapeNode>\n" ); sourceFile.append( " </data>\n" ); sourceFile.append( " </node>\n" ); } int i = 0; for ( Iterator edgeIterator = _graph.getEdges().iterator(); edgeIterator.hasNext(); ) { Edge e = (Edge) edgeIterator.next(); Pair p = e.getEndpoints(); Vertex src = (Vertex) p.getFirst(); Vertex dest = (Vertex) p.getSecond(); int srcId = id.getIndex(src)+1; int destId = id.getIndex(dest)+1; int nId = ++i; sourceFile.append( " <edge id=\"" + nId + "\" source=\"n" + srcId + "\" target=\"n" + destId + "\">\n" ); sourceFile.append( " <data key=\"d1\" >\n" ); sourceFile.append( " <y:PolyLineEdge >\n" ); sourceFile.append( " <y:Path sx=\"-23.75\" sy=\"15.0\" tx=\"-23.75\" ty=\"-15.0\">\n" ); sourceFile.append( " <y:Point x=\"273.3125\" y=\"95.0\"/>\n" ); sourceFile.append( " <y:Point x=\"209.5625\" y=\"95.0\"/>\n" ); sourceFile.append( " <y:Point x=\"209.5625\" y=\"143.701171875\"/>\n" ); sourceFile.append( " <y:Point x=\"265.625\" y=\"143.701171875\"/>\n" ); sourceFile.append( " </y:Path>\n" ); sourceFile.append( " <y:LineStyle type=\"line\" width=\"1.0\" color=\"#000000\" />\n" ); sourceFile.append( " <y:Arrows source=\"none\" target=\"standard\"/>\n" ); sourceFile.append( " <y:EdgeLabel x=\"-148.25\" y=\"30.000000000000014\" width=\"169.0\" height=\"18.701171875\" visible=\"true\" alignment=\"center\" fontFamily=\"Dialog\" fontSize=\"12\" fontStyle=\"plain\" textColor=\"#000000\" modelName=\"free\" modelPosition=\"anywhere\" preferredPlacement=\"on_edge\" distance=\"2.0\" ratio=\"0.5\">" + e.getUserDatum( LABEL_KEY ) + "</y:EdgeLabel>\n" ); sourceFile.append( " <y:BendStyle smoothed=\"false\"/>\n" ); sourceFile.append( " </y:PolyLineEdge>\n" ); sourceFile.append( " </data>\n" ); sourceFile.append( " </edge>\n" ); } sourceFile.append( " </graph>\n" ); sourceFile.append( "</graphml>\n" ); file.write( sourceFile.toString() ); file.flush(); _logger.info( "Wrote: " + mergedGraphml_ ); } catch (IOException e) { e.printStackTrace(); } }
protected KeyedObjectPool makeEmptyPool(int mincapacity) {
protected KeyedObjectPool makeEmptyPool(KeyedPoolableObjectFactory factory) {
protected KeyedObjectPool makeEmptyPool(int mincapacity) { if (this.getClass() != TestBaseKeyedObjectPool.class) { throw new AssertionError("Subclasses of TestBaseKeyedObjectPool must reimplement this method."); } throw new UnsupportedOperationException("BaseKeyedObjectPool isn't a complete implementation."); }
public synchronized void addObject() throws Exception {
public void addObject() throws Exception {
public synchronized void addObject() throws Exception { Object obj = _factory.makeObject(); _numActive++; // A little slimy - must do this because returnObject decrements it. this.returnObject(obj); }
_numActive++; this.returnObject(obj);
synchronized(this) { _numActive++; this.returnObject(obj); }
public synchronized void addObject() throws Exception { Object obj = _factory.makeObject(); _numActive++; // A little slimy - must do this because returnObject decrements it. this.returnObject(obj); }
public synchronized void clear(Object key) { LinkedList pool = (LinkedList)(_poolMap.remove(key)); if(null == pool) { return; } else { for(Iterator it = pool.iterator(); it.hasNext(); ) {
public synchronized void clear() { for(Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext(); ) { Object key = keyiter.next(); final LinkedList list = (LinkedList)(_poolMap.get(key)); for(Iterator it = list.iterator(); it.hasNext(); ) {
public synchronized void clear(Object key) { LinkedList pool = (LinkedList)(_poolMap.remove(key)); if(null == pool) { return; } else { for(Iterator it = pool.iterator(); it.hasNext(); ) { try { _factory.destroyObject(key,((ObjectTimestampPair)(it.next())).value); } catch(Exception e) { // ignore error, keep destroying the rest } it.remove(); _totalIdle--; } } notifyAll(); }
_totalIdle--;
public synchronized void clear(Object key) { LinkedList pool = (LinkedList)(_poolMap.remove(key)); if(null == pool) { return; } else { for(Iterator it = pool.iterator(); it.hasNext(); ) { try { _factory.destroyObject(key,((ObjectTimestampPair)(it.next())).value); } catch(Exception e) { // ignore error, keep destroying the rest } it.remove(); _totalIdle--; } } notifyAll(); }
_poolMap.clear(); if (_recentlyEvictedKeys != null) { _recentlyEvictedKeys.clear(); } _totalIdle = 0;
public synchronized void clear(Object key) { LinkedList pool = (LinkedList)(_poolMap.remove(key)); if(null == pool) { return; } else { for(Iterator it = pool.iterator(); it.hasNext(); ) { try { _factory.destroyObject(key,((ObjectTimestampPair)(it.next())).value); } catch(Exception e) { // ignore error, keep destroying the rest } it.remove(); _totalIdle--; } } notifyAll(); }
suite.addTest(org.apache.commons.pool.composite.TestAll.suite());
public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(org.apache.commons.pool.TestBaseObjectPool.suite()); suite.addTest(org.apache.commons.pool.TestBaseKeyedObjectPool.suite()); suite.addTest(org.apache.commons.pool.TestBasePoolableObjectFactory.suite()); suite.addTest(org.apache.commons.pool.TestBaseKeyedPoolableObjectFactory.suite()); suite.addTest(org.apache.commons.pool.TestPoolUtils.suite()); suite.addTest(org.apache.commons.pool.impl.TestAll.suite()); return suite; }
public void activateObject(Object obj) { }
public void activateObject(Object obj) throws Exception { if (exceptionOnActivate) { if (!(validateCounter++%2 == 0 ? evenValid : oddValid)) { throw new Exception(); } } }
public void activateObject(Object obj) { }
void setThrowExceptionOnPassivate(boolean bool) {
public void setThrowExceptionOnPassivate(boolean bool) {
void setThrowExceptionOnPassivate(boolean bool) { exceptionOnPassivate = bool; }
public boolean validateObject(Object obj) { return validateCounter++%2 == 0 ? evenValid : oddValid; }
public boolean validateObject(Object obj) { if (enableValidation) { return validateCounter++%2 == 0 ? evenValid : oddValid; } else { return true; } }
public boolean validateObject(Object obj) { return validateCounter++%2 == 0 ? evenValid : oddValid; }
assertNotNull(obj);
public void testSetFactoryWithActiveObjects() throws Exception { GenericObjectPool pool = new GenericObjectPool(); pool.setMaxIdle(10); pool.setFactory(new SimpleFactory()); Object obj = pool.borrowObject(); try { pool.setFactory(null); fail("Expected IllegalStateException"); } catch(IllegalStateException e) { // expected } try { pool.setFactory(new SimpleFactory()); fail("Expected IllegalStateException"); } catch(IllegalStateException e) { // expected } }
buf.append("Active: ").append(numActive()).append("\n"); buf.append("Idle: ").append(numIdle()).append("\n");
buf.append("Active: ").append(getNumActive()).append("\n"); buf.append("Idle: ").append(getNumIdle()).append("\n");
synchronized String debugInfo() { StringBuffer buf = new StringBuffer(); buf.append("Active: ").append(numActive()).append("\n"); buf.append("Idle: ").append(numIdle()).append("\n"); Iterator it = _poolList.iterator(); while(it.hasNext()) { buf.append("\t").append(_poolMap.get(it.next())).append("\n"); } return buf.toString(); }
public synchronized void returnObject(Object key, Object obj) throws Exception { _totalActive--;
public void returnObject(Object key, Object obj) throws Exception {
public synchronized void returnObject(Object key, Object obj) throws Exception { _totalActive--; CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key,pool); _poolList.add(key); } Integer active = (Integer)(_activeMap.get(key)); if(null == active) { // do nothing, either null or zero is OK } else if(active.intValue() <= 1) { _activeMap.remove(key); } else { _activeMap.put(key,new Integer(active.intValue() - 1)); } if(_maxIdle > 0 && (pool.size() >= _maxIdle || (_testOnReturn && !_factory.validateObject(key,obj)))) { try { _factory.passivateObject(key,obj); } catch(Exception e) { ; // ignored, we're throwing it out anyway } _factory.destroyObject(key,obj); } else { try { _factory.passivateObject(key,obj); pool.addFirst(new ObjectTimestampPair(obj)); _totalIdle++; } catch(Exception e) { _factory.destroyObject(key,obj); } } notifyAll(); }
CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key,pool); _poolList.add(key);
CursorableLinkedList pool = null; synchronized(this) { pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key, pool); _poolList.add(key); }
public synchronized void returnObject(Object key, Object obj) throws Exception { _totalActive--; CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key,pool); _poolList.add(key); } Integer active = (Integer)(_activeMap.get(key)); if(null == active) { // do nothing, either null or zero is OK } else if(active.intValue() <= 1) { _activeMap.remove(key); } else { _activeMap.put(key,new Integer(active.intValue() - 1)); } if(_maxIdle > 0 && (pool.size() >= _maxIdle || (_testOnReturn && !_factory.validateObject(key,obj)))) { try { _factory.passivateObject(key,obj); } catch(Exception e) { ; // ignored, we're throwing it out anyway } _factory.destroyObject(key,obj); } else { try { _factory.passivateObject(key,obj); pool.addFirst(new ObjectTimestampPair(obj)); _totalIdle++; } catch(Exception e) { _factory.destroyObject(key,obj); } } notifyAll(); }
Integer active = (Integer)(_activeMap.get(key)); if(null == active) { } else if(active.intValue() <= 1) { _activeMap.remove(key);
boolean success = true; if((_testOnReturn && !_factory.validateObject(key, obj))) { success = false; try { _factory.destroyObject(key, obj); } catch(Exception e) { }
public synchronized void returnObject(Object key, Object obj) throws Exception { _totalActive--; CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key,pool); _poolList.add(key); } Integer active = (Integer)(_activeMap.get(key)); if(null == active) { // do nothing, either null or zero is OK } else if(active.intValue() <= 1) { _activeMap.remove(key); } else { _activeMap.put(key,new Integer(active.intValue() - 1)); } if(_maxIdle > 0 && (pool.size() >= _maxIdle || (_testOnReturn && !_factory.validateObject(key,obj)))) { try { _factory.passivateObject(key,obj); } catch(Exception e) { ; // ignored, we're throwing it out anyway } _factory.destroyObject(key,obj); } else { try { _factory.passivateObject(key,obj); pool.addFirst(new ObjectTimestampPair(obj)); _totalIdle++; } catch(Exception e) { _factory.destroyObject(key,obj); } } notifyAll(); }
_activeMap.put(key,new Integer(active.intValue() - 1));
try { _factory.passivateObject(key, obj); } catch(Exception e) { success = false; }
public synchronized void returnObject(Object key, Object obj) throws Exception { _totalActive--; CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key,pool); _poolList.add(key); } Integer active = (Integer)(_activeMap.get(key)); if(null == active) { // do nothing, either null or zero is OK } else if(active.intValue() <= 1) { _activeMap.remove(key); } else { _activeMap.put(key,new Integer(active.intValue() - 1)); } if(_maxIdle > 0 && (pool.size() >= _maxIdle || (_testOnReturn && !_factory.validateObject(key,obj)))) { try { _factory.passivateObject(key,obj); } catch(Exception e) { ; // ignored, we're throwing it out anyway } _factory.destroyObject(key,obj); } else { try { _factory.passivateObject(key,obj); pool.addFirst(new ObjectTimestampPair(obj)); _totalIdle++; } catch(Exception e) { _factory.destroyObject(key,obj); } } notifyAll(); }
if(_maxIdle > 0 && (pool.size() >= _maxIdle || (_testOnReturn && !_factory.validateObject(key,obj)))) { try { _factory.passivateObject(key,obj); } catch(Exception e) { ;
boolean shouldDestroy = false; synchronized(this) { _totalActive--; Integer active = (Integer)(_activeMap.get(key)); if(null == active) { } else if(active.intValue() <= 1) { _activeMap.remove(key); } else { _activeMap.put(key, new Integer(active.intValue() - 1));
public synchronized void returnObject(Object key, Object obj) throws Exception { _totalActive--; CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key,pool); _poolList.add(key); } Integer active = (Integer)(_activeMap.get(key)); if(null == active) { // do nothing, either null or zero is OK } else if(active.intValue() <= 1) { _activeMap.remove(key); } else { _activeMap.put(key,new Integer(active.intValue() - 1)); } if(_maxIdle > 0 && (pool.size() >= _maxIdle || (_testOnReturn && !_factory.validateObject(key,obj)))) { try { _factory.passivateObject(key,obj); } catch(Exception e) { ; // ignored, we're throwing it out anyway } _factory.destroyObject(key,obj); } else { try { _factory.passivateObject(key,obj); pool.addFirst(new ObjectTimestampPair(obj)); _totalIdle++; } catch(Exception e) { _factory.destroyObject(key,obj); } } notifyAll(); }
_factory.destroyObject(key,obj); } else { try { _factory.passivateObject(key,obj);
if(_maxIdle > 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) {
public synchronized void returnObject(Object key, Object obj) throws Exception { _totalActive--; CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key,pool); _poolList.add(key); } Integer active = (Integer)(_activeMap.get(key)); if(null == active) { // do nothing, either null or zero is OK } else if(active.intValue() <= 1) { _activeMap.remove(key); } else { _activeMap.put(key,new Integer(active.intValue() - 1)); } if(_maxIdle > 0 && (pool.size() >= _maxIdle || (_testOnReturn && !_factory.validateObject(key,obj)))) { try { _factory.passivateObject(key,obj); } catch(Exception e) { ; // ignored, we're throwing it out anyway } _factory.destroyObject(key,obj); } else { try { _factory.passivateObject(key,obj); pool.addFirst(new ObjectTimestampPair(obj)); _totalIdle++; } catch(Exception e) { _factory.destroyObject(key,obj); } } notifyAll(); }
_factory.destroyObject(key,obj);
public synchronized void returnObject(Object key, Object obj) throws Exception { _totalActive--; CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key,pool); _poolList.add(key); } Integer active = (Integer)(_activeMap.get(key)); if(null == active) { // do nothing, either null or zero is OK } else if(active.intValue() <= 1) { _activeMap.remove(key); } else { _activeMap.put(key,new Integer(active.intValue() - 1)); } if(_maxIdle > 0 && (pool.size() >= _maxIdle || (_testOnReturn && !_factory.validateObject(key,obj)))) { try { _factory.passivateObject(key,obj); } catch(Exception e) { ; // ignored, we're throwing it out anyway } _factory.destroyObject(key,obj); } else { try { _factory.passivateObject(key,obj); pool.addFirst(new ObjectTimestampPair(obj)); _totalIdle++; } catch(Exception e) { _factory.destroyObject(key,obj); } } notifyAll(); }
notifyAll();
public synchronized void returnObject(Object key, Object obj) throws Exception { _totalActive--; CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key,pool); _poolList.add(key); } Integer active = (Integer)(_activeMap.get(key)); if(null == active) { // do nothing, either null or zero is OK } else if(active.intValue() <= 1) { _activeMap.remove(key); } else { _activeMap.put(key,new Integer(active.intValue() - 1)); } if(_maxIdle > 0 && (pool.size() >= _maxIdle || (_testOnReturn && !_factory.validateObject(key,obj)))) { try { _factory.passivateObject(key,obj); } catch(Exception e) { ; // ignored, we're throwing it out anyway } _factory.destroyObject(key,obj); } else { try { _factory.passivateObject(key,obj); pool.addFirst(new ObjectTimestampPair(obj)); _totalIdle++; } catch(Exception e) { _factory.destroyObject(key,obj); } } notifyAll(); }
return new GenericKeyedObjectPool(_factory,_maxActive,_whenExhaustedAction,_maxWait,_maxIdle,_maxTotal,_testOnBorrow,_testOnReturn,_timeBetweenEvictionRunsMillis,_numTestsPerEvictionRun,_minEvictableIdleTimeMillis,_testWhileIdle);
return new GenericKeyedObjectPool(_factory,_maxActive,_whenExhaustedAction,_maxWait,_maxIdle,_maxTotal,_minIdle,_testOnBorrow,_testOnReturn,_timeBetweenEvictionRunsMillis,_numTestsPerEvictionRun,_minEvictableIdleTimeMillis,_testWhileIdle);
public KeyedObjectPool createPool() { return new GenericKeyedObjectPool(_factory,_maxActive,_whenExhaustedAction,_maxWait,_maxIdle,_maxTotal,_testOnBorrow,_testOnReturn,_timeBetweenEvictionRunsMillis,_numTestsPerEvictionRun,_minEvictableIdleTimeMillis,_testWhileIdle); }
if (config.evictInvalidFrequencyMillis > 0 && config.evictIdleMillis > config.evictInvalidFrequencyMillis) {
if (config.evictInvalidFrequencyMillis > 0 && config.evictIdleMillis < config.evictInvalidFrequencyMillis) {
private static Lender getLender(final FactoryConfig config) { final BorrowPolicy borrowPolicy = config.borrowPolicy; Lender lender; if (config.maxIdle != 0) { if (BorrowPolicy.FIFO.equals(borrowPolicy)) { lender = new FifoLender(); } else if (BorrowPolicy.LIFO.equals(borrowPolicy)) { lender = new LifoLender(); } else if (BorrowPolicy.SOFT_FIFO.equals(borrowPolicy)) { lender = new SoftLender(new FifoLender()); } else if (BorrowPolicy.SOFT_LIFO.equals(borrowPolicy)) { lender = new SoftLender(new LifoLender()); } else if (BorrowPolicy.NULL.equals(borrowPolicy)) { lender = new NullLender(); } else { throw new IllegalStateException("No clue what this borrow type is: " + borrowPolicy); } } else { lender = new NullLender(); } // If the lender is a NullLender then there is no point to evicting idle objects that aren't there. if (!(lender instanceof NullLender)) { // If the evictIdleMillis were less than evictInvalidFrequencyMillis // then the InvalidEvictorLender would never run. if (config.evictInvalidFrequencyMillis > 0 && config.evictIdleMillis > config.evictInvalidFrequencyMillis) { lender = new InvalidEvictorLender(lender); ((InvalidEvictorLender)lender).setValidationFrequencyMillis(config.evictInvalidFrequencyMillis); } if (config.evictIdleMillis > 0) { lender = new IdleEvictorLender(lender); ((IdleEvictorLender)lender).setIdleTimeoutMillis(config.evictIdleMillis); } } return lender; }
if(System.currentTimeMillis() - pair.tstamp > _minEvictableIdleTimeMillis) { try { cursor.remove(); _factory.destroyObject(pair.value); } catch(Exception e) { ; }
if(_minEvictableIdleTimeMillis > 0 && System.currentTimeMillis() - pair.tstamp > _minEvictableIdleTimeMillis) { try { cursor.remove(); _factory.destroyObject(pair.value); } catch(Exception e) { ; }
public void run() { CursorableLinkedList.Cursor cursor = null; while(!_cancelled) { long sleeptime = 0L; synchronized(GenericObjectPool.this) { sleeptime = _timeBetweenEvictionRunsMillis; } try { Thread.currentThread().sleep(_timeBetweenEvictionRunsMillis); } catch(Exception e) { ; // ignored } try { synchronized(GenericObjectPool.this) { if(!_pool.isEmpty()) { if(null == cursor) { cursor = (CursorableLinkedList.Cursor)(_pool.cursor(_pool.size())); } else if(!cursor.hasPrevious()) { cursor.close(); cursor = (CursorableLinkedList.Cursor)(_pool.cursor(_pool.size())); } for(int i=0,m=getNumTests();i<m;i++) { if(!cursor.hasPrevious()) { cursor.close(); cursor = (CursorableLinkedList.Cursor)(_pool.cursor(_pool.size())); } else { ObjectTimestampPair pair = (ObjectTimestampPair)(cursor.previous()); if(System.currentTimeMillis() - pair.tstamp > _minEvictableIdleTimeMillis) { try { cursor.remove(); _factory.destroyObject(pair.value); } catch(Exception e) { ; // ignored } } else if(_testWhileIdle) { boolean active = false; try { _factory.activateObject(pair.value); active = true; } catch(Exception e) { cursor.remove(); try { _factory.passivateObject(pair.value); } catch(Exception ex) { ; // ignored } _factory.destroyObject(pair.value); } if(active) { if(!_factory.validateObject(pair.value)) { cursor.remove(); try { _factory.passivateObject(pair.value); } catch(Exception ex) { ; // ignored } _factory.destroyObject(pair.value); } else { try { _factory.passivateObject(pair.value); } catch(Exception e) { cursor.remove(); _factory.destroyObject(pair.value); } } } } } } } } } catch(Exception e) { // ignored } } if(null != cursor) { cursor.close(); } }
_factory.activateObject(pair.value); if(_testOnBorrow && !_factory.validateObject(pair.value)) { _factory.destroyObject(pair.value);
try { _factory.activateObject(pair.value); if(_testOnBorrow && !_factory.validateObject(pair.value)) { throw new Exception("validateObject failed"); } _numActive++; return pair.value; } catch (Exception e) { try { _factory.destroyObject(pair.value); } catch (Exception e2) { }
public synchronized Object borrowObject() throws Exception { assertOpen(); long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { ObjectTimestampPair pair = null; // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(_pool.removeFirst()); } catch(NoSuchElementException e) { ; /* ignored */ } // otherwise if(null == pair) { // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) if(_maxActive <= 0 || _numActive < _maxActive) { Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); newlyCreated = true; } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { wait(_maxWait); } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } _factory.activateObject(pair.value); if(_testOnBorrow && !_factory.validateObject(pair.value)) { _factory.destroyObject(pair.value); if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object"); } // else keep looping } else { _numActive++; return pair.value; } } }
} } else { _numActive++; return pair.value;
} else { continue; }
public synchronized Object borrowObject() throws Exception { assertOpen(); long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { ObjectTimestampPair pair = null; // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(_pool.removeFirst()); } catch(NoSuchElementException e) { ; /* ignored */ } // otherwise if(null == pair) { // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) if(_maxActive <= 0 || _numActive < _maxActive) { Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); newlyCreated = true; } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: Object obj = _factory.makeObject(); pair = new ObjectTimestampPair(obj); break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { wait(_maxWait); } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } _factory.activateObject(pair.value); if(_testOnBorrow && !_factory.validateObject(pair.value)) { _factory.destroyObject(pair.value); if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object"); } // else keep looping } else { _numActive++; return pair.value; } } }
while(!_cancelled) { try { Thread.sleep(_delay); } catch(Exception e) { } try { evict(); } catch(Exception e) { } try { ensureMinIdle(); } catch(Exception e) { }
try { evict(); } catch(Exception e) { } try { ensureMinIdle(); } catch(Exception e) {
public void run() { while(!_cancelled) { try { Thread.sleep(_delay); } catch(Exception e) { // ignored } try { evict(); } catch(Exception e) { // ignored } try { ensureMinIdle(); } catch(Exception e) { // ignored } } }
public SoftLenderReference(Object referent) {
SoftLenderReference(final Object referent) {
public SoftLenderReference(Object referent) { super(referent); }
LinkedList pool = (LinkedList) (_poolMap.get(key));
ObjectQueue pool = (ObjectQueue) (_poolMap.get(key));
public synchronized void addObject(Object key) throws Exception { assertOpen(); if (_factory == null) { throw new IllegalStateException("Cannot add objects without a factory."); } Object obj = _factory.makeObject(key); // if we need to validate this object, do so boolean success = true; // whether or not this object passed validation if(_testOnReturn && !_factory.validateObject(key, obj)) { success = false; _factory.destroyObject(key, obj); } else { _factory.passivateObject(key, obj); } boolean shouldDestroy = false; // grab the pool (list) of objects associated with the given key LinkedList pool = (LinkedList) (_poolMap.get(key)); // if it doesn't exist, create it if(null == pool) { pool = new LinkedList(); _poolMap.put(key, pool); } // if there's no space in the pool, flag the object for destruction // else if we passivated succesfully, return it to the pool if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) { pool.addLast(new ObjectTimestampPair(obj)); _totalIdle++; } notifyAll(); if(shouldDestroy) { _factory.destroyObject(key, obj); } }
pool = new LinkedList();
pool = new ObjectQueue();
public synchronized void addObject(Object key) throws Exception { assertOpen(); if (_factory == null) { throw new IllegalStateException("Cannot add objects without a factory."); } Object obj = _factory.makeObject(key); // if we need to validate this object, do so boolean success = true; // whether or not this object passed validation if(_testOnReturn && !_factory.validateObject(key, obj)) { success = false; _factory.destroyObject(key, obj); } else { _factory.passivateObject(key, obj); } boolean shouldDestroy = false; // grab the pool (list) of objects associated with the given key LinkedList pool = (LinkedList) (_poolMap.get(key)); // if it doesn't exist, create it if(null == pool) { pool = new LinkedList(); _poolMap.put(key, pool); } // if there's no space in the pool, flag the object for destruction // else if we passivated succesfully, return it to the pool if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) { pool.addLast(new ObjectTimestampPair(obj)); _totalIdle++; } notifyAll(); if(shouldDestroy) { _factory.destroyObject(key, obj); } }
if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) {
if(_maxIdle >= 0 && (pool.queue.size() >= _maxIdle)) {
public synchronized void addObject(Object key) throws Exception { assertOpen(); if (_factory == null) { throw new IllegalStateException("Cannot add objects without a factory."); } Object obj = _factory.makeObject(key); // if we need to validate this object, do so boolean success = true; // whether or not this object passed validation if(_testOnReturn && !_factory.validateObject(key, obj)) { success = false; _factory.destroyObject(key, obj); } else { _factory.passivateObject(key, obj); } boolean shouldDestroy = false; // grab the pool (list) of objects associated with the given key LinkedList pool = (LinkedList) (_poolMap.get(key)); // if it doesn't exist, create it if(null == pool) { pool = new LinkedList(); _poolMap.put(key, pool); } // if there's no space in the pool, flag the object for destruction // else if we passivated succesfully, return it to the pool if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) { pool.addLast(new ObjectTimestampPair(obj)); _totalIdle++; } notifyAll(); if(shouldDestroy) { _factory.destroyObject(key, obj); } }
pool.addLast(new ObjectTimestampPair(obj));
pool.queue.addLast(new ObjectTimestampPair(obj));
public synchronized void addObject(Object key) throws Exception { assertOpen(); if (_factory == null) { throw new IllegalStateException("Cannot add objects without a factory."); } Object obj = _factory.makeObject(key); // if we need to validate this object, do so boolean success = true; // whether or not this object passed validation if(_testOnReturn && !_factory.validateObject(key, obj)) { success = false; _factory.destroyObject(key, obj); } else { _factory.passivateObject(key, obj); } boolean shouldDestroy = false; // grab the pool (list) of objects associated with the given key LinkedList pool = (LinkedList) (_poolMap.get(key)); // if it doesn't exist, create it if(null == pool) { pool = new LinkedList(); _poolMap.put(key, pool); } // if there's no space in the pool, flag the object for destruction // else if we passivated succesfully, return it to the pool if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) { pool.addLast(new ObjectTimestampPair(obj)); _totalIdle++; } notifyAll(); if(shouldDestroy) { _factory.destroyObject(key, obj); } }
LinkedList pool = (LinkedList)(_poolMap.get(key));
ObjectQueue pool = (ObjectQueue)(_poolMap.get(key));
public synchronized Object borrowObject(Object key) throws Exception { assertOpen(); long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { LinkedList pool = (LinkedList)(_poolMap.get(key)); if(null == pool) { pool = new LinkedList(); _poolMap.put(key,pool); } ObjectTimestampPair pair = null; // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(pool.removeFirst()); if(null != pair) { _totalIdle--; } } catch(NoSuchElementException e) { /* ignored */ } // otherwise if(null == pair) { // if there is a totalMaxActive and we are at the limit then // we have to make room if ((_maxTotal > 0) && (_totalActive + _totalIdle >= _maxTotal)) { clearOldest(); } // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) int active = getActiveCount(key); if ((_maxActive < 0 || active < _maxActive) && (_maxTotal < 0 || _totalActive + _totalIdle < _maxTotal)) { Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); newlyCreated = true; } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = _maxWait - elapsed; if (waitTime > 0) { wait(waitTime); } } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } if (newlyCreated) { incrementActiveCount(key); return pair.value; } else { try { _factory.activateObject(key, pair.value); } catch (Exception e) { try { _factory.destroyObject(key,pair.value); } catch (Exception e2) { // swallowed } continue; } boolean invalid = true; try { invalid = _testOnBorrow && !_factory.validateObject(key, pair.value); } catch (Exception e) { // swallowed } if (invalid) { try { _factory.destroyObject(key,pair.value); } catch (Exception e) { // swallowed } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object"); } // else keep looping } else { incrementActiveCount(key); return pair.value; } } } }
pool = new LinkedList();
pool = new ObjectQueue();
public synchronized Object borrowObject(Object key) throws Exception { assertOpen(); long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { LinkedList pool = (LinkedList)(_poolMap.get(key)); if(null == pool) { pool = new LinkedList(); _poolMap.put(key,pool); } ObjectTimestampPair pair = null; // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(pool.removeFirst()); if(null != pair) { _totalIdle--; } } catch(NoSuchElementException e) { /* ignored */ } // otherwise if(null == pair) { // if there is a totalMaxActive and we are at the limit then // we have to make room if ((_maxTotal > 0) && (_totalActive + _totalIdle >= _maxTotal)) { clearOldest(); } // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) int active = getActiveCount(key); if ((_maxActive < 0 || active < _maxActive) && (_maxTotal < 0 || _totalActive + _totalIdle < _maxTotal)) { Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); newlyCreated = true; } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = _maxWait - elapsed; if (waitTime > 0) { wait(waitTime); } } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } if (newlyCreated) { incrementActiveCount(key); return pair.value; } else { try { _factory.activateObject(key, pair.value); } catch (Exception e) { try { _factory.destroyObject(key,pair.value); } catch (Exception e2) { // swallowed } continue; } boolean invalid = true; try { invalid = _testOnBorrow && !_factory.validateObject(key, pair.value); } catch (Exception e) { // swallowed } if (invalid) { try { _factory.destroyObject(key,pair.value); } catch (Exception e) { // swallowed } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object"); } // else keep looping } else { incrementActiveCount(key); return pair.value; } } } }
pair = (ObjectTimestampPair)(pool.removeFirst());
pair = (ObjectTimestampPair)(pool.queue.removeFirst());
public synchronized Object borrowObject(Object key) throws Exception { assertOpen(); long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { LinkedList pool = (LinkedList)(_poolMap.get(key)); if(null == pool) { pool = new LinkedList(); _poolMap.put(key,pool); } ObjectTimestampPair pair = null; // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(pool.removeFirst()); if(null != pair) { _totalIdle--; } } catch(NoSuchElementException e) { /* ignored */ } // otherwise if(null == pair) { // if there is a totalMaxActive and we are at the limit then // we have to make room if ((_maxTotal > 0) && (_totalActive + _totalIdle >= _maxTotal)) { clearOldest(); } // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) int active = getActiveCount(key); if ((_maxActive < 0 || active < _maxActive) && (_maxTotal < 0 || _totalActive + _totalIdle < _maxTotal)) { Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); newlyCreated = true; } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = _maxWait - elapsed; if (waitTime > 0) { wait(waitTime); } } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } if (newlyCreated) { incrementActiveCount(key); return pair.value; } else { try { _factory.activateObject(key, pair.value); } catch (Exception e) { try { _factory.destroyObject(key,pair.value); } catch (Exception e2) { // swallowed } continue; } boolean invalid = true; try { invalid = _testOnBorrow && !_factory.validateObject(key, pair.value); } catch (Exception e) { // swallowed } if (invalid) { try { _factory.destroyObject(key,pair.value); } catch (Exception e) { // swallowed } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object"); } // else keep looping } else { incrementActiveCount(key); return pair.value; } } } }
int active = getActiveCount(key); if ((_maxActive < 0 || active < _maxActive) &&
if ((_maxActive < 0 || pool.activeCount < _maxActive) &&
public synchronized Object borrowObject(Object key) throws Exception { assertOpen(); long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { LinkedList pool = (LinkedList)(_poolMap.get(key)); if(null == pool) { pool = new LinkedList(); _poolMap.put(key,pool); } ObjectTimestampPair pair = null; // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(pool.removeFirst()); if(null != pair) { _totalIdle--; } } catch(NoSuchElementException e) { /* ignored */ } // otherwise if(null == pair) { // if there is a totalMaxActive and we are at the limit then // we have to make room if ((_maxTotal > 0) && (_totalActive + _totalIdle >= _maxTotal)) { clearOldest(); } // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) int active = getActiveCount(key); if ((_maxActive < 0 || active < _maxActive) && (_maxTotal < 0 || _totalActive + _totalIdle < _maxTotal)) { Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); newlyCreated = true; } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = _maxWait - elapsed; if (waitTime > 0) { wait(waitTime); } } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } if (newlyCreated) { incrementActiveCount(key); return pair.value; } else { try { _factory.activateObject(key, pair.value); } catch (Exception e) { try { _factory.destroyObject(key,pair.value); } catch (Exception e2) { // swallowed } continue; } boolean invalid = true; try { invalid = _testOnBorrow && !_factory.validateObject(key, pair.value); } catch (Exception e) { // swallowed } if (invalid) { try { _factory.destroyObject(key,pair.value); } catch (Exception e) { // swallowed } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object"); } // else keep looping } else { incrementActiveCount(key); return pair.value; } } } }
incrementActiveCount(key);
pool.incrementActiveCount();
public synchronized Object borrowObject(Object key) throws Exception { assertOpen(); long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { LinkedList pool = (LinkedList)(_poolMap.get(key)); if(null == pool) { pool = new LinkedList(); _poolMap.put(key,pool); } ObjectTimestampPair pair = null; // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(pool.removeFirst()); if(null != pair) { _totalIdle--; } } catch(NoSuchElementException e) { /* ignored */ } // otherwise if(null == pair) { // if there is a totalMaxActive and we are at the limit then // we have to make room if ((_maxTotal > 0) && (_totalActive + _totalIdle >= _maxTotal)) { clearOldest(); } // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) int active = getActiveCount(key); if ((_maxActive < 0 || active < _maxActive) && (_maxTotal < 0 || _totalActive + _totalIdle < _maxTotal)) { Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); newlyCreated = true; } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = _maxWait - elapsed; if (waitTime > 0) { wait(waitTime); } } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } if (newlyCreated) { incrementActiveCount(key); return pair.value; } else { try { _factory.activateObject(key, pair.value); } catch (Exception e) { try { _factory.destroyObject(key,pair.value); } catch (Exception e2) { // swallowed } continue; } boolean invalid = true; try { invalid = _testOnBorrow && !_factory.validateObject(key, pair.value); } catch (Exception e) { // swallowed } if (invalid) { try { _factory.destroyObject(key,pair.value); } catch (Exception e) { // swallowed } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object"); } // else keep looping } else { incrementActiveCount(key); return pair.value; } } } }
for(Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext(); ) { Object key = keyiter.next(); final LinkedList list = (LinkedList)(_poolMap.get(key));
for(Iterator entries = _poolMap.entrySet().iterator(); entries.hasNext(); ) { final Map.Entry entry = (Map.Entry)entries.next(); final Object key = entry.getKey(); final LinkedList list = ((ObjectQueue)(entry.getValue())).queue;
public synchronized void clear() { for(Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext(); ) { Object key = keyiter.next(); final LinkedList list = (LinkedList)(_poolMap.get(key)); for(Iterator it = list.iterator(); it.hasNext(); ) { try { _factory.destroyObject(key,((ObjectTimestampPair)(it.next())).value); } catch(Exception e) { // ignore error, keep destroying the rest } it.remove(); } } _poolMap.clear(); if (_recentlyEvictedKeys != null) { _recentlyEvictedKeys.clear(); } _totalIdle = 0; notifyAll(); }
TreeMap map = new TreeMap();
final Map map = new TreeMap();
public synchronized void clearOldest() { // build sorted map of idle objects TreeMap map = new TreeMap(); for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) { Object key = keyiter.next(); LinkedList list = (LinkedList) _poolMap.get(key); for (Iterator it = list.iterator(); it.hasNext();) { // each item into the map uses the objectimestamppair object // as the key. It then gets sorted based on the timstamp field // each value in the map is the parent list it belongs in. ObjectTimestampPair pair = (ObjectTimestampPair) it.next(); map.put(pair, key); } } // Now iterate created map and kill the first 15% plus one to account for zero Set setPairKeys = map.entrySet(); int itemsToRemove = ((int) (map.size() * 0.15)) + 1; Iterator iter = setPairKeys.iterator(); while (iter.hasNext() && itemsToRemove > 0) { Map.Entry entry = (Map.Entry) iter.next(); // kind of backwards on naming. In the map, each key is the objecttimestamppair // because it has the ordering with the timestamp value. Each value that the // key references is the key of the list it belongs to. Object key = entry.getValue(); ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey(); LinkedList list = (LinkedList) _poolMap.get(key); list.remove(pairTimeStamp); try { _factory.destroyObject(key, pairTimeStamp.value); } catch (Exception e) { // ignore error, keep destroying the rest } // if that was the last object for that key, drop that pool if (list.isEmpty()) { _poolMap.remove(key); } _totalIdle--; itemsToRemove--; } notifyAll(); }
Object key = keyiter.next(); LinkedList list = (LinkedList) _poolMap.get(key);
final Object key = keyiter.next(); final LinkedList list = ((ObjectQueue)_poolMap.get(key)).queue;
public synchronized void clearOldest() { // build sorted map of idle objects TreeMap map = new TreeMap(); for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) { Object key = keyiter.next(); LinkedList list = (LinkedList) _poolMap.get(key); for (Iterator it = list.iterator(); it.hasNext();) { // each item into the map uses the objectimestamppair object // as the key. It then gets sorted based on the timstamp field // each value in the map is the parent list it belongs in. ObjectTimestampPair pair = (ObjectTimestampPair) it.next(); map.put(pair, key); } } // Now iterate created map and kill the first 15% plus one to account for zero Set setPairKeys = map.entrySet(); int itemsToRemove = ((int) (map.size() * 0.15)) + 1; Iterator iter = setPairKeys.iterator(); while (iter.hasNext() && itemsToRemove > 0) { Map.Entry entry = (Map.Entry) iter.next(); // kind of backwards on naming. In the map, each key is the objecttimestamppair // because it has the ordering with the timestamp value. Each value that the // key references is the key of the list it belongs to. Object key = entry.getValue(); ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey(); LinkedList list = (LinkedList) _poolMap.get(key); list.remove(pairTimeStamp); try { _factory.destroyObject(key, pairTimeStamp.value); } catch (Exception e) { // ignore error, keep destroying the rest } // if that was the last object for that key, drop that pool if (list.isEmpty()) { _poolMap.remove(key); } _totalIdle--; itemsToRemove--; } notifyAll(); }
ObjectTimestampPair pair = (ObjectTimestampPair) it.next(); map.put(pair, key);
map.put(it.next(), key);
public synchronized void clearOldest() { // build sorted map of idle objects TreeMap map = new TreeMap(); for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) { Object key = keyiter.next(); LinkedList list = (LinkedList) _poolMap.get(key); for (Iterator it = list.iterator(); it.hasNext();) { // each item into the map uses the objectimestamppair object // as the key. It then gets sorted based on the timstamp field // each value in the map is the parent list it belongs in. ObjectTimestampPair pair = (ObjectTimestampPair) it.next(); map.put(pair, key); } } // Now iterate created map and kill the first 15% plus one to account for zero Set setPairKeys = map.entrySet(); int itemsToRemove = ((int) (map.size() * 0.15)) + 1; Iterator iter = setPairKeys.iterator(); while (iter.hasNext() && itemsToRemove > 0) { Map.Entry entry = (Map.Entry) iter.next(); // kind of backwards on naming. In the map, each key is the objecttimestamppair // because it has the ordering with the timestamp value. Each value that the // key references is the key of the list it belongs to. Object key = entry.getValue(); ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey(); LinkedList list = (LinkedList) _poolMap.get(key); list.remove(pairTimeStamp); try { _factory.destroyObject(key, pairTimeStamp.value); } catch (Exception e) { // ignore error, keep destroying the rest } // if that was the last object for that key, drop that pool if (list.isEmpty()) { _poolMap.remove(key); } _totalIdle--; itemsToRemove--; } notifyAll(); }
LinkedList list = (LinkedList) _poolMap.get(key);
final LinkedList list = ((ObjectQueue)(_poolMap.get(key))).queue;
public synchronized void clearOldest() { // build sorted map of idle objects TreeMap map = new TreeMap(); for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) { Object key = keyiter.next(); LinkedList list = (LinkedList) _poolMap.get(key); for (Iterator it = list.iterator(); it.hasNext();) { // each item into the map uses the objectimestamppair object // as the key. It then gets sorted based on the timstamp field // each value in the map is the parent list it belongs in. ObjectTimestampPair pair = (ObjectTimestampPair) it.next(); map.put(pair, key); } } // Now iterate created map and kill the first 15% plus one to account for zero Set setPairKeys = map.entrySet(); int itemsToRemove = ((int) (map.size() * 0.15)) + 1; Iterator iter = setPairKeys.iterator(); while (iter.hasNext() && itemsToRemove > 0) { Map.Entry entry = (Map.Entry) iter.next(); // kind of backwards on naming. In the map, each key is the objecttimestamppair // because it has the ordering with the timestamp value. Each value that the // key references is the key of the list it belongs to. Object key = entry.getValue(); ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey(); LinkedList list = (LinkedList) _poolMap.get(key); list.remove(pairTimeStamp); try { _factory.destroyObject(key, pairTimeStamp.value); } catch (Exception e) { // ignore error, keep destroying the rest } // if that was the last object for that key, drop that pool if (list.isEmpty()) { _poolMap.remove(key); } _totalIdle--; itemsToRemove--; } notifyAll(); }
final LinkedList list = (LinkedList)_poolMap.get(key);
final LinkedList list = ((ObjectQueue)_poolMap.get(key)).queue;
public synchronized void evict() throws Exception { Object key = null; if (_recentlyEvictedKeys == null) { _recentlyEvictedKeys = new HashSet(_poolMap.size()); } Set remainingKeys = new HashSet(_poolMap.keySet()); remainingKeys.removeAll(_recentlyEvictedKeys); Iterator keyIter = remainingKeys.iterator(); ListIterator objIter = null; for(int i=0,m=getNumTests();i<m;i++) { if(_poolMap.size() > 0) { // Find next idle object pool key to work on if (key == null) { if (!keyIter.hasNext()) { _recentlyEvictedKeys.clear(); remainingKeys = new HashSet(_poolMap.keySet()); keyIter = remainingKeys.iterator(); } if (!keyIter.hasNext()) { // done, there are no keyed pools return; } key = keyIter.next(); } // if we don't have a keyed object pool iterator if (objIter == null) { final LinkedList list = (LinkedList)_poolMap.get(key); if (_evictLastIndex < 0 || _evictLastIndex > list.size()) { _evictLastIndex = list.size(); } objIter = list.listIterator(_evictLastIndex); } // if the _evictionCursor has a previous object, then test it if(objIter.hasPrevious()) { ObjectTimestampPair pair = (ObjectTimestampPair)(objIter.previous()); boolean removeObject=false; if(_minEvictableIdleTimeMillis > 0 && System.currentTimeMillis() - pair.tstamp > _minEvictableIdleTimeMillis) { removeObject=true; } if(_testWhileIdle && removeObject == false) { boolean active = false; try { _factory.activateObject(key,pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(key,pair.value)) { removeObject=true; } else { try { _factory.passivateObject(key,pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { objIter.remove(); _totalIdle--; _factory.destroyObject(key,pair.value); // Do not remove the key from the _poolList or _poolmap, even if the list // stored in the _poolMap for this key is empty when the // {@link #getMinIdle <code>minIdle</code>} is > 0. // // Otherwise if it was the last object for that key, drop that pool if ((_minIdle == 0) && (((LinkedList)(_poolMap.get(key))).isEmpty())) { _poolMap.remove(key); } } catch(Exception e) { ; // ignored } } } else { // else done evicting keyed pool _recentlyEvictedKeys.add(key); _evictLastIndex = -1; objIter = null; } } } }
if ((_minIdle == 0) && (((LinkedList)(_poolMap.get(key))).isEmpty())) {
if ((_minIdle == 0) && (((ObjectQueue)(_poolMap.get(key))).queue.isEmpty())) {
public synchronized void evict() throws Exception { Object key = null; if (_recentlyEvictedKeys == null) { _recentlyEvictedKeys = new HashSet(_poolMap.size()); } Set remainingKeys = new HashSet(_poolMap.keySet()); remainingKeys.removeAll(_recentlyEvictedKeys); Iterator keyIter = remainingKeys.iterator(); ListIterator objIter = null; for(int i=0,m=getNumTests();i<m;i++) { if(_poolMap.size() > 0) { // Find next idle object pool key to work on if (key == null) { if (!keyIter.hasNext()) { _recentlyEvictedKeys.clear(); remainingKeys = new HashSet(_poolMap.keySet()); keyIter = remainingKeys.iterator(); } if (!keyIter.hasNext()) { // done, there are no keyed pools return; } key = keyIter.next(); } // if we don't have a keyed object pool iterator if (objIter == null) { final LinkedList list = (LinkedList)_poolMap.get(key); if (_evictLastIndex < 0 || _evictLastIndex > list.size()) { _evictLastIndex = list.size(); } objIter = list.listIterator(_evictLastIndex); } // if the _evictionCursor has a previous object, then test it if(objIter.hasPrevious()) { ObjectTimestampPair pair = (ObjectTimestampPair)(objIter.previous()); boolean removeObject=false; if(_minEvictableIdleTimeMillis > 0 && System.currentTimeMillis() - pair.tstamp > _minEvictableIdleTimeMillis) { removeObject=true; } if(_testWhileIdle && removeObject == false) { boolean active = false; try { _factory.activateObject(key,pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(key,pair.value)) { removeObject=true; } else { try { _factory.passivateObject(key,pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { objIter.remove(); _totalIdle--; _factory.destroyObject(key,pair.value); // Do not remove the key from the _poolList or _poolmap, even if the list // stored in the _poolMap for this key is empty when the // {@link #getMinIdle <code>minIdle</code>} is > 0. // // Otherwise if it was the last object for that key, drop that pool if ((_minIdle == 0) && (((LinkedList)(_poolMap.get(key))).isEmpty())) { _poolMap.remove(key); } } catch(Exception e) { ; // ignored } } } else { // else done evicting keyed pool _recentlyEvictedKeys.add(key); _evictLastIndex = -1; objIter = null; } } } }
decrementActiveCount(key);
ObjectQueue pool = (ObjectQueue) (_poolMap.get(key)); if(null == pool) { pool = new ObjectQueue(); _poolMap.put(key, pool); } pool.decrementActiveCount();
public synchronized void invalidateObject(Object key, Object obj) throws Exception { try { _factory.destroyObject(key, obj); } catch (Exception e) { // swallowed } finally { decrementActiveCount(key); notifyAll(); // _totalActive has changed } }
LinkedList pool = (LinkedList)(_poolMap.get(key));
ObjectQueue pool = (ObjectQueue)(_poolMap.get(key));
public synchronized void preparePool(Object key, boolean populateImmediately) { LinkedList pool = (LinkedList)(_poolMap.get(key)); if (null == pool) { pool = new LinkedList(); _poolMap.put(key,pool); } if (populateImmediately) { try { // Create the pooled objects ensureMinIdle(key); } catch (Exception e) { //Do nothing } } }
pool = new LinkedList();
pool = new ObjectQueue();
public synchronized void preparePool(Object key, boolean populateImmediately) { LinkedList pool = (LinkedList)(_poolMap.get(key)); if (null == pool) { pool = new LinkedList(); _poolMap.put(key,pool); } if (populateImmediately) { try { // Create the pooled objects ensureMinIdle(key); } catch (Exception e) { //Do nothing } } }
LinkedList pool = (LinkedList) (_poolMap.get(key));
ObjectQueue pool = (ObjectQueue) (_poolMap.get(key));
public synchronized void returnObject(Object key, Object obj) throws Exception { // if we need to validate this object, do so boolean success = true; // whether or not this object passed validation if(_testOnReturn && !_factory.validateObject(key, obj)) { success = false; try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } } else { try { _factory.passivateObject(key, obj); } catch(Exception e) { success = false; } } if (isClosed()) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } return; } boolean shouldDestroy = false; // grab the pool (list) of objects associated with the given key LinkedList pool = (LinkedList) (_poolMap.get(key)); // if it doesn't exist, create it if(null == pool) { pool = new LinkedList(); _poolMap.put(key, pool); } decrementActiveCount(key); // if there's no space in the pool, flag the object for destruction // else if we passivated succesfully, return it to the pool if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) { pool.addLast(new ObjectTimestampPair(obj)); _totalIdle++; } notifyAll(); if(shouldDestroy) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored? } } }
pool = new LinkedList();
pool = new ObjectQueue();
public synchronized void returnObject(Object key, Object obj) throws Exception { // if we need to validate this object, do so boolean success = true; // whether or not this object passed validation if(_testOnReturn && !_factory.validateObject(key, obj)) { success = false; try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } } else { try { _factory.passivateObject(key, obj); } catch(Exception e) { success = false; } } if (isClosed()) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } return; } boolean shouldDestroy = false; // grab the pool (list) of objects associated with the given key LinkedList pool = (LinkedList) (_poolMap.get(key)); // if it doesn't exist, create it if(null == pool) { pool = new LinkedList(); _poolMap.put(key, pool); } decrementActiveCount(key); // if there's no space in the pool, flag the object for destruction // else if we passivated succesfully, return it to the pool if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) { pool.addLast(new ObjectTimestampPair(obj)); _totalIdle++; } notifyAll(); if(shouldDestroy) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored? } } }
decrementActiveCount(key);
pool.decrementActiveCount();
public synchronized void returnObject(Object key, Object obj) throws Exception { // if we need to validate this object, do so boolean success = true; // whether or not this object passed validation if(_testOnReturn && !_factory.validateObject(key, obj)) { success = false; try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } } else { try { _factory.passivateObject(key, obj); } catch(Exception e) { success = false; } } if (isClosed()) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } return; } boolean shouldDestroy = false; // grab the pool (list) of objects associated with the given key LinkedList pool = (LinkedList) (_poolMap.get(key)); // if it doesn't exist, create it if(null == pool) { pool = new LinkedList(); _poolMap.put(key, pool); } decrementActiveCount(key); // if there's no space in the pool, flag the object for destruction // else if we passivated succesfully, return it to the pool if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) { pool.addLast(new ObjectTimestampPair(obj)); _totalIdle++; } notifyAll(); if(shouldDestroy) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored? } } }
if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) {
if(_maxIdle >= 0 && (pool.queue.size() >= _maxIdle)) {
public synchronized void returnObject(Object key, Object obj) throws Exception { // if we need to validate this object, do so boolean success = true; // whether or not this object passed validation if(_testOnReturn && !_factory.validateObject(key, obj)) { success = false; try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } } else { try { _factory.passivateObject(key, obj); } catch(Exception e) { success = false; } } if (isClosed()) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } return; } boolean shouldDestroy = false; // grab the pool (list) of objects associated with the given key LinkedList pool = (LinkedList) (_poolMap.get(key)); // if it doesn't exist, create it if(null == pool) { pool = new LinkedList(); _poolMap.put(key, pool); } decrementActiveCount(key); // if there's no space in the pool, flag the object for destruction // else if we passivated succesfully, return it to the pool if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) { pool.addLast(new ObjectTimestampPair(obj)); _totalIdle++; } notifyAll(); if(shouldDestroy) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored? } } }
pool.addLast(new ObjectTimestampPair(obj));
pool.queue.addLast(new ObjectTimestampPair(obj));
public synchronized void returnObject(Object key, Object obj) throws Exception { // if we need to validate this object, do so boolean success = true; // whether or not this object passed validation if(_testOnReturn && !_factory.validateObject(key, obj)) { success = false; try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } } else { try { _factory.passivateObject(key, obj); } catch(Exception e) { success = false; } } if (isClosed()) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } return; } boolean shouldDestroy = false; // grab the pool (list) of objects associated with the given key LinkedList pool = (LinkedList) (_poolMap.get(key)); // if it doesn't exist, create it if(null == pool) { pool = new LinkedList(); _poolMap.put(key, pool); } decrementActiveCount(key); // if there's no space in the pool, flag the object for destruction // else if we passivated succesfully, return it to the pool if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) { pool.addLast(new ObjectTimestampPair(obj)); _totalIdle++; } notifyAll(); if(shouldDestroy) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored? } } }
; } try { ensureMinIdle(); } catch (Exception e) {
public void run() { while(!_cancelled) { long sleeptime = 0L; synchronized(GenericKeyedObjectPool.this) { sleeptime = _timeBetweenEvictionRunsMillis; } try { Thread.sleep(sleeptime); } catch(Exception e) { ; // ignored } try { evict(); } catch(Exception e) { ; // ignored } } synchronized(GenericKeyedObjectPool.this) { if(null != _evictionCursor) { _evictionCursor.close(); _evictionCursor = null; } if(null != _evictionKeyCursor) { _evictionKeyCursor.close(); _evictionKeyCursor = null; } } }
if( ((CursorableLinkedList)(_poolMap.get(key))).isEmpty() ) {
if ((_minIdle == 0) && (((CursorableLinkedList)(_poolMap.get(key))).isEmpty())) {
public synchronized void evict() throws Exception { Object key = null; for(int i=0,m=getNumTests();i<m;i++) { if(_poolMap.size() > 0) { // if we don't have a key cursor, then create one, and close any object cursor if(null == _evictionKeyCursor) { _evictionKeyCursor = _poolList.cursor(); key = null; if(null != _evictionCursor) { _evictionCursor.close(); _evictionCursor = null; } } // if we don't have an object cursor if(null == _evictionCursor) { // if the _evictionKeyCursor has a next value, then use it if(_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); _evictionCursor = pool.cursor(pool.size()); } else { // else close the key cursor and loop back around if(null != _evictionKeyCursor) { _evictionKeyCursor.close(); _evictionKeyCursor = _poolList.cursor(); if(null != _evictionCursor) { _evictionCursor.close(); _evictionCursor = null; } } continue; } } // if the _evictionCursor has a previous object, then test it if(_evictionCursor.hasPrevious()) { ObjectTimestampPair pair = (ObjectTimestampPair)(_evictionCursor.previous()); boolean removeObject=false; if(_minEvictableIdleTimeMillis > 0 && System.currentTimeMillis() - pair.tstamp > _minEvictableIdleTimeMillis) { removeObject=true; } else if(_testWhileIdle) { boolean active = false; try { _factory.activateObject(key,pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(key,pair.value)) { removeObject=true; } else { try { _factory.passivateObject(key,pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { _evictionCursor.remove(); _totalIdle--; _factory.destroyObject(key,pair.value); // if that was the last object for that key, drop that pool if( ((CursorableLinkedList)(_poolMap.get(key))).isEmpty() ) { _poolMap.remove(key); _poolList.remove(key); } } catch(Exception e) { ; // ignored } } } else { // else the _evictionCursor is done, so close it and loop around if(_evictionCursor != null) { _evictionCursor.close(); _evictionCursor = null; } } } } }
setMinIdle(conf.minIdle);
public synchronized void setConfig(GenericKeyedObjectPool.Config conf) { setMaxIdle(conf.maxIdle); setMaxActive(conf.maxActive); setMaxTotal(conf.maxTotal); setMaxWait(conf.maxWait); setWhenExhaustedAction(conf.whenExhaustedAction); setTestOnBorrow(conf.testOnBorrow); setTestOnReturn(conf.testOnReturn); setTestWhileIdle(conf.testWhileIdle); setNumTestsPerEvictionRun(conf.numTestsPerEvictionRun); setMinEvictableIdleTimeMillis(conf.minEvictableIdleTimeMillis); setTimeBetweenEvictionRunsMillis(conf.timeBetweenEvictionRunsMillis); }
CursorableLinkedList pool = null; synchronized(this) { pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key, pool); _poolList.add(key); } }
public void returnObject(Object key, Object obj) throws Exception { // grab the pool (list) of objects associated with the given key CursorableLinkedList pool = null; synchronized(this) { pool = (CursorableLinkedList)(_poolMap.get(key)); // if it doesn't exist, create it if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key, pool); _poolList.add(key); } } // if we need to validate this object, do so boolean success = true; // whether or not this object passed validation if((_testOnReturn && !_factory.validateObject(key, obj))) { success = false; try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } } else { try { _factory.passivateObject(key, obj); } catch(Exception e) { success = false; } } boolean shouldDestroy = false; synchronized(this) { // subtract one from the total and keyed active counts _totalActive--; Integer active = (Integer)(_activeMap.get(key)); if(null == active) { // do nothing, either null or zero is OK } else if(active.intValue() <= 1) { _activeMap.remove(key); } else { _activeMap.put(key, new Integer(active.intValue() - 1)); } // if there's no space in the pool, flag the object // for destruction // else if we passivated succesfully, return it to the pool if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) { pool.addFirst(new ObjectTimestampPair(obj)); _totalIdle++; } notifyAll(); } if(shouldDestroy) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored? } } }
CursorableLinkedList pool = (CursorableLinkedList) (_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key, pool); _poolList.add(key); }
public void returnObject(Object key, Object obj) throws Exception { // grab the pool (list) of objects associated with the given key CursorableLinkedList pool = null; synchronized(this) { pool = (CursorableLinkedList)(_poolMap.get(key)); // if it doesn't exist, create it if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key, pool); _poolList.add(key); } } // if we need to validate this object, do so boolean success = true; // whether or not this object passed validation if((_testOnReturn && !_factory.validateObject(key, obj))) { success = false; try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored } } else { try { _factory.passivateObject(key, obj); } catch(Exception e) { success = false; } } boolean shouldDestroy = false; synchronized(this) { // subtract one from the total and keyed active counts _totalActive--; Integer active = (Integer)(_activeMap.get(key)); if(null == active) { // do nothing, either null or zero is OK } else if(active.intValue() <= 1) { _activeMap.remove(key); } else { _activeMap.put(key, new Integer(active.intValue() - 1)); } // if there's no space in the pool, flag the object // for destruction // else if we passivated succesfully, return it to the pool if(_maxIdle >= 0 && (pool.size() >= _maxIdle)) { shouldDestroy = true; } else if(success) { pool.addFirst(new ObjectTimestampPair(obj)); _totalIdle++; } notifyAll(); } if(shouldDestroy) { try { _factory.destroyObject(key, obj); } catch(Exception e) { // ignored? } } }
_graph = parseFile( _graphmlFileName );
_graphList.add( parseFile( _graphmlFileName ) );
private void readFiles() { File file = new File( _graphmlFileName ); if ( file.isFile() ) { _graph = parseFile( _graphmlFileName ); } else if ( file.isDirectory() ) { // Only accpets files which suffix is .graphml FilenameFilter filter = new FilenameFilter() { public boolean accept( File dir, String name ) { return name.endsWith( ".graphml" ); } }; File [] allChildren = file.listFiles( filter ); for ( int i = 0; i < allChildren.length; ++i ) { _graphList.add( parseFile( allChildren[ i ].getAbsolutePath() ) ); } analyseSubGraphs(); } else { throw new RuntimeException( "\"" + _graphmlFileName + "\" is not a file or a directory. Please specify a valid .graphml file or a directory containing .graphml files" ); } }
analyseSubGraphs();
private void readFiles() { File file = new File( _graphmlFileName ); if ( file.isFile() ) { _graph = parseFile( _graphmlFileName ); } else if ( file.isDirectory() ) { // Only accpets files which suffix is .graphml FilenameFilter filter = new FilenameFilter() { public boolean accept( File dir, String name ) { return name.endsWith( ".graphml" ); } }; File [] allChildren = file.listFiles( filter ); for ( int i = 0; i < allChildren.length; ++i ) { _graphList.add( parseFile( allChildren[ i ].getAbsolutePath() ) ); } analyseSubGraphs(); } else { throw new RuntimeException( "\"" + _graphmlFileName + "\" is not a file or a directory. Please specify a valid .graphml file or a directory containing .graphml files" ); } }
analyseSubGraphs();
private void readFiles() { File file = new File( _graphmlFileName ); if ( file.isFile() ) { _graph = parseFile( _graphmlFileName ); } else if ( file.isDirectory() ) { // Only accpets files which suffix is .graphml FilenameFilter filter = new FilenameFilter() { public boolean accept( File dir, String name ) { return name.endsWith( ".graphml" ); } }; File [] allChildren = file.listFiles( filter ); for ( int i = 0; i < allChildren.length; ++i ) { _graphList.add( parseFile( allChildren[ i ].getAbsolutePath() ) ); } analyseSubGraphs(); } else { throw new RuntimeException( "\"" + _graphmlFileName + "\" is not a file or a directory. Please specify a valid .graphml file or a directory containing .graphml files" ); } }
clear();
clearOldest();
public synchronized Object borrowObject(Object key) throws Exception { long starttime = System.currentTimeMillis(); boolean newlyCreated = false; for(;;) { CursorableLinkedList pool = (CursorableLinkedList)(_poolMap.get(key)); if(null == pool) { pool = new CursorableLinkedList(); _poolMap.put(key,pool); _poolList.add(key); } ObjectTimestampPair pair = null; // if there are any sleeping, just grab one of those try { pair = (ObjectTimestampPair)(pool.removeFirst()); if(null != pair) { _totalIdle--; } } catch(NoSuchElementException e) { /* ignored */ } // otherwise if(null == pair) { // if there is a totalMaxActive and we are at the limit then // we have to make room // TODO: this could be improved by only removing the oldest object if ((_maxTotal > 0) && (_totalActive + _totalIdle >= _maxTotal)) { clear(); } // check if we can create one // (note we know that the num sleeping is 0, else we wouldn't be here) int active = getActiveCount(key); if ((_maxActive <= 0 || active < _maxActive) && (_maxTotal <= 0 || _totalActive + _totalIdle < _maxTotal)) { Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); newlyCreated = true; } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: Object obj = _factory.makeObject(key); pair = new ObjectTimestampPair(obj); break; case WHEN_EXHAUSTED_FAIL: throw new NoSuchElementException(); case WHEN_EXHAUSTED_BLOCK: try { if(_maxWait <= 0) { wait(); } else { wait(_maxWait); } } catch(InterruptedException e) { // ignored } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } _factory.activateObject(key,pair.value); if(_testOnBorrow && !_factory.validateObject(key,pair.value)) { _factory.destroyObject(key,pair.value); if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object"); } // else keep looping } else { incrementActiveCount(key); return pair.value; } } }
public boolean validateObject(Object obj) { return true; }
public boolean validateObject(Object obj) { return valid; }
public boolean validateObject(Object obj) { return true; }
try {
if (!_pool.empty()) {
public synchronized Object borrowObject() throws Exception { assertOpen(); Object obj = null; try { obj = _pool.pop(); } catch(EmptyStackException e) { if(null == _factory) { throw new NoSuchElementException(); } else { obj = _factory.makeObject(); } } if(null != _factory && null != obj) { _factory.activateObject(obj); } _numActive++; return obj; }
} catch(EmptyStackException e) {
} else {
public synchronized Object borrowObject() throws Exception { assertOpen(); Object obj = null; try { obj = _pool.pop(); } catch(EmptyStackException e) { if(null == _factory) { throw new NoSuchElementException(); } else { obj = _factory.makeObject(); } } if(null != _factory && null != obj) { _factory.activateObject(obj); } _numActive++; return obj; }
while(!_cancelled) { long sleeptime = 0L; synchronized(GenericKeyedObjectPool.this) { sleeptime = _timeBetweenEvictionRunsMillis; } try { Thread.sleep(sleeptime); } catch(Exception e) { ; } try { evict(); } catch(Exception e) { ; } try { ensureMinIdle(); } catch (Exception e) { ; }
try { evict(); } catch(Exception e) { } try { ensureMinIdle(); } catch (Exception e) {
public void run() { while(!_cancelled) { long sleeptime = 0L; synchronized(GenericKeyedObjectPool.this) { sleeptime = _timeBetweenEvictionRunsMillis; } try { Thread.sleep(sleeptime); } catch(Exception e) { ; // ignored } //Evict from the pool try { evict(); } catch(Exception e) { ; // ignored } //Re-create the connections. try { ensureMinIdle(); } catch (Exception e) { ; // ignored } } }
_evictor = new Evictor(delay); Thread t = new Thread(_evictor); t.setDaemon(true); t.start();
_evictor = new Evictor(); GenericObjectPool.EVICTION_TIMER.schedule(_evictor, delay, delay);
protected synchronized void startEvictor(long delay) { if(null != _evictor) { _evictor.cancel(); _evictor = null; } if(delay > 0) { _evictor = new Evictor(delay); Thread t = new Thread(_evictor); t.setDaemon(true); t.start(); } }