Example usage for java.util Stack Stack

List of usage examples for java.util Stack Stack

Introduction

In this page you can find the example usage for java.util Stack Stack.

Prototype

public Stack() 

Source Link

Document

Creates an empty Stack.

Usage

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {// w w w.j a  v a  2s. c  o  m
        printRequest(request);

        sessionId.set(request.getSession().getId());
        String dataSource = request.getParameter("_dataSource");

        // List grid export
        if ("export".equals(request.getParameter("_operationType"))) {
            exportData(dataSource, response);
            return;
        }

        response.setContentType("text/plain;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "-1");

        if ("getMenu".equals(dataSource)) {
            response.getWriter().write(listServices());
        } else if ("userInfo".equals(dataSource)) {
            ServiceContext ctx = ServiceContextStore.get();
            PrintWriter out = response.getWriter();
            out.print(ctx.getUserId());
            for (String role : ctx.getRoles()) {
                out.print(",");
                out.print(role);
            }
            out.flush();
        } else if ("createDataSource".equals(dataSource)) {
            HashMap<String, String> classToServiceName = new HashMap<String, String>();
            for (ServiceDescription serviceDesc : getServiceDescription()) {
                log.log(Level.INFO, "Service translation from {0} to {1}",
                        new Object[] { serviceDesc.getExpectedClass().getName(), serviceDesc.getName() });
                classToServiceName.put(serviceDesc.getExpectedClass().getName(), serviceDesc.getName());
            }
            GuiDataSourceService dataSourceService = getGuiDataSourceService();
            dataSourceService.setServiceMapping(ServiceContextStore.get(), classToServiceName);

            StringBuilder output = new StringBuilder();
            output.append("dataSources###");
            List<GuiDataSource> allDataSources = dataSourceService.findAll(ServiceContextStore.get());
            for (GuiDataSource dataSourceDef : allDataSources) {
                ds2Ref.put(dataSourceDef.getBaseClass(), dataSourceDef.getTitleField());
                dataSourceDef.setBaseClass(null);
                log.log(Level.INFO, "Entity def for {0}", dataSourceDef.getXxxID());
                dataSourceDef.setDataURL(getServiceUrl(request));

                output.append("$wnd.isc.RestDataSource.create(")
                        .append(mapObjToOutput(dataSourceDef, 6, new Stack<Object>(), true, false))
                        .append(");\n");
            }

            ListSettingsService listInstance = (ListSettingsService) findService(LIST_SETTINGS_SERVICE)
                    .getInstance();
            List<ListSettings> guiList = listInstance.findUserSettings(ServiceContextStore.get());
            for (ListSettings listSettings : guiList) {
                output.append("\n###").append(listSettings.getListID()).append("###")
                        .append(listSettings.getSettings());
            }

            log.log(Level.INFO, "Create datasource {0}", output.toString());
            response.getWriter().append(output);

        } else if (findService(dataSource) != null) {
            ServiceDescription serviceDesc = findService(dataSource);
            String operationType = request.getParameter("_operationType");
            String methodName = request.getParameter("_operationId");

            if (methodName != null && !methodName.endsWith("_fetch")) {
                log.log(Level.FINER, "Executing method '" + dataSource + "." + methodName + "'");
                MethodDescription methodDescription = serviceDesc.getOtherMethods().get(methodName);
                if (methodDescription != null) {
                    Object valObj = null;
                    HashMap<String, Object> jsData = unifyRequest(request);
                    Object[] params = prepareMethodParam(jsData, true, methodDescription.parameterNames,
                            methodDescription.method.getParameterTypes());
                    // Resolve "ids" for iterations
                    int iterate = -1;
                    if (jsData.get("ids") != null) {
                        Class<?>[] paramTypes = methodDescription.method.getParameterTypes();
                        for (int i = 0; i < paramTypes.length; i++) {
                            if (Long.class.equals(paramTypes[i]) || paramTypes[i].equals(Long.TYPE)
                                    && methodDescription.parameterNames[i].equals("id") && params[i] == null) {
                                iterate = i;
                                break;
                            } else if (Collection.class.isAssignableFrom(paramTypes[i])
                                    && methodDescription.parameterNames[i].equals("ids") && params[i] == null) {
                                List<Long> longList = new ArrayList<Long>();
                                String ids = (String) jsData.get("ids");
                                String[] idSplit = ids.split(",");
                                for (int k = 0; k < idSplit.length; k++) {
                                    if (idSplit[i].length() > 0) {
                                        longList.add(Long.parseLong(idSplit[i]));
                                    }
                                }
                                params[i] = longList;
                                break;
                            }
                        }
                    }

                    if (iterate != -1) {
                        if (log.isLoggable(Level.FINER)) {
                            for (int j = 0; j < params.length; j++) {
                                log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                            }
                        }
                        String ids = (String) jsData.get("ids");
                        String[] idSplit = ids.split(",");
                        ArrayList<Object> listResult = new ArrayList<Object>();
                        valObj = listResult;
                        for (int i = 0; i < idSplit.length; i++) {
                            if (idSplit[i].length() > 0) {
                                params[iterate] = Long.parseLong(idSplit[i]);
                                Object subValObj = methodDescription.method.invoke(serviceDesc.getInstance(),
                                        params);
                                if (subValObj != null && subValObj instanceof Collection) {
                                    listResult.addAll((Collection) subValObj);
                                } else if (subValObj != null) {
                                    listResult.add(subValObj);
                                }
                            }
                        }
                        log.info("Return value: " + valObj);
                    } else if (params != null) {
                        if (log.isLoggable(Level.FINER)) {
                            for (int j = 0; j < params.length; j++) {
                                log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                            }
                        }
                        valObj = methodDescription.method.invoke(serviceDesc.getInstance(), params);
                        log.info("Return value: " + valObj);
                    }
                    Collection<Object> collResult;
                    PagedResult<?> pagedResult = null;
                    if (valObj == null) {
                        collResult = new ArrayList<Object>();
                        for (int i = 0; i < params.length; i++) {
                            if (params[i] != null
                                    && params[i].getClass().equals(serviceDesc.getExpectedClass())) {
                                collResult.add(params[i]);
                                break;
                            }
                        }
                    } else if (valObj instanceof Collection) {
                        collResult = (Collection) valObj;
                    } else if (valObj instanceof PagedResult) {
                        collResult = null;
                        pagedResult = (PagedResult) valObj;
                    } else {
                        ArrayList<Object> serviceResultArray = new ArrayList<Object>();
                        serviceResultArray.add(valObj);
                        collResult = serviceResultArray;
                    }
                    if (collResult != null) {
                        sendResponse(response.getWriter(), 0, collResult.size(), collResult);
                    } else if (pagedResult != null) {
                        sendResponse(response.getWriter(), pagedResult);
                    }
                } else {
                    throw new IllegalArgumentException(
                            "No " + methodName + " operation available on " + dataSource);
                }
            } else if (operationType == null) {
                throw makeApplicationException("Unsupported operation", "ERR9001", "NULL");
            } else if (operationType.equals("fetch") && request.getParameter("id") != null) {
                Long idVal = Long.parseLong(request.getParameter("id"));
                if (serviceDesc.getFindById() != null) {
                    Object serviceResult = serviceDesc.getFindById().invoke(serviceDesc.getInstance(),
                            ServiceContextStore.get(), idVal);
                    ArrayList<Object> serviceResultArray = new ArrayList<Object>();
                    serviceResultArray.add(serviceResult);

                    sendResponse(response.getWriter(), 0, 1, serviceResultArray);
                } else {
                    throw new IllegalArgumentException("No fetch operation available");
                }
            } else if (operationType.equals("fetch")) {
                List<?> serviceResult;
                PagedResult<?> pagedServiceResult = null;

                String sRow = request.getParameter("_startRow");
                int startRow = sRow == null ? 0 : Integer.parseInt(sRow);
                String eRow = request.getParameter("_endRow");
                int endRow = eRow == null ? 0 : Integer.parseInt(eRow);

                ArrayList<String> queryParams = new ArrayList();
                Enumeration pNames = request.getParameterNames();
                while (pNames.hasMoreElements()) {
                    String paramName = (String) pNames.nextElement();
                    if (!paramName.startsWith("_")) {
                        queryParams.add(paramName);
                    } else if ("_sortBy".equals(paramName)) {
                        queryParams.add("sortBy");
                    }
                }

                if (queryParams.size() > 0) {
                    Collection<MethodDescription> methods = serviceDesc.getOtherMethods().values();
                    MethodDescription matchedMethod = null;
                    int matchLength = 1000;
                    for (MethodDescription method : methods) {
                        String[] methodParamNames = method.parameterNames;
                        if (methodParamNames != null && methodParamNames.length >= queryParams.size()
                                && (List.class.isAssignableFrom(method.method.getReturnType())
                                        || PagedResult.class.isAssignableFrom(method.method.getReturnType()))) {
                            boolean matchParam = false;
                            for (String queryParam : queryParams) {
                                matchParam = false;
                                for (String methodParamName : methodParamNames) {
                                    if (queryParam.equals(methodParamName)) {
                                        matchParam = true;
                                        break;
                                    }
                                }
                                if (!matchParam) {
                                    break;
                                }
                            }
                            if (matchParam && method.parameterNames.length < matchLength) {
                                matchedMethod = method;
                                matchLength = method.parameterNames.length;
                            }
                        }
                    }

                    Object[] params = null;
                    if (matchedMethod != null) {
                        HashMap<String, Object> jsData = unifyRequest(request);
                        params = prepareMethodParam(jsData, true, matchedMethod.parameterNames,
                                matchedMethod.method.getParameterTypes());
                    } else {
                        List<ConditionalCriteria> conditions = new ArrayList();
                        for (MethodDescription method : methods) {
                            if (method.getMethodName().equals("findByCondition")) {
                                Class<?>[] parameterTypes = method.method.getParameterTypes();
                                if (List.class.isAssignableFrom(parameterTypes[0])) {
                                    params = new Object[] { conditions };
                                    matchedMethod = method;
                                    break;
                                } else if (parameterTypes.length == 3
                                        && ServiceContext.class.isAssignableFrom(parameterTypes[0])
                                        && List.class.isAssignableFrom(parameterTypes[1])
                                        && PagingParameter.class.isAssignableFrom(parameterTypes[2])) {
                                    endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow;
                                    PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow,
                                            LOOK_AHEAD);
                                    params = new Object[] { ServiceContextStore.get(), conditions,
                                            pagingParam };
                                    matchedMethod = method;
                                    break;
                                } else if (parameterTypes.length == 2
                                        && ServiceContext.class.isAssignableFrom(parameterTypes[0])
                                        && List.class.isAssignableFrom(parameterTypes[1])) {
                                    params = new Object[] { ServiceContextStore.get(), conditions };
                                    matchedMethod = method;
                                    break;
                                }
                            }
                        }
                        if (matchedMethod != null) {
                            for (String queryParam : queryParams) {
                                LeafProperty<?> queryProp = new LeafProperty(queryParam, ScServlet.class);
                                String matchStyle = request.getParameter("_textMatchStyle");
                                String queryValue = request.getParameter(queryParam);
                                if (queryParam.equals("sortBy")) {
                                    queryValue = normalizeAssoc(serviceDesc, request.getParameter("_sortBy"));
                                    if (queryValue.startsWith("+")) {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1),
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderAsc(sortProp));
                                    } else if (queryValue.startsWith("-")) {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue.substring(1),
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderDesc(sortProp));
                                    } else {
                                        LeafProperty<?> sortProp = new LeafProperty(queryValue,
                                                ScServlet.class);
                                        conditions.add(ConditionalCriteria.orderAsc(sortProp));
                                    }
                                } else if (queryValue.indexOf('%') != -1) {
                                    conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                            request.getParameter(queryParam) + "%"));
                                } else {
                                    String[] queryParamSplit = queryParam.split("\\.");
                                    Class watchClass = serviceDesc.getExpectedClass();
                                    Object otherEqVal = null;
                                    boolean isString = false;
                                    for (String queryParamPart : queryParamSplit) {
                                        try {
                                            Method method = watchClass.getMethod(
                                                    makeGetMethodName(queryParamPart), (Class[]) null);
                                            watchClass = method.getReturnType();
                                            if (Collection.class.isAssignableFrom(watchClass)) {
                                                // TODO look deeper into class of collection
                                                break;
                                            } else if (Enum.class.isAssignableFrom(watchClass)) {
                                                otherEqVal = Enum.valueOf(watchClass, queryValue);
                                                break;
                                            } else if (String.class.equals(watchClass)) {
                                                isString = true;
                                                break;
                                            } else if (Long.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Long.parseLong(queryValue);
                                                break;
                                            } else if (Integer.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Integer.parseInt(queryValue);
                                                break;
                                            } else if (Double.class.equals(watchClass)) {
                                                isString = true;
                                                otherEqVal = Double.parseDouble(queryValue);
                                                break;
                                            } else if (Date.class.equals(watchClass)) {
                                                otherEqVal = dateFormat.parse(queryValue);
                                                break;
                                            } else if (findServiceByClassName(watchClass.getName()) != null
                                                    && "null".equals(queryValue)) {
                                                otherEqVal = "null";
                                                break;
                                            } else if (findServiceByClassName(watchClass.getName()) != null
                                                    && findServiceByClassName(watchClass.getName())
                                                            .getFindById() != null) {
                                                ServiceDescription srvc = findServiceByClassName(
                                                        watchClass.getName());
                                                otherEqVal = srvc.getFindById().invoke(srvc.getInstance(),
                                                        ServiceContextStore.get(), Long.parseLong(queryValue));
                                            }
                                        } catch (NoSuchMethodException nsme) {
                                            // Ignore error, isString will stay false
                                            break;
                                        }
                                    }
                                    boolean isLike = "substring".equals(matchStyle)
                                            || "startsWith".equals(matchStyle);
                                    if ("null".equals(otherEqVal)) {
                                        conditions.add(ConditionalCriteria.isNull(queryProp));
                                    } else if (otherEqVal instanceof Date) {
                                        DateMidnight start = (new DateTime(otherEqVal)).toDateMidnight();
                                        DateMidnight stop = start.plusDays(1);
                                        conditions.add(ConditionalCriteria.between(queryProp, start.toDate(),
                                                stop.toDate()));
                                    } else if (isString && otherEqVal != null && isLike) {
                                        conditions.add(ConditionalCriteria.like(queryProp, otherEqVal));
                                    } else if (isString && "substring".equals(matchStyle)) {
                                        conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                                "%" + request.getParameter(queryParam) + "%"));
                                    } else if (isString && "startsWith".equals(matchStyle)) {
                                        conditions.add(ConditionalCriteria.ignoreCaseLike(queryProp,
                                                request.getParameter(queryParam) + "%"));
                                    } else if (otherEqVal != null) {
                                        conditions.add(ConditionalCriteria.equal(queryProp, otherEqVal));
                                    } else {
                                        conditions.add(ConditionalCriteria.equal(queryProp, queryValue));
                                    }
                                }
                            }
                        }
                    }

                    if (matchedMethod != null && params != null) {
                        for (int j = 0; j < params.length; j++) {
                            log.log(Level.FINER, "     Parameter[{0}]={1}", new Object[] { j, params[j] });
                        }
                        if (matchedMethod.method.getReturnType().equals(PagedResult.class)) {
                            serviceResult = null;
                            pagedServiceResult = (PagedResult) matchedMethod.method
                                    .invoke(serviceDesc.getInstance(), params);
                        } else {
                            serviceResult = (List<?>) matchedMethod.method.invoke(serviceDesc.getInstance(),
                                    params);
                        }
                    } else {
                        throw makeApplicationException("You can''t filter with such condition.", "ERR9015",
                                (Serializable[]) null);
                    }
                } else if (queryParams.size() == 0 && serviceDesc.getFindAll() != null) {
                    Class<?>[] paramTypes = serviceDesc.getFindAll().getParameterTypes();
                    if (paramTypes.length == 2 && paramTypes[0].equals(ServiceContext.class)
                            && paramTypes[1].equals(PagingParameter.class)
                            && serviceDesc.getFindAll().getReturnType().equals(PagedResult.class)) {
                        endRow = endRow < startRow + LOOK_AHEAD ? startRow + LOOK_AHEAD : endRow;
                        PagingParameter pagingParam = PagingParameter.rowAccess(startRow, endRow, LOOK_AHEAD);
                        pagedServiceResult = (PagedResult<?>) serviceDesc.getFindAll()
                                .invoke(serviceDesc.getInstance(), ServiceContextStore.get(), pagingParam);
                        serviceResult = null;
                    } else if (paramTypes.length == 1 && paramTypes[0].equals(ServiceContext.class)) {
                        serviceResult = (List<? extends Object>) serviceDesc.getFindAll()
                                .invoke(serviceDesc.getInstance(), ServiceContextStore.get());
                    } else {
                        serviceResult = null;
                    }
                } else {
                    throw new ApplicationException("", "No fetch operation available");
                }

                if (pagedServiceResult != null) {
                    sendResponse(response.getWriter(), pagedServiceResult);
                } else {
                    int resultSize = serviceResult == null ? 0 : serviceResult.size();
                    endRow = (endRow == 0 ? resultSize : endRow);
                    sendResponse(response.getWriter(), startRow, endRow < resultSize ? endRow : resultSize,
                            serviceResult);
                }
            } else if (operationType.equals("update") && request.getParameter("id") != null) {
                Object val = serviceDesc.getFindById().invoke(serviceDesc.getInstance(),
                        ServiceContextStore.get(), Long.parseLong(request.getParameter("id")));
                HashMap<String, Object> reqData = unifyRequest(request);
                mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val);
                serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(),
                        ServiceContextStore.get(), val);
                ArrayList<Object> list = new ArrayList<Object>();
                list.add(val);
                sendResponse(response.getWriter(), 0, 1, list);
            } else if ((operationType.equals("add") || operationType.equals("update"))
                    && request.getParameter("id") == null) {
                HashMap<String, Object> reqData = unifyRequest(request);
                Object val = makeNewInstance(serviceDesc.getExpectedClass(), reqData);
                if (val != null) {
                    mapRequestToObj(reqData, serviceDesc.getExpectedClass(), val);
                    serviceDesc.getOtherMethods().get("save").method.invoke(serviceDesc.getInstance(),
                            ServiceContextStore.get(), val);
                    ArrayList<Object> list = new ArrayList<Object>();
                    list.add(val);
                    sendResponse(response.getWriter(), 0, 1, list);
                } else {
                    throw makeApplicationException("Can't create new instance", "ERR9003",
                            serviceDesc.getExpectedClass().getName());
                }
            } else {
                throw makeApplicationException("Unsupported operation", "ERR9001", operationType);
            }
        } else {
            throw makeApplicationException("Wrong datasource name", "ERR9002", dataSource);
        }
    } catch (Throwable ex) {
        // Find most relevant exception in embedded exceptions
        ApplicationException appException = null;
        Throwable relevantException = ex;
        while (ex != null) {
            relevantException = ex;
            if (ex instanceof ApplicationException) {
                appException = (ApplicationException) ex;
                break;
            }
            if (ex instanceof ValidationException) {
                break;
            }

            ex = ex.getCause();
        }

        // Prepare message
        String msg = null;
        if (appException != null) {
            msg = translate(appException.getMessage());
            Serializable[] msgParams = appException.getMessageParameters();
            if (msgParams != null) {
                Object[] params = new Object[msgParams.length];
                for (int i = 0; i < msgParams.length; i++) {
                    if (msgParams[i] instanceof Translatable) {
                        params[i] = translate(((Translatable) msgParams[i]).getContent());
                    } else {
                        params[i] = msgParams[i];
                    }
                }
                msg = MessageFormat.format(msg, params);
            }
        } else if (relevantException instanceof ValidationException) {
            StringBuilder b = new StringBuilder();
            for (InvalidValue iv : ((ValidationException) relevantException).getInvalidValues()) {
                b.append("<b>").append(translate(iv.getPropertyName()) + ":</b> " + iv.getMessage())
                        .append("<br/>");
            }
            msg = b.toString();
        } else {
            msg = translate("ERR9000");
            msg = MessageFormat.format(msg,
                    new Object[] { relevantException.getClass().getName(), relevantException.getMessage() });
        }

        // Print stack trace
        log.log(Level.WARNING, "Relevant exception", relevantException);

        if (msg != null) {
            log.log(Level.WARNING, "SENDING BACK ERROR '" + msg + "'");
            response.getWriter()
                    .write("{response:{ status:-1, data:\""
                            + msg.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"")
                            + "\", startRow:0, endRow:0, totalRows:0}}");
        }
        response.flushBuffer();
        // response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        throw new ServletException(msg);
    }
    response.flushBuffer();
}

From source file:com.holonplatform.core.internal.utils.TypeUtils.java

/**
 * Return the type parameter of a generic type.
 * @param clazz subClass of <code>baseClass</code> to analyze.
 * @param baseClass base class having the type parameter the value of which we need to retrieve
 * @return the parameterized type value/*w w w.java  2 s .  c  om*/
 */
@SuppressWarnings("rawtypes")
public static Type getTypeArgument(Class<?> clazz, Class<?> baseClass) {
    Stack<Type> superclasses = new Stack<>();
    Type currentType;
    Class<?> currentClass = clazz;

    if (clazz.getGenericSuperclass() == Object.class) {
        currentType = clazz;
        superclasses.push(currentType);
    } else {

        do {
            currentType = currentClass.getGenericSuperclass();
            superclasses.push(currentType);
            if (currentType instanceof Class) {
                currentClass = (Class) currentType;
            } else if (currentType instanceof ParameterizedType) {
                currentClass = (Class) ((ParameterizedType) currentType).getRawType();
            }
        } while (!currentClass.equals(baseClass));

    }

    // find which one supplies type argument and return it
    TypeVariable tv = baseClass.getTypeParameters()[0];
    while (!superclasses.isEmpty()) {
        currentType = superclasses.pop();

        if (currentType instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) currentType;
            Class<?> rawType = (Class) pt.getRawType();
            int argIndex = Arrays.asList(rawType.getTypeParameters()).indexOf(tv);
            if (argIndex > -1) {
                Type typeArg = pt.getActualTypeArguments()[argIndex];
                if (typeArg instanceof TypeVariable) {
                    // type argument is another type variable - look for the value of that
                    // variable in subclasses
                    tv = (TypeVariable) typeArg;
                    continue;
                } else {
                    // found the value - return it
                    return typeArg;
                }
            }
        }

        // needed type argument not supplied - break and throw exception
        break;
    }
    throw new IllegalArgumentException(currentType + " does not specify a type parameter");
}

From source file:org.netxilia.server.rest.HomeResource.java

/**
 * build the HTML tags for a tree like view
 * //from   w  ww.  java  2  s  .co m
 * @param foldersSheet
 * @param treeview
 * @throws NetxiliaBusinessException
 * @throws NetxiliaResourceException
 */
private DefaultMutableTreeNode buildWorkbookTree(IWorkbook workbook, ISheet foldersSheet,
        Set<SheetFullName> sheetNames) throws NetxiliaResourceException, NetxiliaBusinessException {
    DefaultMutableTreeNode workbookNode = new DefaultMutableTreeNode(
            new TreeViewData(workbook.getId().getKey(), workbook.getName(), "workbook"));

    Stack<DefaultMutableTreeNode> stockNodes = new Stack<DefaultMutableTreeNode>();
    stockNodes.push(workbookNode);

    Set<SheetFullName> alreadyInsertedSheets = new HashSet<SheetFullName>();
    if (foldersSheet != null) {
        Matrix<CellData> folderCells = foldersSheet.receiveCells(AreaReference.ALL).getNonBlocking();
        for (List<CellData> row : folderCells.getRows()) {
            int level = 0;
            String nodeName = null;
            for (CellData cell : row) {
                if (cell.getValue() != null) {
                    nodeName = cell.getValue().getStringValue();
                    if (nodeName != null && nodeName.length() > 0) {
                        level = cell.getReference().getColumnIndex();
                        break;
                    }
                }
            }

            if (nodeName == null) {
                // empty line - ignored
                continue;
            }

            // first level for folders is 1 (under the root node)
            level = level + 1;
            SheetFullName sheetName = new SheetFullName(workbook.getName(), nodeName);
            boolean isSheet = sheetNames.contains(sheetName);
            if (isSheet) {
                alreadyInsertedSheets.add(sheetName);
            }
            DefaultMutableTreeNode crt = new DefaultMutableTreeNode(new TreeViewData(sheetName.toString(),
                    sheetName.getSheetName(), isSheet ? "sheet" : "folder"));
            while (!stockNodes.empty()) {
                DefaultMutableTreeNode node = stockNodes.peek();
                if (level > node.getLevel()) {
                    // make sure is the direct child
                    node.add(crt);
                    break;
                }
                stockNodes.pop();
            }
            stockNodes.push(crt);
        }
    }
    // add the sheets not already added
    for (SheetFullName sheetName : sheetNames) {
        if (alreadyInsertedSheets.contains(sheetName)) {
            continue;
        }
        DefaultMutableTreeNode sheetNode = new DefaultMutableTreeNode(
                new TreeViewData(sheetName.toString(), sheetName.getSheetName(), "sheet"));
        workbookNode.add(sheetNode);
    }

    return workbookNode;
}

From source file:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePattern.java

/**
 * Gives fresh numbers to all nodes in a tree pattern.
 * /* www  . j a v a2s  . c  o m*/
 */
public void renumberNodes() {
    Stack<NavigationTreePatternNode> st = new Stack<NavigationTreePatternNode>();
    st.push(this.root);
    while (!st.empty()) {
        NavigationTreePatternNode pn = st.pop();
        if (pn.getNodeCode() == -1) {
            // nothing
            //Parameters.logger.debug("-1 node! Left unchanged");
        } else {
            pn.setNodeCode(NavigationTreePatternNode.globalNodeCounter.getAndIncrement());
        }
        Iterator<NavigationTreePatternEdge> ie = pn.getEdges().iterator();
        while (ie.hasNext()) {
            st.push(ie.next().n2);
        }
    }
}

From source file:ilcc.ccgparser.incderivation.RevInc.java

private CCGJTreeNode Incrementize(HashMap<Integer, CCGNodeDepInfo> nccgNodeDeps) {
    stack = new Stack<>();
    CCGJTreeNode fnode = null;/* w w  w  . ja  v a 2  s .  co m*/
    List<ArcJAction> acts = new ArrayList<>();

    while (!input.isEmpty()) {
        int cid = input.get(0).getNodeId();
        //calculateWaitTime(cid-1, nccgNodeDeps);
        List<ArcJAction> pacts;
        if ((pacts = actMap.get(cid)) != null) {
            acts.addAll(pacts);
            actMap.remove(cid);
        } else
            acts.add(ArcJAction.make(SRAction.SHIFT, 0, input.get(0).getCCGcat().toString(), RuleType.lexicon));

        actionMap.put(SRAction.SHIFT, actionMap.get(SRAction.SHIFT) + 1);
        shift();
        while (stack.size() >= 2) {
            CCGJTreeNode right = stack.pop();
            CCGJTreeNode left = stack.pop();
            SCoNLLNode cleft = left.getConllNode();
            SCoNLLNode cright = right.getConllNode();
            int id = cright.getNodeId();
            String ccgKey = cleft.getNodeId() + "--" + cright.getNodeId();
            String ccgKey2 = cright.getNodeId() + "--" + cleft.getNodeId();
            /*
            if(specialcase(left, right)){
            stack.push(left);
            stack.push(right);
            break;
            }
            */

            if ((nccgNodeDeps.containsKey(id) && nccgNodeDeps.get(id).ldepsize() > 0)
                    || drvDeps.containsKey(ccgKey) || drvDeps.containsKey(ccgKey2)
                    || cright.getWrd().equals(cright.getPOS())) {
                Pair<CCGJTreeNode, ArcJAction> tuple = checkAndApplyAction(left, right, ccgKey, nccgNodeDeps);
                if (tuple == null || tuple.getLeft() == null) {
                    stack.push(left);
                    stack.push(right);
                    //fillUnResolveList(left, right, drvDeps.get(ccgKey));
                    break;
                }
                try {
                    ArcJAction act = tuple.getRight();
                    acts.add(act);
                    CCGJTreeNode result = tuple.getLeft();
                    CCGcat lcat = left.getCCGcat(), rcat = right.getCCGcat(), rescat = result.getCCGcat();
                    boolean headIsLeft = (act.getAction() != SRAction.RL);
                    //if( (act.getRuleType() != RuleType.rreveal) && (act.getRuleType() != RuleType.lreveal) ){
                    CCGJRuleInfo info = new CCGJRuleInfo(lcat, rcat, rescat, headIsLeft, act.getRuleType(),
                            act.getLevel(), 0);
                    if (act.getRuleType() == RuleType.lreveal)
                        treebankRules.addRevealRuleInfo(info, lcat.toString() + " " + rcat.toString());
                    else if (act.getRuleType() != RuleType.rreveal)
                        treebankRules.addBinaryRuleInfo(info, lcat.toString() + " " + rcat.toString());
                } catch (Exception ex) {
                    System.err.println(ex);
                }
            } else {
                stack.push(left);
                stack.push(right);
                break;
            }
        }
    }
    if (!stack.empty()) {
        fnode = stack.peek();
        actMap.put(fnode.getConllNode().getNodeId(), acts);
    }
    if (stack.size() != 1) {
        //System.err.println(sentCount+" : "+sent.getLength()+" : Couldn't incrementalize completely : "+ stack.toString());
        uncov = true;
    }
    return fnode;
}

From source file:com.amazonaws.services.kinesis.scaling.StreamScaler.java

private Stack<ShardHashInfo> getOpenShardStack(String streamName) throws Exception {
    // populate the stack with the current set of shards
    Stack<ShardHashInfo> shardStack = new Stack<>();
    List<ShardHashInfo> shards = new ArrayList<>(StreamScalingUtils
            .getOpenShards(this.kinesisClient, streamName, SortOrder.DESCENDING, null).values());
    for (ShardHashInfo s : shards) {
        shardStack.push(s);/*from  ww  w.j  a va2  s. c  om*/
    }

    return shardStack;
}

From source file:biz.source_code.miniConnectionPoolManager.TestMiniConnectionPoolManager.java

/**
    * Constructs a MiniConnectionPoolManager object.
    * @param dataSource      the data source for the connections.
    * @param maxConnections  the maximum number of connections.
    * @param timeout         the maximum time in seconds to wait for a free connection.
    */// w  w  w.  j a v  a 2 s.co m
    public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource, int maxConnections, int timeout) {
        this.dataSource = dataSource;
        this.maxConnections = maxConnections;
        this.timeout = timeout;
        try {
            logWriter = dataSource.getLogWriter();
        } catch (SQLException e) {
        }
        if (maxConnections < 1)
            throw new IllegalArgumentException("Invalid maxConnections value.");
        semaphore = new Semaphore(maxConnections, true);
        recycledConnections = new Stack<PooledConnection>();
        poolConnectionEventListener = new PoolConnectionEventListener();
    }

From source file:com.abstratt.mdd.internal.frontend.textuml.TextUMLCompiler.java

/**
 * Given a position in a compilation unit, finds the contextual package name. 
 * /*from  w  ww.j a  v  a  2  s .  c  o m*/
 * @param toParse source of compilation unit
 * @param line line number, starting from 1
 * @param col column number, starting from 1
 * @return the name of the contextual package
 */
public String findPackageName(String toParse, final int line, final int col) {
    Token token = findTokenAt(toParse, line, col);
    if (token == null)
        return null;
    final Stack<String> segments = new Stack<String>();
    for (Node current = token; current != null; current = current.parent()) {
        current.apply(new AnalysisAdapter() {
            @Override
            public void caseAStart(AStart node) {
                segments.push(TextUMLCore.getSourceMiner().getQualifiedIdentifier(
                        ((APackageHeading) node.getPackageHeading()).getQualifiedIdentifier()));
            }

            public void caseASubNamespace(ASubNamespace node) {
                segments.push(TextUMLCore.getSourceMiner()
                        .getQualifiedIdentifier(((APackageHeading) node.getPackageHeading())));
            }
        });
    }
    if (segments.isEmpty())
        return null;
    StringBuffer result = new StringBuffer();
    while (!segments.isEmpty()) {
        result.append(segments.pop());
        result.append(NamedElement.SEPARATOR);
    }
    result.delete((result.length() - NamedElement.SEPARATOR.length()), result.length());
    return result.toString();
}

From source file:com.unboundid.scim2.common.utils.Parser.java

/**
 * Read a filter from the reader./*ww  w.  jav  a  2 s .  c  om*/
 *
 * @param reader The reader to read the filter from.
 * @param isValueFilter Whether to read the filter as a value filter.
 * @return The parsed filter.
 * @throws BadRequestException If the filter string could not be parsed.
 */
private static Filter readFilter(final StringReader reader, final boolean isValueFilter)
        throws BadRequestException {
    final Stack<Filter> outputStack = new Stack<Filter>();
    final Stack<String> precedenceStack = new Stack<String>();

    String token;
    String previousToken = null;

    while ((token = readFilterToken(reader, isValueFilter)) != null) {
        if (token.equals("(") && expectsNewFilter(previousToken)) {
            precedenceStack.push(token);
        } else if (token.equalsIgnoreCase(FilterType.NOT.getStringValue()) && expectsNewFilter(previousToken)) {
            // "not" should be followed by an (
            String nextToken = readFilterToken(reader, isValueFilter);
            if (nextToken == null) {
                throw BadRequestException.invalidFilter("Unexpected end of filter string");
            }
            if (!nextToken.equals("(")) {
                final String msg = String.format("Expected '(' at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }
            precedenceStack.push(token);
        } else if (token.equals(")") && !expectsNewFilter(previousToken)) {
            String operator = closeGrouping(precedenceStack, outputStack, false);
            if (operator == null) {
                final String msg = String.format(
                        "No opening parenthesis matching closing " + "parenthesis at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }
            if (operator.equalsIgnoreCase(FilterType.NOT.getStringValue())) {
                // Treat "not" the same as "(" except wrap everything in a not filter.
                outputStack.push(Filter.not(outputStack.pop()));
            }
        } else if (token.equalsIgnoreCase(FilterType.AND.getStringValue())
                && !expectsNewFilter(previousToken)) {
            // and has higher precedence than or.
            precedenceStack.push(token);
        } else if (token.equalsIgnoreCase(FilterType.OR.getStringValue()) && !expectsNewFilter(previousToken)) {
            // pop all the pending ands first before pushing or.
            LinkedList<Filter> andComponents = new LinkedList<Filter>();
            while (!precedenceStack.isEmpty()) {
                if (precedenceStack.peek().equalsIgnoreCase(FilterType.AND.getStringValue())) {
                    precedenceStack.pop();
                    andComponents.addFirst(outputStack.pop());
                } else {
                    break;
                }
                if (!andComponents.isEmpty()) {
                    andComponents.addFirst(outputStack.pop());
                    outputStack.push(Filter.and(andComponents));
                }
            }

            precedenceStack.push(token);
        } else if (token.endsWith("[") && expectsNewFilter(previousToken)) {
            // This is a complex value filter.
            final Path filterAttribute;
            try {
                filterAttribute = parsePath(token.substring(0, token.length() - 1));
            } catch (final BadRequestException e) {
                Debug.debugException(e);
                final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark,
                        e.getMessage());
                throw BadRequestException.invalidFilter(msg);
            }

            if (filterAttribute.isRoot()) {
                final String msg = String.format("Attribute path expected at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }

            outputStack.push(Filter.hasComplexValue(filterAttribute, readFilter(reader, true)));
        } else if (isValueFilter && token.equals("]") && !expectsNewFilter(previousToken)) {
            break;
        } else if (expectsNewFilter(previousToken)) {
            // This must be an attribute path followed by operator and maybe value.
            final Path filterAttribute;
            try {
                filterAttribute = parsePath(token);
            } catch (final BadRequestException e) {
                Debug.debugException(e);
                final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark,
                        e.getMessage());
                throw BadRequestException.invalidFilter(msg);
            }

            if (filterAttribute.isRoot()) {
                final String msg = String.format("Attribute path expected at position %d", reader.mark);
                throw BadRequestException.invalidFilter(msg);
            }

            String op = readFilterToken(reader, isValueFilter);

            if (op == null) {
                throw BadRequestException.invalidFilter("Unexpected end of filter string");
            }

            if (op.equalsIgnoreCase(FilterType.PRESENT.getStringValue())) {
                outputStack.push(Filter.pr(filterAttribute));
            } else {
                ValueNode valueNode;
                try {
                    // Mark the beginning of the JSON value so we can later reset back
                    // to this position and skip the actual chars that were consumed
                    // by Jackson. The Jackson parser is buffered and reads everything
                    // until the end of string.
                    reader.mark(0);
                    ScimJsonFactory scimJsonFactory = (ScimJsonFactory) JsonUtils.getObjectReader()
                            .getFactory();
                    JsonParser parser = scimJsonFactory.createScimFilterParser(reader);
                    // The object mapper will return a Java null for JSON null.
                    // Have to distinguish between reading a JSON null and encountering
                    // the end of string.
                    if (parser.getCurrentToken() == null && parser.nextToken() == null) {
                        // End of string.
                        valueNode = null;
                    } else {
                        valueNode = parser.readValueAsTree();

                        // This is actually a JSON null. Use NullNode.
                        if (valueNode == null) {
                            valueNode = JsonUtils.getJsonNodeFactory().nullNode();
                        }
                    }
                    // Reset back to the beginning of the JSON value.
                    reader.reset();
                    // Skip the number of chars consumed by JSON parser.
                    reader.skip(parser.getCurrentLocation().getCharOffset());
                } catch (IOException e) {
                    final String msg = String.format("Invalid comparison value at position %d: %s", reader.mark,
                            e.getMessage());
                    throw BadRequestException.invalidFilter(msg);
                }

                if (valueNode == null) {
                    throw BadRequestException.invalidFilter("Unexpected end of filter string");
                }

                if (op.equalsIgnoreCase(FilterType.EQUAL.getStringValue())) {
                    outputStack.push(Filter.eq(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.NOT_EQUAL.getStringValue())) {
                    outputStack.push(Filter.ne(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.CONTAINS.getStringValue())) {
                    outputStack.push(Filter.co(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.STARTS_WITH.getStringValue())) {
                    outputStack.push(Filter.sw(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.ENDS_WITH.getStringValue())) {
                    outputStack.push(Filter.ew(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.GREATER_THAN.getStringValue())) {
                    outputStack.push(Filter.gt(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.GREATER_OR_EQUAL.getStringValue())) {
                    outputStack.push(Filter.ge(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.LESS_THAN.getStringValue())) {
                    outputStack.push(Filter.lt(filterAttribute, valueNode));
                } else if (op.equalsIgnoreCase(FilterType.LESS_OR_EQUAL.getStringValue())) {
                    outputStack.push(Filter.le(filterAttribute, valueNode));
                } else {
                    final String msg = String.format("Unrecognized attribute operator '%s' at position %d. "
                            + "Expected: eq,ne,co,sw,ew,pr,gt,ge,lt,le", op, reader.mark);
                    throw BadRequestException.invalidFilter(msg);
                }
            }
        } else {
            final String msg = String.format("Unexpected character '%s' at position %d", token, reader.mark);
            throw BadRequestException.invalidFilter(msg);
        }
        previousToken = token;
    }

    closeGrouping(precedenceStack, outputStack, true);

    if (outputStack.isEmpty()) {
        throw BadRequestException.invalidFilter("Unexpected end of filter string");
    }
    return outputStack.pop();
}

From source file:net.dv8tion.jda.entities.impl.MessageImpl.java

@Override
public String getStrippedContent() {
    if (strippedContent == null) {
        String tmp = getContent();
        //all the formatting keys to keep track of
        String[] keys = new String[] { "*", "_", "`", "~~" };

        //find all tokens (formatting strings described above)
        TreeSet<FormatToken> tokens = new TreeSet<>((t1, t2) -> Integer.compare(t1.start, t2.start));
        for (String key : keys) {
            Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp);
            while (matcher.find()) {
                tokens.add(new FormatToken(key, matcher.start()));
            }//from w  ww . j a v a 2  s . c om
        }

        //iterate over all tokens, find all matching pairs, and add them to the list toRemove
        Stack<FormatToken> stack = new Stack<>();
        List<FormatToken> toRemove = new ArrayList<>();
        boolean inBlock = false;
        for (FormatToken token : tokens) {
            if (stack.empty() || !stack.peek().format.equals(token.format)
                    || stack.peek().start + token.format.length() == token.start) {
                //we are at opening tag
                if (!inBlock) {
                    //we are outside of block -> handle normally
                    if (token.format.equals("`")) {
                        //block start... invalidate all previous tags
                        stack.clear();
                        inBlock = true;
                    }
                    stack.push(token);
                } else if (token.format.equals("`")) {
                    //we are inside of a block -> handle only block tag
                    stack.push(token);
                }
            } else if (!stack.empty()) {
                //we found a matching close-tag
                toRemove.add(stack.pop());
                toRemove.add(token);
                if (token.format.equals("`") && stack.empty()) {
                    //close tag closed the block
                    inBlock = false;
                }
            }
        }

        //sort tags to remove by their start-index and iteratively build the remaining string
        Collections.sort(toRemove, (t1, t2) -> Integer.compare(t1.start, t2.start));
        StringBuilder out = new StringBuilder();
        int currIndex = 0;
        for (FormatToken formatToken : toRemove) {
            if (currIndex < formatToken.start) {
                out.append(tmp.substring(currIndex, formatToken.start));
            }
            currIndex = formatToken.start + formatToken.format.length();
        }
        if (currIndex < tmp.length()) {
            out.append(tmp.substring(currIndex));
        }
        //return the stripped text, escape all remaining formatting characters (did not have matching open/close before or were left/right of block
        strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");
    }
    return strippedContent;
}