Java Code Examples for java.util.Stack

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project blacktie, under directory /jatmibroker-xatmi/src/main/java/org/jboss/narayana/blacktie/jatmibroker/core/tx/.

Source file: ThreadActionData.java

  19 
vote

public static TransactionImpl currentAction(){
  Stack txs=(Stack)_threadList.get();
  if (txs != null) {
    try {
      return (TransactionImpl)txs.peek();
    }
 catch (    EmptyStackException e) {
    }
  }
  return null;
}
 

Example 2

From project commons-pool, under directory /src/java/org/apache/commons/pool/impl/.

Source file: StackKeyedObjectPool.java

  18 
vote

/** 
 * Clears the pool, removing all pooled instances.
 */
public synchronized void clear(){
  Iterator it=_pools.keySet().iterator();
  while (it.hasNext()) {
    Object key=it.next();
    Stack stack=(Stack)(_pools.get(key));
    destroyStack(key,stack);
  }
  _totIdle=0;
  _pools.clear();
  _activeCount.clear();
}
 

Example 3

From project des, under directory /daemon/lib/apache-log4j-1.2.16/src/main/java/org/apache/log4j/.

Source file: NDC.java

  18 
vote

/** 
 * Clone the diagnostic context for the current thread. <p>Internally a diagnostic context is represented as a stack.  A given thread can supply the stack (i.e. diagnostic context) to a child thread so that the child can inherit the parent thread's diagnostic context. <p>The child thread uses the  {@link #inherit inherit} method toinherit the parent's diagnostic context.
 * @return Stack A clone of the current thread's  diagnostic context.
 */
public static Stack cloneStack(){
  Stack stack=getCurrentStack();
  if (stack == null)   return null;
 else {
    return (Stack)stack.clone();
  }
}
 

Example 4

From project eclipse.platform.runtime, under directory /bundles/org.eclipse.core.jobs/src/org/eclipse/core/internal/jobs/.

Source file: LockManager.java

  18 
vote

/** 
 * Resumes all the locks that were suspended while this thread was waiting to acquire another lock.
 */
void resumeSuspendedLocks(Thread owner){
  LockState[] toResume;
synchronized (suspendedLocks) {
    Stack prevLocks=(Stack)suspendedLocks.get(owner);
    if (prevLocks == null)     return;
    toResume=(LockState[])prevLocks.pop();
    if (prevLocks.empty())     suspendedLocks.remove(owner);
  }
  for (int i=0; i < toResume.length; i++)   toResume[i].resume();
}
 

Example 5

From project grails-ide, under directory /org.grails.ide.eclipse.editor.gsp/src/org/grails/ide/eclipse/editor/gsp/translation/internal/.

Source file: StackMap.java

  18 
vote

/** 
 * Returns the most recently pushed value to which this map maps the specified key. Returns <tt>null</tt> if the map contains no mapping for this key.
 * @param key key whose associated value is to be returned.
 * @return the most recently put value to which this map maps thespecified key, or <tt>null</tt> if the map contains no mapping for this key.
 */
public Object peek(Object key){
  Stack stack=(Stack)fInternalMap.get(key);
  if (stack != null) {
    Object o=stack.peek();
    if (stack.isEmpty()) {
      fInternalMap.remove(key);
    }
    return o;
  }
  return null;
}
 

Example 6

From project Jetwick, under directory /src/test/java/de/jetwick/tw/.

Source file: TweetProducerViaSearchTest.java

  18 
vote

@Test public void testFIFO(){
  Queue q=new LinkedBlockingDeque();
  q.add("test");
  q.add("pest");
  assertEquals("test",q.poll());
  q=new LinkedBlockingQueue();
  q.add("test");
  q.add("pest");
  assertEquals("test",q.poll());
  Stack v=new Stack();
  v.add("test");
  v.add("pest");
  assertEquals("pest",v.pop());
}
 

Example 7

From project jolokia, under directory /agent/core/src/test/java/org/jolokia/converter/json/.

Source file: DateExtractorTest.java

  18 
vote

@Test public void directExtract() throws AttributeNotFoundException {
  Date date=new Date();
  Stack stack=new Stack();
  Object result=extractor.extractObject(null,date,stack,false);
  assertEquals(result,date);
  stack.add("time");
  result=extractor.extractObject(null,date,stack,false);
  assertEquals(result,date);
}
 

Example 8

From project droolsjbpm-tools, under directory /drools-eclipse/org.drools.eclipse/src/main/java/org/drools/eclipse/editors/.

Source file: DroolsPairMatcher.java

  17 
vote

private IRegion searchRight(IDocument document,int offset,char rightChar,char leftChar) throws BadLocationException {
  Stack stack=new Stack();
  anchor=ICharacterPairMatcher.LEFT;
  char[] chars=document.get(offset,document.getLength() - offset).toCharArray();
  for (int i=0; i < chars.length; i++) {
    if (chars[i] == leftChar) {
      stack.push(new Character(chars[i]));
      continue;
    }
    if (chars[i] == rightChar) {
      if (stack.isEmpty()) {
        return new Region(offset - 1,i + 2);
      }
 else {
        stack.pop();
      }
    }
  }
  return null;
}
 

Example 9

From project en4j, under directory /NBPlatformApp/SearchLucene/src/main/java/com/rubenlaguna/en4j/searchlucene/.

Source file: CustomTokenFilter.java

  17 
vote

public CustomTokenFilter(TokenStream ts){
  super(ts);
  synonymStack=new Stack();
  termAttr=(TermAttribute)addAttribute(TermAttribute.class);
  save=ts.cloneAttributes();
}
 

Example 10

From project flyingsaucer, under directory /flying-saucer-core/src/main/java/org/xhtmlrenderer/swing/.

Source file: SelectionHighlighter.java

  17 
vote

private boolean createMaps(){
  if (panel.getRootBox() == null) {
    return false;
  }
  textInlineMap=new LinkedHashMap();
  elementBoxMap=new HashMap();
  Stack s=new Stack();
  s.push(panel.getRootBox());
  while (!s.empty()) {
    Box b=(Box)s.pop();
    Element element=b.getElement();
    if (element != null && !elementBoxMap.containsKey(element)) {
      elementBoxMap.put(element,b);
    }
    if (b instanceof InlineLayoutBox) {
      InlineLayoutBox ilb=(InlineLayoutBox)b;
      for (Iterator it=ilb.getInlineChildren().iterator(); it.hasNext(); ) {
        Object o=it.next();
        if (o instanceof InlineText) {
          InlineText t=(InlineText)o;
          Text txt=t.getTextNode();
          if (!textInlineMap.containsKey(txt)) {
            textInlineMap.put(txt,new ArrayList());
          }
          ((List)textInlineMap.get(txt)).add(t);
        }
 else {
          s.push((Box)o);
        }
      }
    }
 else {
      Iterator childIterator=b.getChildIterator();
      while (childIterator.hasNext()) {
        s.push(childIterator.next());
      }
    }
  }
  return true;
}
 

Example 11

From project hdiv, under directory /hdiv-core/src/main/java/org/hdiv/urlProcessor/.

Source file: AbstractUrlProcessor.java

  17 
vote

/** 
 * Removes from <code>url<code> references to relative paths.
 * @param url url
 * @param originalRequestUri originalRequestUri
 * @return returns <code>url</code> without relative paths.
 */
protected String removeRelativePaths(String url,String originalRequestUri){
  String urlWithoutRelativePath=url;
  if (url.startsWith("..")) {
    Stack stack=new Stack();
    String localUri=originalRequestUri.substring(originalRequestUri.indexOf("/"),originalRequestUri.lastIndexOf("/"));
    StringTokenizer localUriParts=new StringTokenizer(localUri.replace('\\','/'),"/");
    while (localUriParts.hasMoreTokens()) {
      String part=localUriParts.nextToken();
      stack.push(part);
    }
    StringTokenizer pathParts=new StringTokenizer(url.replace('\\','/'),"/");
    while (pathParts.hasMoreTokens()) {
      String part=pathParts.nextToken();
      if (!part.equals(".")) {
        if (part.equals("..")) {
          stack.pop();
        }
 else {
          stack.push(part);
        }
      }
    }
    StringBuffer flatPathBuffer=new StringBuffer();
    for (int i=0; i < stack.size(); i++) {
      flatPathBuffer.append("/").append(stack.elementAt(i));
    }
    urlWithoutRelativePath=flatPathBuffer.toString();
  }
  return urlWithoutRelativePath;
}
 

Example 12

From project hecl, under directory /core/org/hecl/.

Source file: HeclException.java

  17 
vote

/** 
 * <code>pushException</code> adds to the exception stack.
 */
private void pushException(String s){
  stack=new Stack();
  Vector lst=new Vector();
  lst.addElement(new Thing(code));
  lst.addElement(message);
  stack.push(new Thing(new ListThing(lst)));
}
 

Example 13

From project ioke, under directory /src/ikj/main/org/jregex/util/io/.

Source file: PathElementMask.java

  17 
vote

public Enumeration elements(final File dir){
  if (dir == null)   throw new IllegalArgumentException();
  final Stack stack=new Stack();
  stack.push(dir);
  return new Enumerator(){
{
      currObj=dir;
    }
    private Enumeration currEn;
    protected boolean find(){
      while (currEn == null || !currEn.hasMoreElements()) {
        if (stack.size() == 0) {
          return false;
        }
        currEn=new ListEnumerator((File)stack.pop(),inst);
      }
      currObj=currEn.nextElement();
      if (((File)currObj).isDirectory())       stack.push(currObj);
      return true;
    }
  }
;
}
 

Example 14

From project ivyde, under directory /org.apache.ivyde.eclipse.resolvevisualizer/src/org/apache/ivyde/eclipse/resolvevisualizer/.

Source file: ResolveVisualizerView.java

  17 
vote

public ResolveVisualizerView(){
  historyStack=new Stack();
  forwardStack=new Stack();
  forceHiddenFilter=new ForceHiddenFilter();
  forceHiddenFilter.setEnabled(true);
  contentProvider.addFilter(forceHiddenFilter);
}
 

Example 15

From project codjo-standalone-common, under directory /src/main/java/net/codjo/utils/.

Source file: ConnectionManager.java

  16 
vote

/** 
 * Constructeur de ConnectionManager
 * @param classDriver              Description of the Parameter
 * @param url                      Description of the Parameter
 * @param catalog                  Description of the Parameter
 * @param props                    Description of the Parameter
 * @param numericTruncationWarning
 * @throws ClassNotFoundException Description of the Exception
 */
public ConnectionManager(String classDriver,String url,String catalog,Properties props,boolean numericTruncationWarning) throws ClassNotFoundException {
  Class.forName(classDriver);
  this.classDriver=classDriver;
  this.dbUrl=url;
  this.dbProps=props;
  this.catalog=catalog;
  if (numericTruncationWarning) {
    dbProps.put("SQLINITSTRING","set arithabort numeric_truncation on");
  }
 else {
    dbProps.put("SQLINITSTRING","set arithabort numeric_truncation off");
  }
  unusedConnections=new Stack();
  allConnections=new java.util.LinkedList();
  initTimer();
}
 

Example 16

From project dawn-isencia, under directory /com.isencia.passerelle.engine/src/main/java/com/isencia/passerelle/model/util/.

Source file: MoMLParser.java

  16 
vote

/** 
 * Reset the MoML parser, forgetting about any previously parsed models.
 * @see #purgeModelRecord(String)
 * @see #purgeAllModelRecords()
 */
public void reset(){
  _attributes=new HashMap();
  _configureNesting=0;
  _containers=new Stack();
  _linkRequests=null;
  _linkRequestStack=new Stack();
  _deleteRequests=null;
  _deleteRequestStack=new Stack();
  _current=null;
  _docNesting=0;
  _externalEntities=new Stack();
  _modified=false;
  _namespace=_DEFAULT_NAMESPACE;
  _namespaces=new Stack();
  _namespaceTranslations=new Stack();
  _skipRendition=false;
  _skipElementIsNew=false;
  _skipElement=0;
  _toplevel=null;
  _resetUndo();
}
 

Example 17

From project indextank-engine, under directory /cojen-2.2.1-sources/org/cojen/util/.

Source file: PatternMatcher.java

  16 
vote

public RuntimeClassFile createClassFile(){
  RuntimeClassFile cf=new RuntimeClassFile(PatternMatcher.class.getName(),PatternMatcher.class.getName(),PatternMatcher.class.getClassLoader());
  cf.markSynthetic();
  cf.setSourceFile(PatternMatcher.class.getName());
  TypeDesc objectArrayType=TypeDesc.OBJECT.toArrayType();
  TypeDesc[] params={objectArrayType};
  MethodInfo mi=cf.addConstructor(Modifiers.PUBLIC,params);
  mBuilder=new CodeBuilder(mi);
  mBuilder.loadThis();
  mBuilder.loadLocal(mBuilder.getParameter(0));
  mBuilder.invokeSuperConstructor(params);
  mBuilder.returnVoid();
  mIntType=TypeDesc.INT;
  mBooleanType=TypeDesc.BOOLEAN;
  mListType=TypeDesc.forClass(List.class);
  mStringType=TypeDesc.STRING;
  mObjectType=TypeDesc.OBJECT;
  mIntArrayType=TypeDesc.INT.toArrayType();
  TypeDesc charArrayType=TypeDesc.CHAR.toArrayType();
  params=new TypeDesc[]{charArrayType,mIntType,mListType};
  mi=cf.addMethod(Modifiers.PUBLIC,"fillMatchResults",null,params);
  mBuilder=new CodeBuilder(mi);
  mLookupLocal=mBuilder.getParameter(0);
  mLimitLocal=mBuilder.getParameter(1);
  mResultsLocal=mBuilder.getParameter(2);
  mPositionsLocal=mBuilder.createLocalVariable("positions",mIntArrayType);
  mIndexLocal=mBuilder.createLocalVariable("index",mIntType);
  mBuilder.mapLineNumber(++mReferenceLine);
  mBuilder.loadConstant(mMaxWildPerKey * 2);
  mBuilder.newObject(mIntArrayType);
  mBuilder.storeLocal(mPositionsLocal);
  mBuilder.loadConstant(0);
  mBuilder.storeLocal(mIndexLocal);
  mTempLocals=new Stack();
  mReturnLabel=mBuilder.createLabel();
  generateBranches(mPatternRoot,-1,0);
  mReturnLabel.setLocation();
  mBuilder.returnVoid();
  return cf;
}
 

Example 18

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/acewiki/.

Source file: Wiki.java

  15 
vote

private void removeExpiredPages(Stack<WikiPage> stack){
  WikiPage previousPage=null;
  for (  WikiPage page : new ArrayList<WikiPage>(stack)) {
    if (page.isExpired() || page.equals(previousPage)) {
      stack.remove(page);
    }
 else {
      previousPage=page;
    }
  }
  if (stack.size() > 0 && currentPage.equals(stack.peek())) {
    stack.pop();
  }
}
 

Example 19

From project AdminCmd, under directory /src/main/java/be/Balor/bukkit/AdminCmd/.

Source file: ACHelper.java

  15 
vote

/** 
 * Add modified block in the undoQueue
 * @param blocks
 */
public void addInUndoQueue(final String player,final Stack<BlockRemanence> blocks){
  if (undoQueue.containsKey(player)) {
    undoQueue.get(player).push(blocks);
  }
 else {
    final Stack<Stack<BlockRemanence>> blockQueue=new Stack<Stack<BlockRemanence>>();
    blockQueue.push(blocks);
    undoQueue.put(player,blockQueue);
  }
}
 

Example 20

From project alg-vis, under directory /src/algvis/unionfind/.

Source file: UnionFindFind.java

  15 
vote

UnionFindNode findSimple(UnionFindNode u){
  Stack<UnionFindNode> S=new Stack<UnionFindNode>();
  UnionFindNode result=null;
  UnionFindNode v=null;
  u.setColor(NodeColor.FIND);
  u.mark();
  addStep("uffindstart",u.getKey());
  mysuspend();
  if (u.getParent() == null) {
    u.setColor(NodeColor.FOUND);
    addStep("ufalreadyroot");
    mysuspend();
    u.unmark();
    return u;
  }
  v=u;
  while (v.getParent() != null) {
    S.add(v);
    v.setColor(NodeColor.FIND);
    addStep("ufup");
    mysuspend();
    v=v.getParent();
  }
  result=v;
  v.setColor(NodeColor.FOUND);
  addStep("ufrootfound",result.getKey());
  mysuspend();
  while (!S.empty()) {
    v=S.pop();
    v.setColor(NodeColor.NORMAL);
  }
  u.unmark();
  return result;
}
 

Example 21

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/client/utils/.

Source file: URIUtils.java

  15 
vote

/** 
 * Removes dot segments according to RFC 3986, section 5.2.4
 * @param uri the original URI
 * @return the URI without dot segments
 */
private static URI removeDotSegments(URI uri){
  String path=uri.getPath();
  if ((path == null) || (path.indexOf("/.") == -1)) {
    return uri;
  }
  String[] inputSegments=path.split("/");
  Stack<String> outputSegments=new Stack<String>();
  for (int i=0; i < inputSegments.length; i++) {
    if ((inputSegments[i].length() == 0) || (".".equals(inputSegments[i]))) {
    }
 else     if ("..".equals(inputSegments[i])) {
      if (!outputSegments.isEmpty()) {
        outputSegments.pop();
      }
    }
 else {
      outputSegments.push(inputSegments[i]);
    }
  }
  StringBuilder outputBuffer=new StringBuilder();
  for (  String outputSegment : outputSegments) {
    outputBuffer.append('/').append(outputSegment);
  }
  try {
    return new URI(uri.getScheme(),uri.getAuthority(),outputBuffer.toString(),uri.getQuery(),uri.getFragment());
  }
 catch (  URISyntaxException e) {
    throw new IllegalArgumentException(e);
  }
}
 

Example 22

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/sqljep/function/.

Source file: PostfixCommand.java

  15 
vote

@SuppressWarnings("unchecked") protected final void removeParams(Stack<Comparable> s,int num){
  int i=1;
  s.pop();
  while (i < num) {
    s.pop();
    i++;
  }
  s.push(null);
}
 

Example 23

From project and-bible, under directory /AndBible/src/net/bible/service/history/.

Source file: HistoryManager.java

  15 
vote

/** 
 * add item and check size of stack
 * @param stack
 * @param item
 */
private synchronized void add(Stack<HistoryItem> stack,HistoryItem item){
  if (item != null) {
    if (stack.isEmpty() || !item.equals(stack.peek())) {
      Log.d(TAG,"Adding " + item + " to history");
      Log.d(TAG,"Stack size:" + stack.size());
      stack.push(item);
      while (stack.size() > MAX_HISTORY) {
        Log.d(TAG,"Shrinking large stack");
        stack.remove(0);
      }
    }
  }
}
 

Example 24

From project Android-File-Manager, under directory /src/com/nexes/manager/.

Source file: FileManager.java

  15 
vote

/** 
 * Constructs an object of the class <br> this class uses a stack to handle the navigation of directories.
 */
public FileManager(){
  mDirContent=new ArrayList<String>();
  mPathStack=new Stack<String>();
  mPathStack.push("/");
  mPathStack.push(mPathStack.peek() + "sdcard");
}
 

Example 25

From project Android-File-Manager-Tablet, under directory /src/com/nexes/manager/tablet/.

Source file: FileManager.java

  15 
vote

/** 
 * Constructs an object of the class <br> this class uses a stack to handle the navigation of directories.
 */
public FileManager(){
  mDirContent=new ArrayList<String>();
  mPathStack=new Stack<String>();
  mPathStack.push("/");
  mPathStack.push(mPathStack.peek() + "sdcard");
}
 

Example 26

From project android-voip-service, under directory /src/main/java/org/linphone/core/tutorials/.

Source file: TestVideoActivity.java

  15 
vote

private Stack<VideoSize> createSizesToTest(){
  Stack<VideoSize> stack=new Stack<VideoSize>();
  stack.push(VideoSize.createStandard(QCIF,false));
  stack.push(VideoSize.createStandard(CIF,false));
  stack.push(VideoSize.createStandard(QVGA,false));
  stack.push(VideoSize.createStandard(HVGA,false));
  stack.push(new VideoSize(640,480));
  stack.push(new VideoSize(800,480));
  return stack;
}
 

Example 27

From project android_external_easymock, under directory /src/org/easymock/internal/.

Source file: LastControl.java

  15 
vote

public static void reportMatcher(IArgumentMatcher matcher){
  Stack<IArgumentMatcher> stack=threadToArgumentMatcherStack.get();
  if (stack == null) {
    stack=new Stack<IArgumentMatcher>();
    threadToArgumentMatcherStack.set(stack);
  }
  stack.push(matcher);
}
 

Example 28

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: Deck.java

  15 
vote

private void undoredo(Stack<UndoRow> src,Stack<UndoRow> dst){
  AnkiDb ankiDB=AnkiDatabaseManager.getDatabase(mDeckPath);
  UndoRow row;
  commitToDB();
  while (true) {
    row=src.pop();
    if (row != null) {
      break;
    }
  }
  Long start=row.mStart;
  Long end=row.mEnd;
  if (end == null) {
    end=latestUndoRow();
  }
  ArrayList<String> sql=ankiDB.queryColumn(String.class,String.format(Utils.ENGLISH_LOCALE,"SELECT sql FROM undoLog " + "WHERE seq > %d and seq <= %d " + "ORDER BY seq DESC",start,end),0);
  Long newstart=latestUndoRow();
  Iterator<String> iter=sql.iterator();
  while (iter.hasNext()) {
    ankiDB.getDatabase().execSQL(iter.next());
  }
  Long newend=latestUndoRow();
  dst.push(new UndoRow(row.mName,newstart,newend));
}
 

Example 29

From project ant4eclipse, under directory /org.ant4eclipse.lib.jdt/src/org/ant4eclipse/lib/jdt/internal/tools/.

Source file: ClasspathEntryResolverExecutor.java

  15 
vote

/** 
 * <p> Creates a new instance of type  {@link ClasspathEntryResolverExecutor}. </p>
 * @param failOnNonHandledEntry
 */
public ClasspathEntryResolverExecutor(boolean failOnNonHandledEntry){
  this._resolvedProjects=new LinkedList<EclipseProject>();
  this._referencedProjects=new LinkedList<EclipseProject>();
  this._currentProject=new Stack<EclipseProject>();
  this._failOnNonHandledEntry=failOnNonHandledEntry;
}
 

Example 30

From project AnySoftKeyboard, under directory /src/com/anysoftkeyboard/keyboards/.

Source file: KeyboardCondensor.java

  15 
vote

int stackRightSideKeyForLater(Stack<Key> rightKeys,Key k,int targetWidth){
  int currentRightX;
  rightKeys.push(k);
  currentRightX=k.x + k.width;
  k.width=targetWidth;
  return currentRightX;
}
 

Example 31

From project Archimedes, under directory /br.org.archimedes.core/src/br/org/archimedes/controller/commands/.

Source file: MakeMacroCommand.java

  15 
vote

public void doIt(Drawing drawing) throws IllegalActionException, NullArgumentException {
  if (drawing == null) {
    throw new NullArgumentException();
  }
  Stack<UndoableCommand> undoHistory=drawing.getUndoHistory();
  if (undoHistory.size() >= commandCount) {
    List<UndoableCommand> cmds=new ArrayList<UndoableCommand>();
    while (commandCount > 0) {
      UndoableCommand command=undoHistory.pop();
      cmds.add(0,command);
      commandCount--;
    }
    MacroCommand macro=new MacroCommand(cmds);
    undoHistory.push(macro);
  }
 else {
    throw new IllegalActionException();
  }
}
 

Example 32

From project archive-commons, under directory /archive-commons/src/main/java/org/archive/format/json/.

Source file: CrossProductOfLists.java

  15 
vote

public List<List<T>> crossProduct(List<List<List<T>>> listOfLists){
  if (LOG.isLoggable(Level.INFO)) {
    int count=listOfLists.size();
    LOG.info(String.format("Total of (%d) lists to cross product",count));
    for (int i=0; i < count; i++) {
      LOG.info(String.format("Field (%d) is (%d) deep",i,listOfLists.get(i).size()));
      for (      List<T> inner : listOfLists.get(i)) {
        LOG.info(String.format("----(%d):(%s)",i,StringUtils.join(inner.toArray(),",")));
      }
    }
  }
  ArrayList<List<T>> results=new ArrayList<List<T>>();
  Stack<T> current=new Stack<T>();
  Deque<List<List<T>>> remainder=new ArrayDeque<List<List<T>>>(listOfLists);
  recurse(remainder,current,results);
  return results;
}
 

Example 33

From project Arecibo, under directory /agent/src/main/java/com/ning/arecibo/agent/config/jmx/.

Source file: JMXDynamicUtils.java

  15 
vote

public synchronized void startClientCacheRetention() throws DataSourceException {
  if (jmxClientCacheKeys != null) {
    throw new DataSourceException("Simultaneous usage of jmx client cache retention not allowed: clientCacheKey stack is already initialized");
  }
 else {
    jmxClientCacheKeys=new Stack<String>();
  }
}
 

Example 34

From project arquillian-core, under directory /core/impl-base/src/main/java/org/jboss/arquillian/core/impl/.

Source file: ManagerImpl.java

  15 
vote

private void debug(Object event,boolean push){
  if (DEBUG) {
    if (eventStack == null) {
      eventStack=new ThreadLocal<Stack<Object>>(){
        @Override protected Stack<Object> initialValue(){
          return new Stack<Object>();
        }
      }
;
    }
    if (push) {
      System.out.println(calcDebugPrefix() + "(E) " + getEventName(event));
      eventStack.get().push(event);
    }
 else {
      if (!eventStack.get().isEmpty()) {
        eventStack.get().pop();
      }
    }
  }
}
 

Example 35

From project arquillian_deprecated, under directory /impl-base/src/main/java/org/jboss/arquillian/impl/core/.

Source file: ManagerImpl.java

  15 
vote

private void debug(Object event,boolean push){
  if (DEBUG) {
    if (eventStack == null) {
      eventStack=new ThreadLocal<Stack<Object>>(){
        @Override protected Stack<Object> initialValue(){
          return new Stack<Object>();
        }
      }
;
    }
    if (push) {
      System.out.println(calcDebugPrefix() + "(E) " + event.getClass().getSimpleName());
      eventStack.get().push(event);
    }
 else {
      if (!eventStack.get().isEmpty()) {
        eventStack.get().pop();
      }
    }
  }
}
 

Example 36

From project AudioBox.fm-JavaLib, under directory /audiobox.fm-core/src/main/java/fm/audiobox/core/parsers/.

Source file: XmlParser.java

  15 
vote

@Override public void startDocument() throws SAXException {
  this.stack=new Stack<IEntity>();
  this.stack.push(this.entity);
  if (log.isDebugEnabled()) {
    startParse=System.currentTimeMillis();
  }
  super.startDocument();
}
 

Example 37

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/proxy/.

Source file: Collaborator.java

  15 
vote

/** 
 * Invoke the preCall method on the interceptor
 * @param o : The Object being invoked
 * @param m : method
 * @param parameters : method paramters
 * @throws Throwable
 */
public Object preInvoke(Object o,Method m,Object[] parameters) throws Throwable {
  Stack<Collaborator.StackElement> stack=new Stack<Collaborator.StackElement>();
  if (interceptors != null) {
    try {
      for (      Interceptor im : interceptors) {
        Collaborator.StackElement se=new StackElement(im);
        stack.push(se);
        se.setPreCallToken(im.preCall(cm,m,parameters));
      }
    }
 catch (    Throwable t) {
      postInvokeExceptionalReturn(stack,o,m,t);
      throw t;
    }
  }
  return stack;
}
 

Example 38

From project bndtools, under directory /bndtools.core/src/bndtools/utils/.

Source file: DependencyUtils.java

  15 
vote

public static <T>void processDependencyMap(Collection<T> input,Map<T,Set<T>> dependencies,Processor<T> processor,IProgressMonitor monitor) throws CoreException, CircularDependencyException {
  SubMonitor progress=SubMonitor.convert(monitor,input.size());
  Set<T> processed=new TreeSet<T>();
  Stack<T> callStack=new Stack<T>();
  for (  T selected : input) {
    processDependencyMap(selected,callStack,dependencies,processed,processor,progress);
  }
}
 

Example 39

From project BoneJ, under directory /src/org/doube/skeleton/.

Source file: Graph.java

  15 
vote

/** 
 * Depth first search method to detect cycles in the graph.
 * @return list of BACK edges
 */
ArrayList<Edge> depthFirstSearch(){
  ArrayList<Edge> backEdges=new ArrayList<Edge>();
  Stack<Vertex> stack=new Stack<Vertex>();
  for (  final Vertex v : this.vertices)   v.setVisited(false);
  stack.push(this.root);
  int visitOrder=0;
  while (!stack.empty()) {
    Vertex u=stack.pop();
    if (!u.isVisited()) {
      if (u.getPredecessor() != null)       u.getPredecessor().setType(Edge.TREE);
      u.setVisited(true,visitOrder++);
      for (      final Edge e : u.getBranches()) {
        if (e.getType() == Edge.UNDEFINED) {
          final Vertex ov=e.getOppositeVertex(u);
          if (!ov.isVisited()) {
            stack.push(ov);
            ov.setPredecessor(e);
          }
 else {
            e.setType(Edge.BACK);
            backEdges.add(e);
          }
        }
      }
    }
  }
  return backEdges;
}
 

Example 40

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.

Source file: BlockingStack.java

  15 
vote

/** 
 * Return a copy of all elements for safe examination. Obviously this collection will not reflect reality for very long, but is safe to iterate etc.
 * @return
 */
public Stack<T> getElements(){
  Stack<T> copy=new Stack<T>();
synchronized (mStack) {
    for (    T o : mStack) {
      copy.add(o);
    }
  }
  return copy;
}
 

Example 41

From project bundlemaker, under directory /main/org.bundlemaker.core.jdt/src/org/bundlemaker/core/jdt/internal/parser/.

Source file: JdtAstVisitor.java

  15 
vote

/** 
 * <p> Creates a new instance of type  {@link JdtAstVisitor}. </p>
 * @param javaSourceResource
 * @param mapTypeInfo
 */
public JdtAstVisitor(IModifiableResource javaSourceResource){
  Assert.isNotNull(javaSourceResource);
  _javaSourceResource=javaSourceResource;
  _typeBindings=new Stack<ITypeBinding>();
  _currentTypes=new Stack<IModifiableType>();
  _realTypes=new Stack<String>();
}
 

Example 42

From project capedwarf-blue, under directory /datastore/src/main/java/org/jboss/capedwarf/datastore/.

Source file: JBossTransaction.java

  15 
vote

static Transaction newTransaction(){
  Stack<JBossTransaction> stack=current.get();
  if (stack == null) {
    stack=new Stack<JBossTransaction>();
    current.set(stack);
  }
 else {
    JBossTransaction jt=stack.peek();
    jt.suspend();
  }
  try {
    tm.begin();
  }
 catch (  Exception e) {
    if (stack.isEmpty())     current.remove();
 else     stack.peek().resume(true);
    throw new DatastoreFailureException("Cannot begin tx.",e);
  }
  JBossTransaction tx=new JBossTransaction();
  stack.push(tx);
  return tx;
}
 

Example 43

From project Carolina-Digital-Repository, under directory /persistence/src/main/java/edu/unc/lib/dl/ingest/aip/.

Source file: CheckPathConflictFilter.java

  15 
vote

private String makePath(PID pid,RDFAwareAIPImpl rdfaip){
  StringBuffer result=new StringBuffer();
  Stack<String> slugs=new Stack<String>();
  PID step=pid;
  PID top=null;
  do {
    String slug=JRDFGraphUtil.getRelatedLiteralObject(rdfaip.getGraph(),step,ContentModelHelper.CDRProperty.slug.getURI());
    slugs.push(slug);
    top=step;
    step=JRDFGraphUtil.getPIDRelationshipSubject(rdfaip.getGraph(),ContentModelHelper.Relationship.contains.getURI(),step);
  }
 while (step != null);
  String containerPath=getTripleStoreQueryService().lookupRepositoryPath(rdfaip.getContainerPlacement(top).parentPID);
  if (containerPath.endsWith("/")) {
    containerPath=containerPath.substring(0,containerPath.length() - 1);
  }
  result.append(containerPath);
  while (!slugs.isEmpty()) {
    result.append("/").append(slugs.pop());
  }
  return result.toString();
}
 

Example 44

From project ceres, under directory /ceres-core/src/main/java/com/bc/ceres/core/runtime/internal/.

Source file: ModuleResolver.java

  15 
vote

/** 
 * Constructs a new module resolver.
 * @param moduleParentClassLoader the parent class loader for the module
 * @param resolvingLibs           if true, libs are resolved
 */
public ModuleResolver(ClassLoader moduleParentClassLoader,boolean resolvingLibs){
  Assert.notNull(moduleParentClassLoader,"moduleParentClassLoader");
  this.moduleParentClassLoader=moduleParentClassLoader;
  this.resolvingLibs=resolvingLibs;
  this.moduleStack=new Stack<String>();
}
 

Example 45

From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/admin/util/.

Source file: ParserUtils.java

  15 
vote

public static int findClossingBracketPosition(int openBracket,String line,char init,char end){
  Stack<Integer> st=new Stack<Integer>();
  for (int i=openBracket; i >= 0 && i < line.length(); i++) {
    if (line.charAt(i) == init) {
      st.push(new Integer(i));
    }
 else     if (line.charAt(i) == end) {
      if (!st.empty())       st.pop();
      if (st.empty()) {
        return i;
      }
    }
  }
  return -1;
}
 

Example 46

From project clj-ds, under directory /src/main/java/com/trifork/clj_ds/.

Source file: PersistentVector.java

  15 
vote

private Stack<MapEntry<Integer,Object[]>> initialPath(){
  Stack<MapEntry<Integer,Object[]>> res=new Stack<MapEntry<Integer,Object[]>>();
  res.push(new MapEntry<Integer,Object[]>(-1,vec.tail));
  Node node=vec.root;
  for (int level=sft; level > 0; level-=5) {
    res.push(new MapEntry<Integer,Object[]>(0,node.array));
    node=(Node)node.array[0];
    if (node == null) {
      res.pop();
      break;
    }
  }
  return res;
}
 

Example 47

From project cloudify, under directory /dsl/src/main/java/org/cloudifysource/dsl/internal/packaging/.

Source file: ZipUtils.java

  15 
vote

/** 
 * Zips a directory into the given file.
 * @param directory the directory to zip.
 * @param zipfile the zip file to create.
 * @throws IOException in case of an error.
 */
public static void zip(final File directory,final File zipfile) throws IOException {
  final URI base=directory.toURI();
  final File toZip=new File(zipfile,"");
  toZip.setWritable(true);
  final Stack<File> stack=new Stack<File>();
  stack.push(directory);
  final OutputStream out=new FileOutputStream(toZip);
  Closeable res=out;
  try {
    final ZipOutputStream zout=new ZipOutputStream(out);
    res=zout;
    while (!stack.isEmpty()) {
      final File currentDirectory=stack.pop();
      for (      final File kid : currentDirectory.listFiles()) {
        String name=base.relativize(kid.toURI()).getPath();
        if (kid.isDirectory()) {
          stack.push(kid);
          name=name.endsWith("/") ? name : name + "/";
          zout.putNextEntry(new ZipEntry(name));
        }
 else {
          zout.putNextEntry(new ZipEntry(name));
          copy(kid,zout);
          zout.closeEntry();
        }
      }
    }
  }
  finally {
    res.close();
  }
}
 

Example 48

From project com.cedarsoft.serialization, under directory /test-utils/src/main/java/com/cedarsoft/serialization/test/utils/.

Source file: XmlNamespaceTranslator.java

  15 
vote

public void translateNamespaces(@Nonnull Document xmlDoc,boolean addNsToAttributes){
  Stack<Node> nodes=new Stack<Node>();
  nodes.push(xmlDoc.getDocumentElement());
  while (!nodes.isEmpty()) {
    Node node=nodes.pop();
switch (node.getNodeType()) {
case Node.ATTRIBUTE_NODE:
case Node.ELEMENT_NODE:
      Value<String> value=this.translations.get(new Key<String>(node.getNamespaceURI()));
    if (value != null) {
      node=xmlDoc.renameNode(node,value.getValue(),node.getNodeName());
    }
  break;
}
if (addNsToAttributes) {
NamedNodeMap attributes=node.getAttributes();
if (!(attributes == null || attributes.getLength() == 0)) {
  for (int i=0, count=attributes.getLength(); i < count; ++i) {
    Node attribute=attributes.item(i);
    if (attribute != null) {
      nodes.push(attribute);
    }
  }
}
}
NodeList childNodes=node.getChildNodes();
if (!(childNodes == null || childNodes.getLength() == 0)) {
for (int i=0, count=childNodes.getLength(); i < count; ++i) {
  Node childNode=childNodes.item(i);
  if (childNode != null) {
    nodes.push(childNode);
  }
}
}
}
}
 

Example 49

From project commons-compress, under directory /src/main/java/org/apache/commons/compress/archivers/dump/.

Source file: DumpArchiveInputStream.java

  15 
vote

/** 
 * Get full path for specified archive entry, or null if there's a gap.
 * @param entry
 * @return  full path for specified archive entry, or null if there's a gap.
 */
private String getPath(DumpArchiveEntry entry){
  Stack<String> elements=new Stack<String>();
  Dirent dirent=null;
  for (int i=entry.getIno(); ; i=dirent.getParentIno()) {
    if (!names.containsKey(Integer.valueOf(i))) {
      elements.clear();
      break;
    }
    dirent=names.get(Integer.valueOf(i));
    elements.push(dirent.getName());
    if (dirent.getIno() == dirent.getParentIno()) {
      break;
    }
  }
  if (elements.isEmpty()) {
    pending.put(Integer.valueOf(entry.getIno()),entry);
    return null;
  }
  StringBuilder sb=new StringBuilder(elements.pop());
  while (!elements.isEmpty()) {
    sb.append('/');
    sb.append(elements.pop());
  }
  return sb.toString();
}
 

Example 50

From project commons-io, under directory /src/test/java/org/apache/commons/io/input/.

Source file: ReversedLinesFileReaderTestParamFile.java

  15 
vote

@Test public void testDataIntegrityWithBufferedReader() throws URISyntaxException, IOException {
  File testFileIso=new File(this.getClass().getResource("/" + fileName).toURI());
  reversedLinesFileReader=new ReversedLinesFileReader(testFileIso,buffSize,encoding);
  Stack<String> lineStack=new Stack<String>();
  bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream(testFileIso),encoding));
  String line=null;
  while ((line=bufferedReader.readLine()) != null) {
    lineStack.push(line);
  }
  while ((line=reversedLinesFileReader.readLine()) != null) {
    String lineFromBufferedReader=lineStack.pop();
    assertEquals(lineFromBufferedReader,line);
  }
}
 

Example 51

From project craftbook, under directory /circuits/src/main/java/com/sk89q/craftbook/plc/lang/.

Source file: Perlstone.java

  15 
vote

private String errmsg(String err,int fno,char opcode,LineInfo li,boolean[] pt,boolean[] tt,boolean[] lt,int pshift,int tshift,int lshift,Stack<Boolean> stack,int tc){
  String errm="";
  if (!err.startsWith(ChatColor.RED + "Detailed Error Message: ")) {
    errm+=ChatColor.RED + "Detailed Error Message: " + ChatColor.RESET+ err+ "\n";
    errm+=ChatColor.RED + "Persistent Variable Table: \n " + ChatColor.RESET+ dumpStateText(pt)+ "\n";
    errm+=ChatColor.RED + " - Shift: " + ChatColor.RESET+ pshift+ "\n";
    errm+=ChatColor.RED + "Temp Variable Table: \n " + ChatColor.RESET+ dumpStateText(tt)+ "\n";
    errm+=ChatColor.RED + " - Shift: " + ChatColor.RESET+ tshift+ "\n";
  }
 else {
    errm+=err + "\n";
  }
  errm+=ChatColor.RED + "====\n";
  if (tc > 0)   errm+="(" + tc + " tail call"+ (tc > 1 ? "s" : "")+ " omitted)\n====\n";
  errm+=ChatColor.RED + "Location: " + ChatColor.RESET+ "Opcode "+ opcode+ " at line "+ li.line+ ", column "+ li.col+ " in function #"+ fno+ "\n";
  errm+=ChatColor.RED + "Local Variable Table: \n " + ChatColor.RESET+ dumpStateText(lt)+ "\n";
  errm+=ChatColor.RED + " - Shift: " + ChatColor.RESET+ lshift+ "\n";
  errm+=ChatColor.RED + "Function Stack: " + ChatColor.RESET+ dumpStateText(stack.toArray(new Boolean[0]));
  return errm;
}
 

Example 52

From project DistCpV2-0.20.203, under directory /src/main/java/org/apache/hadoop/tools/.

Source file: SimpleCopyListing.java

  15 
vote

private void traverseNonEmptyDirectory(SequenceFile.Writer fileListWriter,FileStatus sourceStatus,Path sourcePathRoot,boolean localFile) throws IOException {
  FileSystem sourceFS=sourcePathRoot.getFileSystem(getConf());
  Stack<FileStatus> pathStack=new Stack<FileStatus>();
  pathStack.push(sourceStatus);
  while (!pathStack.isEmpty()) {
    for (    FileStatus child : getChildren(sourceFS,pathStack.pop())) {
      if (LOG.isDebugEnabled())       LOG.debug("Recording source-path: " + sourceStatus.getPath() + " for copy.");
      writeToFileListing(fileListWriter,child,sourcePathRoot,localFile);
      if (isDirectoryAndNotEmpty(sourceFS,child)) {
        if (LOG.isDebugEnabled())         LOG.debug("Traversing non-empty source dir: " + sourceStatus.getPath());
        pathStack.push(child);
      }
    }
  }
}
 

Example 53

From project dolphin, under directory /texcel/svn/com/tan/svn/.

Source file: SvnComparer.java

  15 
vote

/** 
 * Create the directory.
 * @param dest
 * @return
 */
private String makeDirectory(File file){
  if (file.exists() && file.isDirectory())   return "EXISTS";
  if (file.exists() && file.isFile()) {
    file.delete();
  }
  StringBuilder svnadd=new StringBuilder();
  if (!file.exists()) {
    Stack<File> stack=new Stack<File>();
    stack.add(file);
    do {
      file=file.getParentFile();
      stack.add(file);
    }
 while (!file.exists());
    while (!stack.isEmpty()) {
      File f=stack.pop();
      if (f.mkdir()) {
        appendln(svnadd,"svn add --force ",f);
      }
    }
  }
  return svnadd.toString();
}
 

Example 54

From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-api/src/main/java/org/easysoa/proxy/core/api/records/correlation/.

Source file: CorrelationEngineImpl.java

  15 
vote

/** 
 * @param jsonObject
 * @param foundFields
 * @param pathStack
 */
public void visit(JSONObject jsonObject,HashMap<String,CandidateField> foundFields,Stack<Object> pathStack){
  for (  Object key : jsonObject.keySet()) {
    Object obj=jsonObject.get(key);
    pathStack.push(key);
    visitAny(obj,foundFields,pathStack);
    pathStack.pop();
  }
}
 

Example 55

From project eclipse-integration-commons, under directory /org.springsource.ide.eclipse.commons.content.core/src/org/springsource/ide/eclipse/commons/content/core/.

Source file: ContentManager.java

  15 
vote

/** 
 * @param item
 * @return
 * @throws CoreException
 */
public List<ContentItem> getDependencies(ContentItem item) throws CoreException {
  List<ContentItem> results=new ArrayList<ContentItem>();
  Stack<ContentItem> queue=new Stack<ContentItem>();
  queue.add(item);
  while (!queue.isEmpty()) {
    ContentItem next=queue.pop();
    results.add(next);
    List<Dependency> dependencies=next.getRemoteDescriptor().getDependencies();
    for (    Dependency dependency : dependencies) {
      ContentItem dependentItem=itemById.get(dependency.getId());
      if (dependentItem == null) {
        String message=NLS.bind("Failed to resolve dependencies: ''{0}'' requires ''{1}'' which is not available",next.getId(),dependency.getId());
        throw new CoreException(new Status(IStatus.ERROR,ContentPlugin.PLUGIN_ID,message));
      }
      if (dependentItem.needsDownload()) {
        if (!results.contains(dependentItem)) {
          queue.add(dependentItem);
        }
      }
    }
  }
  return results;
}
 

Example 56

From project eclipse-task-editor, under directory /plugins/de.sebastianbenz.task.ui/src/de/sebastianbenz/task/ui/views/.

Source file: ContentProvider.java

  15 
vote

private TreePath treePath(Object object){
  if (object instanceof EObject) {
    EObject eObject=(EObject)object;
    Stack<Object> path=new Stack<Object>();
    while (eObject != null) {
      path.push(eObject);
      eObject=eObject.eContainer();
    }
    Object[] segments=new Object[path.size()];
    for (int i=0; !path.isEmpty(); i++) {
      segments[i]=path.pop();
    }
    return new TreePath(segments);
  }
  return null;
}
 

Example 57

From project eclipsefp, under directory /net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/views/outline/provisionary/.

Source file: TreeElement.java

  15 
vote

private static List<ITreeElement> convert(final String[] args){
  List<ITreeElement> result=new ArrayList<ITreeElement>();
  int index=0;
  Stack<TreeElement> stack=new Stack<TreeElement>();
  while (args.length > index + 2) {
    try {
      int level=Integer.parseInt(args[index++]);
      String text=args[index++];
      String imageKey=args[index++];
      TreeElement elem=new TreeElement(text,imageKey);
      if (level > stack.size()) {
        TreeElement newParent=(TreeElement)result.get(result.size() - 1);
        stack.push(newParent);
        elem.setParent(newParent);
        newParent.addChild(elem);
      }
 else       if (stack.size() > level) {
        while (stack.size() > level) {
          stack.pop();
        }
        if (!stack.isEmpty()) {
          TreeElement newParent=stack.peek();
          elem.setParent(newParent);
          newParent.addChild(elem);
        }
      }
 else {
        if (!stack.isEmpty()) {
          TreeElement newParent=stack.peek();
          elem.setParent(newParent);
          newParent.addChild(elem);
        }
      }
      result.add(elem);
    }
 catch (    final NumberFormatException numfex) {
    }
  }
  return result;
}
 

Example 58

From project empire-db, under directory /empire-db-struts2/src/main/java/org/apache/empire/struts2/jsp/tags/.

Source file: MenuTag.java

  15 
vote

@SuppressWarnings("unchecked") @Override public int doStartTag() throws JspException {
  HtmlTagDictionary dic=HtmlTagDictionary.getInstance();
  HtmlWriter w=new HtmlWriter(pageContext.getOut());
  HtmlTag menu=w.startTag(dic.MenuTag());
  addStandardAttributes(menu,null);
  menu.beginBody(true);
  MenuInfo mi=new MenuInfo();
  Stack<MenuInfo> stack=(Stack<MenuInfo>)pageContext.getAttribute(MENU_STACK_ATTRIBUTE);
  if (stack != null) {
    MenuInfo parent=stack.peek();
    mi.currentId=getString(currentItem,parent.currentId);
    mi.currentClass=getString(currentClass,parent.currentClass);
    mi.enabledClass=getString(enabledClass,parent.enabledClass);
    mi.disabledClass=getString(disabledClass,parent.disabledClass);
    mi.expandedClass=getString(expandedClass,parent.expandedClass);
    mi.actionItem=getString(actionItem,parent.actionItem);
  }
 else {
    stack=new Stack<MenuInfo>();
    pageContext.setAttribute(MENU_STACK_ATTRIBUTE,stack);
    mi.currentId=getString(currentItem,null);
    mi.currentClass=getString(currentClass,dic.MenuItemCurrentClass());
    mi.enabledClass=getString(enabledClass,dic.MenuItemLinkClass());
    mi.disabledClass=getString(disabledClass,dic.MenuItemDisabledClass());
    mi.expandedClass=getString(expandedClass,dic.MenuItemExpandedClass());
    mi.actionItem=getString(actionItem,null);
  }
  stack.push(mi);
  return EVAL_BODY_INCLUDE;
}
 

Example 59

From project ExperienceMod, under directory /ExperienceMod/lib/de/congrace/exp4j/.

Source file: FunctionSeparatorToken.java

  15 
vote

@Override void mutateStackForInfixTranslation(Stack<Token> operatorStack,StringBuilder output){
  Token token;
  while (!((token=operatorStack.peek()) instanceof ParenthesisToken) && !token.getValue().equals("(")) {
    output.append(operatorStack.pop().getValue()).append(" ");
  }
}
 

Example 60

From project fairy, under directory /fairy-core/src/main/java/com/mewmew/fairy/v1/cli/.

Source file: AnnotatedCLI.java

  15 
vote

public static <T>AnnotatedCLI getMagicCLI(Class<T> c){
  Stack<Class> stack=new Stack<Class>();
  Class p=c;
  while (p != Object.class) {
    stack.push(p);
    p=p.getSuperclass();
  }
  return new AnnotatedCLI(stack.toArray(new Class[stack.size()]));
}
 

Example 61

From project fitnesse, under directory /src/fitnesse/slimTables/.

Source file: HtmlTable.java

  15 
vote

private void insertRowAfter(Row existingRow,Row childRow){
  NodeList rowNodes=tableNode.getChildren();
  int index=rowNodes.indexOf(existingRow.rowNode);
  Stack<Node> tempStack=new Stack<Node>();
  while (rowNodes.size() - 1 > index) {
    tempStack.push(rowNodes.elementAt(tableNode.getChildren().size() - 1));
    rowNodes.remove(rowNodes.size() - 1);
  }
  rowNodes.add(childRow.rowNode);
  while (tempStack.size() > 0) {
    rowNodes.add(tempStack.pop());
  }
}
 

Example 62

From project Gedcom, under directory /src/main/java/org/folg/gedcom/visitors/.

Source file: GedcomWriter.java

  15 
vote

public void write(Gedcom gedcom,OutputStream out) throws IOException {
  stack=new Stack<Object>();
  nestedException=null;
  String charset=getCharsetName(gedcom);
  eol=(charset.equals("x-MacRoman") ? "\r" : "\n");
  OutputStreamWriter writer;
  if ("ANSEL".equals(charset)) {
    writer=new AnselOutputStreamWriter(out);
  }
 else {
    writer=new OutputStreamWriter(out,charset);
  }
  this.out=new BufferedWriter(writer);
  gedcom.accept(this);
  this.out.write("0 TRLR" + eol);
  this.out.flush();
  if (nestedException != null) {
    throw nestedException;
  }
}
 

Example 63

From project Gemini-Blueprint, under directory /core/src/main/java/org/eclipse/gemini/blueprint/blueprint/container/support/.

Source file: BlueprintEditorRegistrar.java

  15 
vote

public void registerCustomEditors(PropertyEditorRegistry registry){
  registry.registerCustomEditor(Date.class,new DateEditor());
  registry.registerCustomEditor(Stack.class,new BlueprintCustomCollectionEditor(Stack.class));
  registry.registerCustomEditor(Vector.class,new BlueprintCustomCollectionEditor(Vector.class));
  registry.registerCustomEditor(Collection.class,new BlueprintCustomCollectionEditor(Collection.class));
  registry.registerCustomEditor(Set.class,new BlueprintCustomCollectionEditor(Set.class));
  registry.registerCustomEditor(SortedSet.class,new BlueprintCustomCollectionEditor(SortedSet.class));
  registry.registerCustomEditor(List.class,new BlueprintCustomCollectionEditor(List.class));
  registry.registerCustomEditor(SortedMap.class,new CustomMapEditor(SortedMap.class));
  registry.registerCustomEditor(HashSet.class,new BlueprintCustomCollectionEditor(HashSet.class));
  registry.registerCustomEditor(LinkedHashSet.class,new BlueprintCustomCollectionEditor(LinkedHashSet.class));
  registry.registerCustomEditor(TreeSet.class,new BlueprintCustomCollectionEditor(TreeSet.class));
  registry.registerCustomEditor(ArrayList.class,new BlueprintCustomCollectionEditor(ArrayList.class));
  registry.registerCustomEditor(LinkedList.class,new BlueprintCustomCollectionEditor(LinkedList.class));
  registry.registerCustomEditor(HashMap.class,new CustomMapEditor(HashMap.class));
  registry.registerCustomEditor(LinkedHashMap.class,new CustomMapEditor(LinkedHashMap.class));
  registry.registerCustomEditor(Hashtable.class,new CustomMapEditor(Hashtable.class));
  registry.registerCustomEditor(TreeMap.class,new CustomMapEditor(TreeMap.class));
  registry.registerCustomEditor(Properties.class,new PropertiesEditor());
  registry.registerCustomEditor(ConcurrentMap.class,new CustomMapEditor(ConcurrentHashMap.class));
  registry.registerCustomEditor(ConcurrentHashMap.class,new CustomMapEditor(ConcurrentHashMap.class));
  registry.registerCustomEditor(Queue.class,new BlueprintCustomCollectionEditor(LinkedList.class));
  registry.registerCustomEditor(Dictionary.class,new CustomMapEditor(Hashtable.class));
}
 

Example 64

From project GKEngine, under directory /main/gxt/src/com/extjs/gxt/ui/client/widget/grid/.

Source file: GridView.java

  15 
vote

protected void updateAllColumnWidths(){
  int tw=getTotalWidth();
  int clen=cm.getColumnCount();
  Stack<Integer> ws=new Stack<Integer>();
  for (int i=0; i < clen; i++) {
    ws.push(getColumnWidth(i));
    header.updateColumnWidth(i,cm.getColumnWidth(i));
    if (footer != null) {
      footer.updateColumnWidth(i,cm.getColumnWidth(i));
    }
  }
  NodeList<Element> ns=getRows();
  for (int i=0, len=ns.getLength(); i < len; i++) {
    Element row=ns.getItem(i);
    row.getStyle().setPropertyPx("width",tw);
    if (row.getFirstChild() != null) {
      row.getFirstChildElement().getStyle().setPropertyPx("width",tw);
      TableSectionElement e=row.getFirstChild().cast();
      TableRowElement nodeList=e.getRows().getItem(0);
      for (int j=0; j < clen; j++) {
        ((Element)nodeList.getChildNodes().getItem(j)).getStyle().setPropertyPx("width",ws.get(j));
      }
    }
  }
  templateOnAllColumnWidthsUpdated(ws,tw);
  syncHScroll();
}
 

Example 65

From project GNDMS, under directory /kit/src/de/zib/gndms/kit/config/.

Source file: TreeConfig.java

  15 
vote

public Iterator<String> iterator(){
  final Collection<String> results=new LinkedList<String>();
  final Stack<StackElement> work=new Stack<StackElement>();
  work.push(new StackElement(null,tree,null));
  while (!work.isEmpty()) {
    final StackElement elem=work.pop();
    if (elem.node.isObject()) {
      for (final Iterator<String> iter=elem.node.getFieldNames(); iter.hasNext(); ) {
        final String fieldName=iter.next();
        final JsonNode child=elem.node.get(fieldName);
        final StackElement childElem=new StackElement(elem,child,fieldName);
        if (child.isValueNode())         results.add(childElem.getKey(null));
 else         work.push(childElem);
      }
    }
 else     if (elem.node.isArray()) {
      final int size=elem.node.size();
      results.add(elem.getKey("count"));
      for (int i=0; i < size; i++) {
        final JsonNode child=elem.node.get(i);
        final StackElement childElem=new StackElement(elem,child,Integer.toString(i));
        if (child.isValueNode())         results.add(childElem.getKey(null));
 else         work.push(childElem);
      }
    }
 else     throw new IllegalStateException("Unexpected json node type");
  }
  return results.iterator();
}
 

Example 66

From project gobandroid, under directory /src/org/ligi/gobandroid_hd/logic/.

Source file: GoGame.java

  15 
vote

/** 
 * check if a group has liberties
 * @param group2check - the group to check
 * @return boolean weather the group has liberty
 */
public boolean hasGroupLiberties(int x,int y){
  boolean checked_pos[][]=new boolean[calc_board.getSize()][calc_board.getSize()];
  Stack<Integer> ptStackX=new Stack<Integer>();
  Stack<Integer> ptStackY=new Stack<Integer>();
  ptStackX.push(x);
  ptStackY.push(y);
  while (!ptStackX.empty()) {
    int newx=ptStackX.pop();
    int newy=ptStackY.pop();
    if (cell_has_libertie(newx,newy))     return true;
 else     checked_pos[newx][newy]=true;
    if (newx > 0)     if (calc_board.areCellsEqual(newx - 1,newy,newx,newy) && (checked_pos[newx - 1][newy] == false)) {
      ptStackX.push(newx - 1);
      ptStackY.push(newy);
    }
    if (newx < calc_board.getSize() - 1)     if (calc_board.areCellsEqual(newx + 1,newy,newx,newy) && (checked_pos[newx + 1][newy] == false)) {
      ptStackX.push(newx + 1);
      ptStackY.push(newy);
    }
    if (newy > 0)     if (calc_board.areCellsEqual(newx,newy - 1,newx,newy) && (checked_pos[newx][newy - 1] == false)) {
      ptStackX.push(newx);
      ptStackY.push(newy - 1);
    }
    if (newy < calc_board.getSize() - 1)     if (calc_board.areCellsEqual(newx,newy + 1,newx,newy) && (checked_pos[newx][newy + 1] == false)) {
      ptStackX.push(newx);
      ptStackY.push(newy + 1);
    }
  }
  return false;
}
 

Example 67

From project GoFleetLSServer, under directory /backtrackTSP/src/main/java/org/emergya/backtrackTSP/.

Source file: AStar.java

  15 
vote

public void run(){
  try {
    Stack<TSPStop> stack=new Stack<TSPStop>();
    stack.add(this.bag.getFirst());
    openCandidates.put(-1d,stack);
    BackTrackSolution solution=astar(this.distances,new BackTrackSolution(new Stack<TSPStop>()));
    best.add(solution);
  }
 catch (  Throwable t) {
    LOG.error("Failure on astar procedure.",t);
  }
}
 

Example 68

From project GraphWalker, under directory /src/main/java/org/graphwalker/generators/.

Source file: A_StarPathGenerator.java

  15 
vote

@Override public String[] getNext() throws InterruptedException {
  Util.AbortIf(!hasNext(),"Finished");
  if (lastVertex == null || lastVertex != getMachine().getCurrentVertex() || preCalculatedPath == null || preCalculatedPath.size() == 0) {
    boolean oldCalculatingPathValue=getMachine().isCalculatingPath();
    getMachine().setCalculatingPath(true);
    preCalculatedPath=a_star();
    getMachine().setCalculatingPath(oldCalculatingPathValue);
    if (preCalculatedPath == null) {
      throw new RuntimeException("No path found to " + this.getStopCondition());
    }
    Stack<Edge> temp=new Stack<Edge>();
    while (preCalculatedPath.size() > 0) {
      temp.push(preCalculatedPath.pop());
    }
    preCalculatedPath=temp;
  }
  Edge edge=preCalculatedPath.pop();
  getMachine().walkEdge(edge);
  lastVertex=getMachine().getCurrentVertex();
  String[] retur={getMachine().getEdgeName(edge),getMachine().getCurrentVertexName()};
  return retur;
}
 

Example 69

From project gs-algo, under directory /src/org/graphstream/algorithm/.

Source file: Dijkstra.java

  15 
vote

/** 
 * Returns the shortest path from the source node to a given target node. If there is no path from the source to the target returns an empty path. This method constructs a  {@link org.graphstream.graph.Path} object whichconsumes heap memory proportional to the number of edges and nodes in the path. When possible, prefer using  {@link #getPathNodes(Node)} and{@link #getPathEdges(Node)} which are more memory- and time-efficient.
 * @param target a node
 * @return the shortest path from the source to the target
 * @complexity O(<em>p</em>) where <em>p</em> is the number of the nodes inthe path
 */
public Path getPath(Node target){
  Path path=new Path();
  if (Double.isInfinite(getPathLength(target)))   return path;
  Stack<Edge> stack=new Stack<Edge>();
  for (  Edge e : getPathEdges(target))   stack.push(e);
  path.setRoot(source);
  while (!stack.isEmpty())   path.add(stack.pop());
  return path;
}
 

Example 70

From project gs-core, under directory /src/org/graphstream/graph/.

Source file: Path.java

  15 
vote

/** 
 * Get a copy of this path
 * @return A copy of this path.
 */
@SuppressWarnings("unchecked") public Path getACopy(){
  Path newPath=new Path();
  newPath.root=this.root;
  newPath.edgePath=(Stack<Edge>)edgePath.clone();
  newPath.nodePath=(Stack<Node>)nodePath.clone();
  return newPath;
}
 

Example 71

From project GTNA, under directory /src/gtna/transformation/partition/.

Source file: StrongConnectivityPartition.java

  15 
vote

public static Partition getStrongPartition(Graph g){
  ArrayList<ArrayList<Integer>> components=new ArrayList<ArrayList<Integer>>();
  int[] indexes=Util.initIntArray(g.getNodes().length,-1);
  int[] lowlink=new int[g.getNodes().length];
  Stack<Integer> S=new Stack<Integer>();
  index=0;
  for (int v=0; v < g.getNodes().length; v++) {
    if (indexes[v] == -1) {
      strongConnect(v,g,indexes,lowlink,S,components);
    }
  }
  return new Partition(components);
}
 

Example 72

From project httpClient, under directory /httpclient/src/main/java/org/apache/http/client/utils/.

Source file: URIUtils.java

  15 
vote

/** 
 * Removes dot segments according to RFC 3986, section 5.2.4
 * @param uri the original URI
 * @return the URI without dot segments
 */
private static URI removeDotSegments(URI uri){
  String path=uri.getPath();
  if ((path == null) || (path.indexOf("/.") == -1)) {
    return uri;
  }
  String[] inputSegments=path.split("/");
  Stack<String> outputSegments=new Stack<String>();
  for (int i=0; i < inputSegments.length; i++) {
    if ((inputSegments[i].length() == 0) || (".".equals(inputSegments[i]))) {
    }
 else     if ("..".equals(inputSegments[i])) {
      if (!outputSegments.isEmpty()) {
        outputSegments.pop();
      }
    }
 else {
      outputSegments.push(inputSegments[i]);
    }
  }
  StringBuilder outputBuffer=new StringBuilder();
  for (  String outputSegment : outputSegments) {
    outputBuffer.append('/').append(outputSegment);
  }
  try {
    return new URI(uri.getScheme(),uri.getAuthority(),outputBuffer.toString(),uri.getQuery(),uri.getFragment());
  }
 catch (  URISyntaxException e) {
    throw new IllegalArgumentException(e);
  }
}
 

Example 73

From project IronCount, under directory /src/test/java/com/jointhegrid/ironcount/mockingbird/.

Source file: MockingBirdMessageHandler.java

  15 
vote

@Override public void handleMessage(MessageAndMetadata<Message> m){
  String url=getMessage(m.message());
  URI i=URI.create(url);
  String domain=i.getHost();
  String path=i.getPath();
  String[] parts=domain.split("\\.");
  Stack<String> s=new Stack<String>();
  s.add(path);
  s.addAll(Arrays.asList(parts));
  StringBuilder sb=new StringBuilder();
  for (int j=0; j <= parts.length; j++) {
    sb.append(s.pop());
    countIt(sb.toString());
    sb.append(":");
  }
}
 

Example 74

From project ISAcreator, under directory /src/main/java/org/isatools/isacreator/formatmappingutility/ui/.

Source file: MappingUtilView.java

  15 
vote

public void createGUI(){
  createFileChooser();
  menuPanels.getMain().hideGlassPane();
  createWestPanel(logo,null);
  createSouthPanel();
  workingProgressScreen=new WorkingScreen();
  workingProgressScreen.createGUI();
  setupErrorPanel();
  status=new JLabel();
  previousPage=new Stack<HistoryComponent>();
  setOpaque(false);
  dataEntryEnvironment=new DataEntryEnvironment();
  setDataEntryEnvironment(dataEntryEnvironment);
}
 

Example 75

From project jASM_16, under directory /src/main/java/de/codesourcery/jasm16/ast/.

Source file: ASTUtils.java

  15 
vote

public static Iterator<ASTNode> createDepthFirst(ASTNode node){
  final Stack<ASTNode> stack=new Stack<ASTNode>();
  if (node != null) {
    stack.push(node);
  }
  return new Iterator<ASTNode>(){
    @Override public boolean hasNext(){
      return !stack.isEmpty();
    }
    @Override public ASTNode next(){
      ASTNode n=stack.peek();
      for (      ASTNode child : n.getChildren()) {
        stack.push(child);
      }
      return stack.pop();
    }
    @Override public void remove(){
      throw new UnsupportedOperationException("Not implemented");
    }
  }
;
}
 

Example 76

From project jbosgi-framework, under directory /core/src/main/java/org/jboss/osgi/framework/internal/.

Source file: LazyActivationTracker.java

  15 
vote

private static void addDefinedClass(HostBundleState hostBundle,String className){
  if (hostBundle.awaitLazyActivation() && hostBundle.isAlreadyStarting() == false) {
    Stack<HostBundleState> stack=stackAssociation.get();
    if (stack == null) {
      stack=new Stack<HostBundleState>();
      stackAssociation.set(stack);
    }
    if (stack.contains(hostBundle) == false) {
      LOGGER.tracef("addDefinedClass %s from: %s",className,hostBundle);
      stack.push(hostBundle);
    }
  }
}
 

Example 77

From project jboss-rmi-api_spec, under directory /src/main/java/org/jboss/com/sun/corba/se/impl/io/.

Source file: FVDCodeBaseImpl.java

  15 
vote

public String[] bases(String x){
  try {
    if (vhandler == null) {
      vhandler=new ValueHandlerImpl(false);
    }
    Stack<String> repIds=new Stack<String>();
    Class<?> parent=ObjectStreamClass.lookup(vhandler.getClassFromType(x)).forClass().getSuperclass();
    while (!parent.equals(java.lang.Object.class)) {
      repIds.push(vhandler.createForAnyType(parent));
      parent=parent.getSuperclass();
    }
    String result[]=new String[repIds.size()];
    for (int i=result.length - 1; i >= 0; i++)     result[i]=repIds.pop();
    return result;
  }
 catch (  Throwable t) {
    throw wrapper.missingLocalValueImpl(CompletionStatus.COMPLETED_MAYBE,t);
  }
}
 

Example 78

From project jCAE, under directory /amibe/src/org/jcae/mesh/amibe/algos3d/.

Source file: AbstractAlgoVertex.java

  15 
vote

private boolean processAllVertices(){
  Stack<Vertex> stackNotProcessedObject=new Stack<Vertex>();
  Stack<Double> stackNotProcessedValue=new Stack<Double>();
  double cost=-1.0;
  while (!tree.isEmpty()) {
    preProcessVertex();
    Vertex current=null;
    Iterator<QSortedTree.Node<Vertex>> itt=tree.iterator();
    if (processed > 0 && (processed % progressBarStatus) == 0)     thisLogger().info("Vertices processed: " + processed);
    while (itt.hasNext()) {
      QSortedTree.Node<Vertex> q=itt.next();
      current=q.getData();
      cost=q.getValue();
      if (cost > tolerance)       break;
      if (canProcessVertex(current))       break;
      if (thisLogger().isLoggable(Level.FINE))       thisLogger().fine("Vertex not processed: " + current);
      notProcessed++;
      stackNotProcessedObject.push(current);
      if (tolerance != 0.0)       stackNotProcessedValue.push(Double.valueOf(cost + 0.7 * (tolerance - cost)));
 else       stackNotProcessedValue.push(Double.valueOf(1.0));
      current=null;
    }
    if (cost > tolerance || current == null)     break;
    while (stackNotProcessedObject.size() > 0) {
      double newCost=stackNotProcessedValue.pop().doubleValue();
      Vertex f=stackNotProcessedObject.pop();
      tree.update(f,newCost);
    }
    tree.remove(current);
    processVertex(current,cost);
    afterProcessHook();
    processed++;
  }
  postProcessAllVertices();
  return processed > 0;
}
 

Example 79

From project jchempaint, under directory /src/main/org/openscience/jchempaint/renderer/generators/.

Source file: ExtendedAtomGenerator.java

  15 
vote

private Position getNextPosition(Stack<Position> unused){
  if (unused.size() > 0) {
    return unused.pop();
  }
 else {
    return Position.N;
  }
}
 

Example 80

From project JDave, under directory /jdave-core/src/java/jdave/runner/.

Source file: Scanner.java

  15 
vote

private void forEach(final String extension,IFileHandler fileHandler,Stack<File> dirs){
  do {
    File dir=dirs.pop();
    for (    File file : dir.listFiles()) {
      if (file.isDirectory()) {
        dirs.push(file);
      }
 else {
        if (file.getName().endsWith("." + extension)) {
          fileHandler.handle(file);
        }
      }
    }
  }
 while (!dirs.isEmpty());
}
 

Example 81

From project JGit, under directory /org.spearce.jgit/src/org/spearce/jgit/lib/.

Source file: GitIndex.java

  15 
vote

/** 
 * Construct and write tree out of index.
 * @return SHA-1 of the constructed tree
 * @throws IOException
 */
public ObjectId writeTree() throws IOException {
  checkWriteOk();
  ObjectWriter writer=new ObjectWriter(db);
  Tree current=new Tree(db);
  Stack<Tree> trees=new Stack<Tree>();
  trees.push(current);
  String[] prevName=new String[0];
  for (  Entry e : entries.values()) {
    if (e.getStage() != 0)     continue;
    String[] newName=splitDirPath(e.getName());
    int c=longestCommonPath(prevName,newName);
    while (c < trees.size() - 1) {
      current.setId(writer.writeTree(current));
      trees.pop();
      current=trees.isEmpty() ? null : (Tree)trees.peek();
    }
    while (trees.size() < newName.length) {
      if (!current.existsTree(newName[trees.size() - 1])) {
        current=new Tree(current,Constants.encode(newName[trees.size() - 1]));
        current.getParent().addEntry(current);
        trees.push(current);
      }
 else {
        current=(Tree)current.findTreeMember(newName[trees.size() - 1]);
        trees.push(current);
      }
    }
    FileTreeEntry ne=new FileTreeEntry(current,e.sha1,Constants.encode(newName[newName.length - 1]),(e.mode & FileMode.EXECUTABLE_FILE.getBits()) == FileMode.EXECUTABLE_FILE.getBits());
    current.addEntry(ne);
  }
  while (!trees.isEmpty()) {
    current.setId(writer.writeTree(current));
    trees.pop();
    if (!trees.isEmpty())     current=trees.peek();
  }
  return current.getTreeId();
}
 

Example 82

From project jless, under directory /src/main/java/com/bazaarvoice/jless/ast/node/.

Source file: InternalNode.java

  15 
vote

/** 
 * Clones fields and child nodes, but ignores the iterator stack (since the new nodes are not attached to the tree and so should not be part of any kind of iteration).
 */
@Override public InternalNode clone(){
  InternalNode node=(InternalNode)super.clone();
  node._children=new ArrayList<Node>();
  node._childrenView=Collections.unmodifiableList(node._children);
  node._childIteratorStack=new Stack<MutableChildIterator>();
  cloneChildren(node);
  return node;
}
 

Example 83

From project jmeter-sla-report, under directory /src/java/org/apache/jmeter/extra/report/sla/parser/.

Source file: AssertionResultParser.java

  15 
vote

public Object startElement(XMLStreamReader streamReader,Stack<Object> elementStack) throws XMLStreamException {
  AssertionResultElement assertionResultElement=new AssertionResultElement();
  StaxUtil.moveReaderToElement("name",streamReader);
  assertionResultElement.setName(streamReader.getElementText());
  StaxUtil.moveReaderToElement("failure",streamReader);
  assertionResultElement.setFailure(Boolean.parseBoolean(streamReader.getElementText()));
  StaxUtil.moveReaderToElement("error",streamReader);
  assertionResultElement.setError(Boolean.parseBoolean(streamReader.getElementText()));
  if (assertionResultElement.isFailure() || assertionResultElement.isError()) {
    StaxUtil.moveReaderToElement("failureMessage",streamReader);
    assertionResultElement.setFailureMessage(streamReader.getElementText());
    SampleElement sampleElement=(SampleElement)elementStack.peek();
    sampleElement.getAssertionResultList().add(assertionResultElement);
  }
  return assertionResultElement;
}
 

Example 84

From project joshua, under directory /src/joshua/corpus/syntax/.

Source file: ArraySyntaxTree.java

  15 
vote

public int getOneConstituent(int from,int to){
  int spanLength=to - from;
  Stack<Integer> stack=new Stack<Integer>();
  for (int i=forwardIndex.get(from); i < forwardIndex.get(from + 1); i+=2) {
    int currentSpan=forwardLattice.get(i + 1);
    if (currentSpan == spanLength) {
      return forwardLattice.get(i);
    }
 else     if (currentSpan < spanLength)     break;
  }
  if (stack.isEmpty())   return 0;
  StringBuilder sb=new StringBuilder();
  while (!stack.isEmpty()) {
    String w=Vocabulary.word(stack.pop());
    if (sb.length() != 0)     sb.append(":");
    sb.append(w);
  }
  String label=sb.toString();
  return Vocabulary.id(adjustMarkup(label));
}