Java Code Examples for java.util.Stack

The following are top voted examples for showing how to use java.util.Stack. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: monarch   File: DataSerializer.java   View source code 6 votes vote down vote up
/**
 * Writes an <code>Stack</code> to a <code>DataOutput</code>. Note that even though
 * <code>list</code> may be an instance of a subclass of <code>Stack</code>,
 * <code>readStack</code> will always return an instance of <code>Stack</code>, <B>not</B> an
 * instance of the subclass. To preserve the class type of <code>list</code>,
 * {@link #writeObject(Object, DataOutput)} should be used for data serialization.
 *
 * @throws IOException A problem occurs while writing to <code>out</code>
 *
 * @see #readStack
 * @since GemFire 5.7
 */
public static void writeStack(Stack<?> list, DataOutput out) throws IOException {

  InternalDataSerializer.checkOut(out);

  int size;
  if (list == null) {
    size = -1;
  } else {
    size = list.size();
  }
  InternalDataSerializer.writeArrayLength(size, out);
  if (logger.isTraceEnabled(LogMarker.SERIALIZER)) {
    logger.trace(LogMarker.SERIALIZER, "Writing Stack with {} elements: {}", size, list);
  }
  if (size > 0) {
    for (int i = 0; i < size; i++) {
      writeObject(list.get(i), out);
    }
  }
}
 
Example 2
Project: UtilsMaven   File: JDBCUtils.java   View source code 6 votes vote down vote up
/**
 * 将事务回滚到最近的一个保存点,若没有保存点则回滚到开始事务处
 */
public static void rollbackTransactionToTheLatestSavepoint() {
    Connection connection = tl_conn.get();
    if (connection == null) {
        throw new RuntimeException("You do not start a Transaction so you can not rollback a transaction!");
    }
    try {
        Stack<Savepoint> stack_sp = tl_sp.get();
        if (stack_sp.empty()) {
            JDBCUtils.rollbackTransaction();
            return;
        }
        connection.rollback(stack_sp.pop());
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Project: powertext   File: RTextScrollPane.java   View source code 6 votes vote down vote up
/**
 * Returns the first descendant of a component that is an
 * <code>RTextArea</code>.  This is primarily here to support
 * <code>javax.swing.JLayer</code>s that wrap <code>RTextArea</code>s.
 *
 * @param comp The component to recursively look through.
 * @return The first descendant text area, or <code>null</code> if none
 *         is found.
 */
private static RTextArea getFirstRTextAreaDescendant(Component comp) {
	Stack<Component> stack = new Stack<Component>();
	stack.add(comp);
	while (!stack.isEmpty()) {
		Component current = stack.pop();
		if (current instanceof RTextArea) {
			return (RTextArea)current;
		}
		if (current instanceof Container) {
			Container container = (Container)current;
			stack.addAll(Arrays.asList(container.getComponents()));
		}
	}
	return null;
}
 
Example 4
Project: elements-of-programming-interviews-solutions   File: InorderIterative.java   View source code 6 votes vote down vote up
public static List<Integer> BSTInOrder(BinaryTree<Integer> node) {
    ArrayList<Integer> list = new ArrayList<>();
    Stack<BinaryTree<Integer>> stack = new Stack<>();
    while (!node.isVisited || !stack.isEmpty()) {
        if (node.isVisited)
            node = stack.pop();
        if (node.left != null && !node.left.isVisited) {
            stack.push(node);
            node = node.left;
        } else {
            list.add(node.data);
            node.isVisited = true;
            if (node.right != null)
                node = node.right;
        }
    }
    return list;
}
 
Example 5
Project: jdk8u-jdk   File: DefaultStyledDocument.java   View source code 6 votes vote down vote up
/**
 * Initialize the buffer
 */
void beginEdits(int offset, int length) {
    this.offset = offset;
    this.length = length;
    this.endOffset = offset + length;
    pos = offset;
    if (changes == null) {
        changes = new Vector<ElemChanges>();
    } else {
        changes.removeAllElements();
    }
    if (path == null) {
        path = new Stack<ElemChanges>();
    } else {
        path.removeAllElements();
    }
    fracturedParent = null;
    fracturedChild = null;
    offsetLastIndex = offsetLastIndexOnReplace = false;
}
 
Example 6
Project: Equella   File: PropBagWrapper.java   View source code 6 votes vote down vote up
public void pushOverride(String path, int index)
{
	if( overrides == null )
	{
		overrides = new Stack<PathOverride>();
	}

	PropBagEx base = bag;
	if( !overrides.isEmpty() )
	{
		base = overrides.peek().override;
	}

	PropBagEx subtree = null;
	if( base != null )
	{
		subtree = base.getSubtree(path + '[' + index + ']');
	}

	overrides.add(new PathOverride(ensureNoSlash(ensureSlash(path)), subtree));
}
 
Example 7
Project: picocli   File: CommandLine.java   View source code 6 votes vote down vote up
private int consumeOneArgument(ArgSpec argSpec,
                               Range arity,
                               Stack<String> args,
                               Class<?> type,
                               List<Object> result,
                               int index,
                               String argDescription) throws Exception {
    String[] values = argSpec.splitValue(trim(args.pop()));
    ITypeConverter<?> converter = getTypeConverter(type, argSpec, 0);

    for (int j = 0; j < values.length; j++) {
        result.add(tryConvert(argSpec, index, converter, values[j], type));
        if (tracer.isInfo()) {
            tracer.info("Adding [%s] to %s for %s%n", String.valueOf(result.get(result.size() - 1)), argSpec.toString(), argDescription);
        }
    }
    //checkMaxArityExceeded(arity, max, field, values);
    return ++index;
}
 
Example 8
Project: Industrial-Foregoing   File: ChorusCache.java   View source code 6 votes vote down vote up
public ChorusCache(World world, BlockPos current) {
    this.world = world;
    this.chorus = new ArrayList<>();
    Stack<BlockPos> chorus = new Stack<>();
    chorus.push(current);
    while (!chorus.isEmpty()) {
        BlockPos checking = chorus.pop();
        if (BlockUtils.isChorus(world, checking)) {
            Iterable<BlockPos> area = BlockPos.getAllInBox(checking.offset(EnumFacing.DOWN).offset(EnumFacing.SOUTH).offset(EnumFacing.WEST), checking.offset(EnumFacing.UP).offset(EnumFacing.NORTH).offset(EnumFacing.EAST));
            for (BlockPos blockPos : area) {
                if (BlockUtils.isChorus(world, blockPos) && !this.chorus.contains(blockPos) && blockPos.distanceSq(current.getX(), current.getY(), current.getZ()) <= 1000) {
                    chorus.push(blockPos);
                    this.chorus.add(blockPos);
                }
            }
        }
    }
}
 
Example 9
Project: spellchecker_ta   File: Clitic.java   View source code 6 votes vote down vote up
static boolean clitic_7(Stack s)
{
	byte[] topElmt = ((Entry)s.peek()).getPart();
	byte[] oldTopElmt = topElmt;

	byte[] clitic = BooleanMethod.endsWith_Clitic_7(topElmt);
	if(clitic != null)
	{
		//System.out.println(x + "Clitic 7 - Avathu");
		s.pop();
		s.push(new Entry(clitic,Tag.Clitic));
		topElmt = ByteMeth.subArray(topElmt,0,topElmt.
			length-clitic.length);
		s.push(new Entry(topElmt,-1,oldTopElmt));
		Sandhi.clitic(s);
		return true;
	}
	return false;
}
 
Example 10
Project: openjdk-systemtest   File: TestLambdaMultithreaded.java   View source code 6 votes vote down vote up
private int convertFahrenheitToCelsius(String fahrenheit) {
	Stack<Integer> stack = new Stack<Integer>();

	// Subtract 32 from the temperature
	ldc.execute(stack, fahrenheit);
	bipush.execute(stack, 32);
	isub.execute(stack);
	
	// Multiply by 5
	bipush.execute(stack, 5);
	imul.execute(stack);

	// Divide by 9
	ldc.execute(stack, "Nine");
	idiv.execute(stack);
	
	// Pull the answer from the stack
	Integer celsius = stack.get(0);
	return celsius;
}
 
Example 11
Project: Parasites-of-HellSpace   File: SpawningEnemy.java   View source code 6 votes vote down vote up
public void create()
{
    enemyStack = new Stack<Enemy>();


    Timer.schedule(new Task()
    {
        @Override
        public void run()
        {
            int choiceToMove = MathUtils.random(3);
            for(int i = 0; i < 5; i++)
            {
                enemyStack.add(new WeakEnemy(choiceToMove, xOffset * i, yOffset * i));
            }
            //Timer.instance().clear();
        }
    }, 0.5f, intervalBetweenSpawn);
}
 
Example 12
Project: myfaces-trinidad   File: XhtmlLafUtils.java   View source code 6 votes vote down vote up
/**
 * Returns the Stack for a Style info, creating it, if necessary.
 */
@SuppressWarnings("unchecked")
private static Stack<Object> _getStyleInfoStack(
  Stack[] styleInfo,
  int     stackIndex
  )
{
  Stack<Object> styleInfoStack = styleInfo[stackIndex];

  if (styleInfoStack == null)
  {
    // create new stack
    styleInfoStack = new Stack<Object>();

    // push on initial default
    styleInfoStack.push(_STYLE_DEFAULTS[stackIndex]);

    // save away new stack
    styleInfo[stackIndex] = styleInfoStack;
  }

  return styleInfoStack;
}
 
Example 13
Project: UtilsMaven   File: JDBCUtils.java   View source code 6 votes vote down vote up
/**
 * 开始一个事务,该事务连接是线程安全的。
 */
public static void startTransaction() {
    Connection connection = tl_conn.get();
    if (connection != null) {
        throw new RuntimeException(
                "You have started a Transaction and can not start transaction repeatedly for the same connection!");
    }

    try {
        connection = JDBCUtils.getConnection();
        connection.setAutoCommit(false);
        tl_conn.set(connection);
        tl_sp.set(new Stack<Savepoint>());
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 14
Project: jaffa-framework   File: LoggingService.java   View source code 6 votes vote down vote up
/** Remove the elements from the Message Driven Context (MDC) of Log4J, that may have been added by the call to setLoggingContext().
 * @param payload Any serializable object.
 * @param messageInfo the corresponding MessageInfo object, as specified in the configuration file.
 */
public static void unsetLoggingContext(Object payload, MessageInfo messageInfo) {
    Stack<Map<String, Object>> stack = t_loggingContext.get();
    if (stack == null || stack.size() == 0)
        throw new UnsupportedOperationException("The unsetLoggingContext() method can only be called after a setLoggingContext()");

    // Remove the current context
    if (MDC.getContext() != null) {
        Set<String> keys = new HashSet<String>(MDC.getContext().keySet());
        for (String key : keys)
            MDC.remove(key);
    }

    // Now add the elements of the previous logging context into the MDC
    Map<String, Object> previousLoggingContext = stack.pop();
    for (Map.Entry<String, Object> me : previousLoggingContext.entrySet())
        MDC.put(me.getKey(), me.getValue());
}
 
Example 15
Project: apache-tomcat-7.0.73-with-comment   File: StandardContext.java   View source code 6 votes vote down vote up
/**
 * Get naming context full name.
 */
private String getNamingContextName() {
if (namingContextName == null) {
    Container parent = getParent();
    if (parent == null) {
    namingContextName = getName();
    } else {
    Stack<String> stk = new Stack<String>();
    StringBuilder buff = new StringBuilder();
    while (parent != null) {
        stk.push(parent.getName());
        parent = parent.getParent();
    }
    while (!stk.empty()) {
        buff.append("/" + stk.pop());
    }
    buff.append(getName());
    namingContextName = buff.toString();
    }
}
return namingContextName;
}
 
Example 16
Project: iTAP-controller   File: ObfuscationTopologyManager.java   View source code 6 votes vote down vote up
public ArrayList<Route> getRoutes(DatapathId srcDpid, DatapathId dstDpid, boolean tunnelEnabled, int maxLength) {

	        ArrayList<DatapathId> v = new ArrayList<DatapathId>();
	        ArrayList<Route> routes = new ArrayList<Route>();

	        //routesList.clear();
	        ArrayList<Stack<NodePortTuple>> routesList = new ArrayList<Stack<NodePortTuple>>();

	        this.searchDfs(routesList,srcDpid,dstDpid,v,maxLength+1 /* +1 because #switches = #hops+1*/, new Stack<NodePortTuple>());
	        
	        
	        for(Stack<NodePortTuple> r:routesList){
	            ArrayList<NodePortTuple> ports = new ArrayList<NodePortTuple>();
	            for(NodePortTuple np:r){
	                ports.add(np);
	            }
	            Route path = new Route(srcDpid, dstDpid);
	            path.setPath(ports);
	            routes.add(path);
	        }
	      return routes;
	    }
 
Example 17
Project: JavaPPTX   File: PPHeapStackViewer.java   View source code 6 votes vote down vote up
/**
* Creates a new heap-stack viewer with the specified bounds.
*
* @param slide The <code>PPCodeTraceSlide</code> to which the viewer belongs
* @param x The left edge of the stack region
* @param y The top edge of the stack region
* @param width The width of the stack region
* @param height The height of the stack region
*/

  public PPHeapStackViewer(PPCodeTraceSlide slide,
                           double x, double y, double width, double height) {
     this.slide = slide;
     bb = new Rectangle2D.Double(x, y, width, height);
     hp = 0x1000;
     sp = 0x10000;
     addrMap = new HashMap<Integer,PPWord>();
     callStack = new Stack<PPWord>();
     setLeftMargin(LEFT_MARGIN);
     setRightMargin(RIGHT_MARGIN);
     setTopMargin(TOP_MARGIN);
     setBottomMargin(BOTTOM_MARGIN);
     setFont(VALUE_FONT);
     setAddressFont(ADDRESS_FONT);
     setLabelFont(LABEL_FONT);
     setLabelOrientation("label-address");
  }
 
Example 18
Project: tap17-muggl-javaee   File: IDiv.java   View source code 6 votes vote down vote up
/**
 * Execute the instruction.
 * @param frame The currently executed frame.
 * @throws ExecutionException Thrown in case of fatal problems during the execution.
 */
@Override
public void execute(Frame frame) throws ExecutionException {
	try {
		Stack<Object> stack = frame.getOperandStack();
		Integer value2 = (Integer) stack.pop();
		Integer value1 = (Integer) stack.pop();
		if (value2 == 0) {
			throw new VmRuntimeException(frame.getVm().generateExc("java.lang.ArithmeticException", "Divison by zero."));
		}
		stack.push(value1 / value2);
	} catch (VmRuntimeException e) {
		ExceptionHandler handler = new ExceptionHandler(frame, e);
		try {
			handler.handleException();
		} catch (ExecutionException e2) {
			executionFailed(e2);
		}
	}
}
 
Example 19
Project: gwt-jackson-apt   File: DefaultStringArrayReader.java   View source code 6 votes vote down vote up
@Override
public String[] readArray(JsonReader reader) {
    Stack<String> stringStack = new Stack<>();
    reader.beginArray();
    while (JsonToken.END_ARRAY != reader.peek()) {
        if (JsonToken.NULL == reader.peek()) {
            reader.skipValue();
            stringStack.push(null);
        } else {
            stringStack.push(reader.nextString());
        }
    }
    reader.endArray();

    return stringStack.toArray(new String[stringStack.size()]);
}
 
Example 20
Project: oscm   File: PropertyImportTest.java   View source code 6 votes vote down vote up
@Before
public void setup() throws Exception {

    sqlConn = Mockito.mock(Connection.class);
    statement = Mockito.mock(PreparedStatement.class);
    resultSet = Mockito.mock(ResultSet.class);
    sqlStatementes = new ArrayList<>();
    prepStatements = new Stack<>();
    Mockito.when(sqlConn.prepareStatement(Matchers.anyString()))
            .thenReturn(statement);
    Mockito.when(statement.executeQuery()).thenReturn(resultSet);

    p_driverClass = "java.lang.String";
    tempFile = File.createTempFile("temp", ".properties");
    tempFile.deleteOnExit();
    p_propertyFile = tempFile.getAbsolutePath();
}
 
Example 21
Project: LinkedList_learning   File: LinkedList.java   View source code 6 votes vote down vote up
public static Boolean isPalindrome2(Node head) {
	if (head == null)
		return false;
	Node slow = head;
	Node fast = head;
	Stack<Integer> sta = new Stack<Integer>();
	while (fast != null && fast.next != null) {
		sta.push(slow.value);
		slow = slow.next;
		fast = fast.next.next;
	}
	if (fast != null)// 如果有奇数个节点,slow再往后移动一个
		slow = slow.next;

	while (!sta.isEmpty()) {
		if (sta.pop() != slow.value)
			return false;
		slow = slow.next;
	}
	return true;
}
 
Example 22
Project: parser_ta   File: VAuxillary.java   View source code 6 votes vote down vote up
public Stack checkVai(Stack s,byte[] byteVerb)
{
	if(me.endswith(byteVerb,VVariables.vai))
	{
		byte auxVerb[]=me.subarray(byteVerb,byteVerb.length-VVariables.vai.length,byteVerb.length);
		byte mainVerb[]=me.subarray(byteVerb,0,(byteVerb.length-VVariables.vai.length));
		if(mainVerb.length==0)
		{
			s.push(me.addarray(auxVerb,TagVerb));
			return s;
		}
		s.push(me.addarray(auxVerb,TagAuxVerb));
		s.push(mainVerb);
	}
	return s;
}
 
Example 23
Project: StarCraft-GPBot   File: GameData.java   View source code 6 votes vote down vote up
public void initializeIfNull() {
	if(bp == null) {
		bp = new Stack<Tuple>();
	}
	if (workers == null){
		workers = new ArrayList<Unit>();
	}
	if (squads == null){
		squads = new ArrayList<Unit>();
	}
	if (buildings == null){
		buildings = new ArrayList<Unit>();
	}
	if (enemies == null){
		enemies = new ArrayList<Unit>();
	}
}
 
Example 24
Project: Tree_learning   File: binaryTree.java   View source code 6 votes vote down vote up
public void Mirror1(BinaryTreeNode btn) {
	BinaryTreeNode root = btn;
	if (root == null)
		return;
	Stack<BinaryTreeNode> sta = new Stack<>();
	sta.push(root);
	while (!sta.isEmpty()) {
		BinaryTreeNode node = sta.pop();
		if (node.leftNode != null || node.rightNode != null) {
			BinaryTreeNode temp = node.leftNode;
			node.leftNode = node.rightNode;
			node.rightNode = temp;
		}
		if (node.leftNode != null)
			sta.push(node.leftNode);
		if (node.rightNode != null)
			sta.push(node.rightNode);
	}
}
 
Example 25
Project: openjdk-jdk10   File: T4684378.java   View source code 5 votes vote down vote up
public static void main(String[] argv) {
    Stack<String> bar = new Stack<String>();
    String foo;

    // Compiles, but causes verify error
    foo=(bar.empty()?"":bar.peek()).intern();

    // The following two work fine
    foo = (bar.empty()?"":bar.peek().intern());
    foo = (bar.empty()?"":(String)bar.peek()).intern();
}
 
Example 26
Project: Swap   File: PLA_AbsListView.java   View source code 5 votes vote down vote up
/**
 * @return A view from the ScrapViews collection. These are unordered.
 */
View getScrapView(int position) {
    DebugUtil.i("getFromScrap: " + position);

    if(getHeaderViewsCount() > position){
        //non scraped view.
        return null;
    }

    final Stack<View> scrapViews;
    if (mViewTypeCount == 1) {
        scrapViews = mCurrentScrap;
    } else {
        final int whichScrap = mAdapter.getItemViewType(position);
        if (whichScrap >= 0 && whichScrap < mScrapViews.length) {
            scrapViews = mScrapViews[whichScrap];
        } else {
            return null;
        }
    }

    // look for the exact same layout
    int size = scrapViews.size();
    for(int i = size - 1; i >= 0; --i) {
        final LayoutParams lp = (LayoutParams) scrapViews.get(i).getLayoutParams();
        if(lp.scrappedFromPosition == position) {
            return scrapViews.remove(i);
        }
    }

    if (size > 0) {
        // reused the oldest one.
        return scrapViews.remove(0);
    } else {
        return null;
    }
}
 
Example 27
Project: JInsight   File: RuleHelper.java   View source code 5 votes vote down vote up
private static OperationId lastId() {
  Stack<OperationContext> contexts = CONTEXT_STACK.get();
  OperationContext prevContext = null;
  for (int i = contexts.size() - 1; i >= 0; i--) {
    prevContext = contexts.get(i);
    if (prevContext != RENTRANT) {
      break;
    }
  }
  return prevContext != null ? prevContext.getId() : null;
}
 
Example 28
Project: spellchecker_ta   File: Infinity.java   View source code 5 votes vote down vote up
public static boolean kka_ka(Stack s)
{
	//System.out.println(x + "Infinitive kka ka");
	byte[] topElmt = ((Entry)s.peek()).getPart();
	byte[] oldTopElmt = topElmt;

	//kka
	if(ByteMeth.endsWith(topElmt,Constant.kka))
	{
		//System.out.println(x + "kka");
		s.pop();
		s.push(new Entry(Constant.kka,Tag.Infinitive));
		topElmt = ByteMeth.subArray(topElmt,0,topElmt.
			length-Constant.kka.length);
		s.push(new Entry(topElmt,-1,oldTopElmt));
		return true;
	}
	//ka
	if(ByteMeth.endsWith(topElmt,Constant.ka))
	{
		//System.out.println(x + "ka");
		s.pop();
		s.push(new Entry(Constant.ka,Tag.Infinitive));
		topElmt = ByteMeth.subArray(topElmt,0,topElmt.
			length-Constant.ka.length);
		if(ByteMeth.isEqual(topElmt,Constant.kEt))
			topElmt = ByteMeth.replace(topElmt,Constant.L,1);
		if(ByteMeth.isEqual(topElmt,Constant.kaR))
			topElmt = ByteMeth.replace(topElmt,Constant.l,1);
		s.push(new Entry(topElmt,-1,oldTopElmt));
		return true;
	}
	return false;
}
 
Example 29
Project: hadoop   File: SimpleCopyListing.java   View source code 5 votes vote down vote up
private void traverseNonEmptyDirectory(SequenceFile.Writer fileListWriter,
                                       FileStatus sourceStatus,
                                       Path sourcePathRoot,
                                       DistCpOptions options)
                                       throws IOException {
  FileSystem sourceFS = sourcePathRoot.getFileSystem(getConf());
  final boolean preserveAcls = options.shouldPreserve(FileAttribute.ACL);
  final boolean preserveXAttrs = options.shouldPreserve(FileAttribute.XATTR);
  final boolean preserveRawXattrs = options.shouldPreserveRawXattrs();
  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.");
      CopyListingFileStatus childCopyListingStatus =
        DistCpUtils.toCopyListingFileStatus(sourceFS, child,
          preserveAcls && child.isDirectory(),
          preserveXAttrs && child.isDirectory(),
          preserveRawXattrs && child.isDirectory());
      writeToFileListing(fileListWriter, childCopyListingStatus,
           sourcePathRoot, options);
      if (isDirectoryAndNotEmpty(sourceFS, child)) {
        if (LOG.isDebugEnabled())
          LOG.debug("Traversing non-empty source dir: "
                     + sourceStatus.getPath());
        pathStack.push(child);
      }
    }
  }
}
 
Example 30
Project: Mini-JVM   File: ExecutionEngine.java   View source code 5 votes vote down vote up
public void execute() {
    Method mainMethod = methodArea.queryMainMethod(classFile).orElseThrow(() -> new RuntimeException("没有可执行的main方法"));
    Stack<StackFrame> frames = new Stack<>();
    frames.add(new StackFrame(mainMethod));
    List<AbstractCommand> commands = mainMethod.getCodeAttribute().getCommands();
    StackFrame frame = frames.peek();
    for (int i = frame.getIndex(); i < commands.size(); ) {
        AbstractCommand command = commands.get(i);
        ExecutionResult result = new ExecutionResult();
        command.execute(frame, result);
        if (result.isRunNextCmd()) { // 运行下一条指令
            frame.setIndex(i++);
        } else if (result.isPauseAndRunNewFrame()) { // 调用另一个函数
            // 保存当前函数下一条要执行的命令
            frame.setIndex(i + 1);
            frame = _generateStackFrame(frame, frame.getOperandStack(), result.getNextMethod());
            frames.push(frame);
            commands = frame.getCommands();
            i = frame.getIndex();
        } else if (result.isExitCurrentFrame()) {
            frames.pop();
            if (frames.isEmpty()) return;
            frame = frames.peek();
            commands = frame.getCommands();
            i = frame.getIndex();
        } else if(result.isJump()) {
            frame.setIndex(result.getNextCmdOffset());
            i = result.getNextCmdOffset();
        }
    }
}
 
Example 31
Project: lemon   File: Expr.java   View source code 5 votes vote down vote up
/**
 * 处理操作符.
 */
public void processOper(Token token, Stack<Token> tokenStack,
        List<Token> output) {
    if ("(".equals(token.getValue())) {
        tokenStack.push(token);

        return;
    }

    if (")".equals(token.getValue())) {
        popTokenStack(tokenStack, output, true);

        return;
    }

    if (tokenStack.empty()) {
        tokenStack.push(token);

        return;
    }

    Token innerToken = tokenStack.peek();

    // 越靠前,索引越小,优先级越高
    if (opers.indexOf(innerToken.getValue()) <= opers.indexOf(token
            .getValue())) {
        // 如果当前token的优先级低于栈顶的操作符优先级,就弹出栈顶的操作符
        output.add(tokenStack.pop());
    }

    tokenStack.push(token);
}
 
Example 32
Project: tomcat7   File: SystemLogHandler.java   View source code 5 votes vote down vote up
/**
 * Find PrintStream to which the output must be written to.
 */
protected PrintStream findStream() {
    Stack<CaptureLog> stack = logs.get();
    if (stack != null && !stack.isEmpty()) {
        CaptureLog log = stack.peek();
        if (log != null) {
            PrintStream ps = log.getStream();
            if (ps != null) {
                return ps;
            }
        }
    }
    return out;
}
 
Example 33
Project: tomcat7   File: JspC.java   View source code 5 votes vote down vote up
/**
 * Locate all jsp files in the webapp. Used if no explicit
 * jsps are specified.
 */
public void scanFiles( File base ) throws JasperException {
    Stack<String> dirs = new Stack<String>();
    dirs.push(base.toString());

    // Make sure default extensions are always included
    if ((getExtensions() == null) || (getExtensions().size() < 2)) {
        addExtension("jsp");
        addExtension("jspx");
    }

    while (!dirs.isEmpty()) {
        String s = dirs.pop();
        File f = new File(s);
        if (f.exists() && f.isDirectory()) {
            String[] files = f.list();
            String ext;
            for (int i = 0; (files != null) && i < files.length; i++) {
                File f2 = new File(s, files[i]);
                if (f2.isDirectory()) {
                    dirs.push(f2.getPath());
                } else {
                    String path = f2.getPath();
                    String uri = path.substring(uriRoot.length());
                    ext = files[i].substring(files[i].lastIndexOf('.') +1);
                    if (getExtensions().contains(ext) ||
                        jspConfig.isJspPage(uri)) {
                        pages.add(path);
                    }
                }
            }
        }
    }
}
 
Example 34
Project: jdk8u-jdk   File: VariableHeightLayoutCache.java   View source code 5 votes vote down vote up
public VariableHeightLayoutCache() {
    super();
    tempStacks = new Stack<Stack<TreePath>>();
    visibleNodes = new Vector<Object>();
    boundsBuffer = new Rectangle();
    treePathMapping = new Hashtable<TreePath, TreeStateNode>();
}
 
Example 35
Project: creacoinj   File: ScriptBuilder.java   View source code 5 votes vote down vote up
/**
 * Adds the given number as a push data chunk to the given index in the program.
 * This is intended to use for negative numbers or values > 16, and although
 * it will accept numbers in the range 0-16 inclusive, the encoding would be
 * considered non-standard.
 * 
 * @see #number(int)
 */
protected ScriptBuilder bigNum(int index, long num) {
    final byte[] data;

    if (num == 0) {
        data = new byte[0];
    } else {
        Stack<Byte> result = new Stack<>();
        final boolean neg = num < 0;
        long absvalue = Math.abs(num);

        while (absvalue != 0) {
            result.push((byte) (absvalue & 0xff));
            absvalue >>= 8;
        }

        if ((result.peek() & 0x80) != 0) {
            // The most significant byte is >= 0x80, so push an extra byte that
            // contains just the sign of the value.
            result.push((byte) (neg ? 0x80 : 0));
        } else if (neg) {
            // The most significant byte is < 0x80 and the value is negative,
            // set the sign bit so it is subtracted and interpreted as a
            // negative when converting back to an integral.
            result.push((byte) (result.pop() | 0x80));
        }

        data = new byte[result.size()];
        for (int byteIdx = 0; byteIdx < data.length; byteIdx++) {
            data[byteIdx] = result.get(byteIdx);
        }
    }

    // At most the encoded value could take up to 8 bytes, so we don't need
    // to use OP_PUSHDATA opcodes
    return addChunk(index, new ScriptChunk(data.length, data));
}
 
Example 36
Project: InfixToObject   File: InfixToPrefix.java   View source code 5 votes vote down vote up
public ArrayList<IElementRepresentation<V>> convert(ArrayList<IElementRepresentation<V>> infixEq) {
    Stack<IElementRepresentation<V>> stack = new Stack<IElementRepresentation<V>>();
    ArrayList<IElementRepresentation<V>> prefixedEq = new ArrayList<IElementRepresentation<V>>();
    ArrayList<IElementRepresentation<V>> reversedInfix = new ArrayList<IElementRepresentation<V>>(infixEq);
    Collections.reverse(reversedInfix);

    for (IElementRepresentation<V> element : reversedInfix) {
        if (!element.isOperator()) {
        	prefixedEq.add(element);
        } else {
            if (element.isBlockEnd()) {
                stack.push(element);
            } else if (element.isBlockStart()) {
                while (!stack.lastElement().isBlockEnd()) {
                	prefixedEq.add(stack.pop());
                }
                stack.pop();
            } else {
                if (stack.isEmpty()) {
                    stack.push(element);
                } else if (stack.lastElement().getPriority() <= element.getPriority()) {
                    stack.push(element);
                } else {
                    while (!stack.isEmpty() && stack.lastElement().getPriority() >= element.getPriority()) {
                        prefixedEq.add(stack.pop());
                    }
                    stack.push(element);
                }
            }
        }
    }

    while (!stack.isEmpty()) {
    	prefixedEq.add(stack.pop());
    }

    Collections.reverse(prefixedEq);
    return prefixedEq;
}
 
Example 37
Project: UtilsMaven   File: JDBCUtils.java   View source code 5 votes vote down vote up
/**
 * 用于在事务中设置一个保存点,属于线程安全的
 */
public static void setSavePoint() {
    Connection connection = tl_conn.get();
    if (connection == null) {
        throw new RuntimeException("You do not start a Transaction so you can not set a savepoint!");
    }
    try {
        Stack<Savepoint> stack_sp = tl_sp.get();
        Savepoint sp = connection.setSavepoint();
        stack_sp.push(sp);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 38
Project: tap17-muggl-javaee   File: F2i.java   View source code 5 votes vote down vote up
/**
 * Execute the instruction.
 * @param frame The currently executed frame.
 * @throws ExecutionException Thrown in case of fatal problems during the execution.
 */
@Override
@SuppressWarnings("unused")
public void execute(Frame frame) throws ExecutionException {
	Stack<Object> stack = frame.getOperandStack();
	stack.push(((Float) stack.pop()).intValue());
}
 
Example 39
Project: KotlinTestVersusJUnit   File: Bomb.java   View source code 5 votes vote down vote up
private Stack<Wire> wiresBlueYellowAndGreen() {
    Stack<Wire> wires = new Stack<>();
    wires.push(Wire.blue);
    wires.push(Wire.yellow);
    wires.push(Wire.green);
    return wires;
}
 
Example 40
Project: FuzzDroid   File: UtilSMT.java   View source code 5 votes vote down vote up
public static Unit getPostDominatorOfUnit(IInfoflowCFG cfg, Unit dataFlowStatement) {		
	Map<Unit, Set<ControlFlowPath>> controlFlowPathsAtUnit = new HashMap<Unit, Set<ControlFlowPath>>();
	Set<ControlFlowPath> currentPaths = new HashSet<ControlFlowPath>();
	Stack<Unit> worklist = new Stack<Unit>();
	worklist.add(dataFlowStatement);	

	while(!worklist.isEmpty()) {
		Unit currentUnit = worklist.pop();
		
		if(currentUnit.hasTag(InstrumentedCodeTag.name)) {
			List<Unit> successors = cfg.getSuccsOf(currentUnit);
			
			for(Unit nextUnit : successors) {
				if(proceedWithNextUnit(currentUnit, nextUnit, currentPaths, controlFlowPathsAtUnit)) {
					worklist.push(nextUnit);				
				}
			}
			continue;
		}
		
		SootMethod currentMethod = cfg.getMethodOf(currentUnit);
		
		//this is a kind of hack: We excluded exception-edges here and also keep in mind that ALL dominator-algorithms are intra-procedural
		MHGPostDominatorsFinder<Unit> postdominatorFinder = new MHGPostDominatorsFinder<Unit>(new BriefUnitGraph(currentMethod.retrieveActiveBody()));
		Unit immediatePostDominator = postdominatorFinder.getImmediateDominator(currentUnit);
		while(immediatePostDominator.hasTag(InstrumentedCodeTag.name)) {
			immediatePostDominator = postdominatorFinder.getImmediateDominator(immediatePostDominator);
		}
		return immediatePostDominator;
	}	
	return null;
}