Example usage for java.util StringTokenizer countTokens

List of usage examples for java.util StringTokenizer countTokens

Introduction

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

Prototype

public int countTokens() 

Source Link

Document

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

Usage

From source file:org.LexGrid.LexBIG.caCore.web.util.LexEVSHTTPUtils.java

/**
 * Returns fully qualified search class names
 * @param searchClasses - specifies the search class names
 * @param packageName - specifies the package name
 * @return//from  w  ww. j a v  a 2s .c o m
 */
private String getSearchClassNames(String searchClasses) throws Exception {
    String path = "";

    /**
    if(packageName != null && !(targetClassName.indexOf(SystemConstant.DOT)>0) && (targetClassName.indexOf(",")<0)){
      targetClassName = packageName +SystemConstant.DOT+targetClassName;
    }
     **/
    String delimiter = null;
    if (searchClasses.indexOf(SystemConstant.FORWARD_SLASH) > 0) {
        delimiter = SystemConstant.FORWARD_SLASH_STR;
    } else {
        delimiter = SystemConstant.COMMA_STR;
    }
    StringTokenizer st = new StringTokenizer(searchClasses, delimiter);

    String className = st.nextToken();
    if (className.indexOf(SystemConstant.DOT) > 0) {
        path = className;
    } else {
        path = classCache.getQualifiedClassName(className);
    }

    if (st.countTokens() > 0) {
        while (st.hasMoreElements()) {
            className = st.nextToken().trim();
            if (className.indexOf(SystemConstant.DOT) > 0) {
                path += SystemConstant.COMMA + className;
            } else {
                path += SystemConstant.COMMA + classCache.getQualifiedClassName(className);
            }
        }
    }
    return path;
}

From source file:hydrograph.ui.dataviewer.filter.FilterHelper.java

/**
 * Gets the condition value./*  w  w  w . j  a  va2  s  . c  om*/
 * 
 * @param fieldName
 *            the field name
 * @param value
 *            the value
 * @param conditional
 *            the conditional
 * @param fieldsAndTypes
 *            the fields and types
 * @param isDisplayPressed
 *            the is display pressed
 * @return the condition value
 */
protected String getConditionValue(String fieldName, String value, String conditional,
        Map<String, String> fieldsAndTypes, boolean isDisplayPressed) {
    String trimmedCondition = StringUtils.trim(conditional);
    String dataType = fieldsAndTypes.get(fieldName);
    if ((FilterConstants.TYPE_STRING.equalsIgnoreCase(dataType)
            || FilterConstants.TYPE_DATE.equalsIgnoreCase(dataType)
            || FilterConstants.TYPE_BOOLEAN.equalsIgnoreCase(dataType)) && !conditional.endsWith("(Field)")) {
        if (FilterConstants.IN.equalsIgnoreCase(trimmedCondition)
                || FilterConstants.NOT_IN.equalsIgnoreCase(trimmedCondition)) {
            if (StringUtils.isNotBlank(value) && value.contains(FilterConstants.DELIM_COMMA)) {
                StringTokenizer tokenizer = new StringTokenizer(value, FilterConstants.DELIM_COMMA);
                StringBuffer temp = new StringBuffer();
                int numberOfTokens = tokenizer.countTokens();
                temp.append(FilterConstants.OPEN_BRACKET);
                for (int index = 0; index < numberOfTokens; index++) {
                    if (FilterConstants.TYPE_DATE.equalsIgnoreCase(dataType) && !isDisplayPressed) {
                        try {
                            Fields dataViewerFileSchema = getSchema();
                            SimpleDateFormat formatter = getDateFormatter(fieldName, dataViewerFileSchema);
                            Date parsedDate = getParsedDate(tokenizer.nextToken(), formatter);
                            temp.append(FilterConstants.SINGLE_QOUTE).append(formatter.format(parsedDate))
                                    .append(FilterConstants.SINGLE_QOUTE);
                        } catch (ParseException parseException) {
                            logger.error("Error while parsing date value", parseException);
                        }
                    } else {
                        temp.append(FilterConstants.SINGLE_QOUTE).append(tokenizer.nextToken())
                                .append(FilterConstants.SINGLE_QOUTE);
                    }
                    if (index < numberOfTokens - 1) {
                        temp.append(FilterConstants.DELIM_COMMA);
                    }
                }
                temp.append(FilterConstants.CLOSE_BRACKET);
                return temp.toString();
            } else {
                return FilterConstants.OPEN_BRACKET + FilterConstants.SINGLE_QOUTE + value
                        + FilterConstants.SINGLE_QOUTE + FilterConstants.CLOSE_BRACKET;
            }
        } else {
            if (!isDisplayPressed) {
                if (FilterConstants.TYPE_DATE.equalsIgnoreCase(dataType)) {
                    try {
                        Fields dataViewerFileSchema = getSchema();
                        SimpleDateFormat formatter = getDateFormatter(fieldName, dataViewerFileSchema);
                        Date parsedDate = getParsedDate(value, formatter);
                        return FilterConstants.SINGLE_QOUTE + formatter.format(parsedDate)
                                + FilterConstants.SINGLE_QOUTE;
                    } catch (ParseException parseException) {
                        logger.error("Error while parsing date value", parseException);
                    }
                } else {
                    return FilterConstants.SINGLE_QOUTE + value + FilterConstants.SINGLE_QOUTE;
                }
                return null;
            } else {
                return FilterConstants.SINGLE_QOUTE + value + FilterConstants.SINGLE_QOUTE;
            }

        }
    } else {
        if (FilterConstants.IN.equalsIgnoreCase(trimmedCondition)
                || FilterConstants.NOT_IN.equalsIgnoreCase(trimmedCondition)) {
            return FilterConstants.OPEN_BRACKET + value + FilterConstants.CLOSE_BRACKET;
        } else {
            return value;
        }
    }
}

From source file:de.betterform.xml.xforms.model.submission.Submission.java

/**
 * Performs submission attribute defaulting.
 * <p/>/*from w  ww.j  av  a2s.  c  o m*/
 * Supports XForms 1.1 relevant and validate attributes. However, this
 * support should be externalized in a - say Submission11 - class which
 * simply overwrites this template method.
 */
protected void initializeSubmission() throws XFormsException {
    // 1. init binding context
    // path expression
    this.locationPath = "/";
    String refAttribute = getXFormsAttribute(REF_ATTRIBUTE);
    if (refAttribute != null) {
        this.locationPath = refAttribute;
    }
    String bindAttribute = getXFormsAttribute(BIND_ATTRIBUTE);
    if (bindAttribute != null) {
        Object bindObject = this.container.lookup(bindAttribute);
        if (bindObject == null || !(bindObject instanceof Bind)) {
            throw new XFormsBindingException(
                    "invalid bind id at " + DOMUtil.getCanonicalPath(this.getElement()), this.target,
                    bindAttribute);
        }

        this.locationPath = ((Bind) bindObject).getLocationPath();
    }

    // instance id
    this.instanceId = this.model.computeInstanceId(this.locationPath);

    // 2. submission options
    // get required method attribute
    this.method = new AttributeOrValueChild(this.element, this.model, METHOD_ATTRIBUTE);
    this.method.init();
    if (this.method == null) {
        // complain
        throw new XFormsLinkException("no method specified for submission", this.target, null);
    }

    // get optional version attribute
    this.version = getXFormsAttribute(VERSION_ATTRIBUTE);
    if (this.version == null) {
        this.version = "1.0"; // setting default
    }

    // get optional indent attribute
    String indentAttribute = getXFormsAttribute(INDENT_ATTRIBUTE);
    if (indentAttribute != null) {
        this.indent = Boolean.valueOf(indentAttribute);
    } else {
        this.indent = false; // setting default
    }

    // get optional mediatype attribute
    this.mediatype = getXFormsAttribute(MEDIATYPE_ATTRIBUTE);
    if (this.mediatype == null) {
        this.mediatype = "application/xml"; //setting default
    }

    // get optional encoding attribute
    this.encoding = getXFormsAttribute(ENCODING_ATTRIBUTE);
    if (this.encoding == null) {
        this.encoding = "UTF-8"; // setting default
    }

    // get optional omit-xml-declaration attribute
    String omitxmldeclarationAttribute = getXFormsAttribute(OMIT_XML_DECLARATION_ATTRIBUTE);
    if (omitxmldeclarationAttribute != null) {
        this.omitxmldeclaration = "true".equals(omitxmldeclarationAttribute)
                || "1".equals(omitxmldeclarationAttribute);
    } else {
        this.omitxmldeclaration = false;
    }

    // get optional standalone attribute
    String standaloneAttribute = getXFormsAttribute(STANDALONE_ATTRIBUTE);
    if (standaloneAttribute != null) {
        this.standalone = Boolean.valueOf(standaloneAttribute);
    }

    // get optional cdata-section-elements attribute
    this.cdatasectionelements = getXFormsAttribute(CDATA_SECTION_ELEMENTS_ATTRIBUTE);

    // get optional action attribute
    this.separator = getXFormsAttribute(SEPARATOR_ATTRIBUTE);
    if (this.separator == null) {
        // default per schema
        this.separator = "&";
    }

    // get optional includenamespaceprefixes attribute
    String includenamespaceprefixesAttribute = getXFormsAttribute(INCLUDENAMESPACEPREFIXES_ATTRIBUTE);
    if (includenamespaceprefixesAttribute != null) {
        StringTokenizer tokenizer = new StringTokenizer(includenamespaceprefixesAttribute);
        this.includenamespaceprefixes = new ArrayList<String>(tokenizer.countTokens());

        while (tokenizer.hasMoreTokens()) {
            this.includenamespaceprefixes.add(tokenizer.nextToken());
        }
    }

    // get optional replace attribute
    this.replace = getXFormsAttribute(REPLACE_ATTRIBUTE);
    if (this.replace == null) {
        // default per schema
        this.replace = "all";
    }

    // get optional instance attribute
    this.instance = getXFormsAttribute(INSTANCE_ATTRIBUTE);

    // get optional target attribute

    this.targetExpr = getXFormsAttribute(TARGETREF_ATTRIBUTE);
    if (targetExpr == null) {
        //try deprecated 'target' attrbute
        if (getXFormsAttribute(TARGET_ATTRIBUTE) != null) {
            this.targetExpr = getXFormsAttribute(TARGET_ATTRIBUTE);
            LOGGER.warn("'target' Attribute is deprecated - Please use 'targetref' instead.");
        }
    }

    // check for cross model submission
    if (this.targetExpr != null && this.targetExpr.startsWith("model('")) {
        targetModelId = this.targetExpr.substring(this.targetExpr.indexOf("'") + 1);
        targetModelId = targetModelId.substring(0, targetModelId.indexOf("'"));

        if (targetModelId != null && !targetModelId.equals("")) {
            this.targetExpr = this.targetExpr.replace("model('" + targetModelId + "')", "");
            if (targetExpr.equals("")) {
                targetExpr = null;
            }
        }

    }

    // 3. XForms 1.1 support

    // XForms 1.0 Version
    if (this.container.getVersion().equals(Container.XFORMS_1_0)) {
        this.action = getXFormsAttribute(ACTION_ATTRIBUTE);
        if (this.action == null) {
            throw new XFormsLinkException("no action or resource specified for submission", this.target, null);
        }
    } else {
        // initialize XForms 1.1 submission children
        initializeSubmissionOptions();
        // XForms Version > 1.0 or not set
        this.resource = new AttributeOrValueChild(this.element, this.model, RESOURCE_ATTRIBUTE);
        this.resource.init();
        if (!resource.isAvailable()) {
            // handle action attribtue
            this.action = getXFormsAttribute(ACTION_ATTRIBUTE);
        }
        // either resource or action must be set
        if (!this.resource.isAvailable() && this.action == null) {
            //todo: this should be corrected as resouce may be empty due to spec see the xforms-submit event and 'validation-error'
            throw new XFormsLinkException("no action or resource specified for submission", this.target, null);
        } else if (this.resource == null) {
            getLogger().warn(toString() + " relying on deprecated action attribute");
        }
    }

    // ##### validation and serailization must be handled together #####
    this.validate = true; //default

    //get serialization attribute. If serialization is 'none' validate defaults to false
    this.serialization = getXFormsAttribute(SERIALIZATION_ATTRIBUTE);
    if (this.serialization != null && this.serialization.equalsIgnoreCase("none")) {
        this.validate = false; // setting default when not serialized that might get overwritten by evaluation of validateAttribute below
    }

    // get optional validate attribute
    String validateAttribute = getXFormsAttribute(VALIDATE_ATTRIBUTE);
    if (validateAttribute != null) {
        this.validate = Boolean.valueOf(validateAttribute);
    }

    // get optional relevant attribute
    String relevantAttribute = getXFormsAttribute(RELEVANT_ATTRIBUTE);
    this.relevant = relevantAttribute != null ? Boolean.valueOf(relevantAttribute) : Boolean.TRUE;

}

From source file:helma.framework.core.RequestEvaluator.java

/**
 *
 *//*from  w ww.java2 s . co m*/
public void run() {
    // first, set a local variable to the current transactor thread so we know
    // when it's time to quit because another thread took over.
    Thread localThread = Thread.currentThread();

    // spans whole execution loop - close connections in finally clause
    try {

        // while this thread is serving requests
        while (localThread == thread) {

            // object reference to ressolve request path
            Object currentElement;

            // Get req and res into local variables to avoid memory caching problems
            // in unsynchronized method.
            RequestTrans req = getRequest();
            ResponseTrans res = getResponse();

            // request path object
            RequestPath requestPath = new RequestPath(app);

            String txname = req.getMethod() + ":" + req.getPath();
            Log eventLog = app.getEventLog();
            if (eventLog.isDebugEnabled()) {
                eventLog.debug(txname + " starting");
            }

            int tries = 0;
            boolean done = false;
            Throwable error = null;
            String functionName = function instanceof String ? (String) function : null;

            while (!done && localThread == thread) {
                // catch errors in path resolution and script execution
                try {

                    // initialize scripting engine
                    initScriptingEngine();
                    app.setCurrentRequestEvaluator(this);
                    // update scripting prototypes
                    scriptingEngine.enterContext();

                    // avoid going into transaction if called function doesn't exist.
                    // this only works for the (common) case that method is a plain
                    // method name, not an obj.method path
                    if (reqtype == INTERNAL) {
                        // if object is an instance of NodeHandle, get the node object itself.
                        if (thisObject instanceof NodeHandle) {
                            thisObject = ((NodeHandle) thisObject).getNode(app.nmgr.safe);
                            // If no valid node object return immediately
                            if (thisObject == null) {
                                done = true;
                                reqtype = NONE;
                                break;
                            }
                        }
                        // If function doesn't exist, return immediately
                        if (functionName != null
                                && !scriptingEngine.hasFunction(thisObject, functionName, true)) {
                            app.logEvent(missingFunctionMessage(thisObject, functionName));
                            done = true;
                            reqtype = NONE;
                            break;
                        }
                    } else if (function != null && functionName == null) {
                        // only internal requests may pass a function instead of a function name
                        throw new IllegalStateException("No function name in non-internal request ");
                    }

                    // Update transaction name in case we're processing an error
                    if (error != null) {
                        txname = "error:" + txname;
                    }

                    // begin transaction
                    transactor = Transactor.getInstance(app.nmgr);
                    transactor.begin(txname);

                    Object root = app.getDataRoot(scriptingEngine);
                    initGlobals(root, requestPath);

                    String action = null;

                    if (error != null) {
                        res.setError(error);
                    }

                    switch (reqtype) {
                    case HTTP:

                        // bring over the message from a redirect
                        session.recoverResponseMessages(res);

                        // catch redirect in path resolution or script execution
                        try {
                            // catch object not found in path resolution
                            try {
                                if (error != null) {
                                    // there was an error in the previous loop, call error handler
                                    currentElement = root;
                                    res.setStatus(500);

                                    // do not reset the requestPath so error handler can use the original one
                                    // get error handler action
                                    String errorAction = app.props.getProperty("error", "error");

                                    action = getAction(currentElement, errorAction, req);

                                    if (action == null) {
                                        throw new RuntimeException(error);
                                    }
                                } else if ((req.getPath() == null) || "".equals(req.getPath().trim())) {
                                    currentElement = root;
                                    requestPath.add(null, currentElement);

                                    action = getAction(currentElement, null, req);

                                    if (action == null) {
                                        throw new NotFoundException("Action not found");
                                    }
                                } else {
                                    // march down request path...
                                    StringTokenizer st = new StringTokenizer(req.getPath(), "/");
                                    int ntokens = st.countTokens();

                                    // limit path to < 50 tokens
                                    if (ntokens > 50) {
                                        throw new RuntimeException("Path too long");
                                    }

                                    String[] pathItems = new String[ntokens];

                                    for (int i = 0; i < ntokens; i++)
                                        pathItems[i] = st.nextToken();

                                    currentElement = root;
                                    requestPath.add(null, currentElement);

                                    for (int i = 0; i < ntokens; i++) {
                                        if (currentElement == null) {
                                            throw new NotFoundException("Object not found.");
                                        }

                                        if (pathItems[i].length() == 0) {
                                            continue;
                                        }

                                        // if we're at the last element of the path,
                                        // try to interpret it as action name.
                                        if (i == (ntokens - 1) && !req.getPath().endsWith("/")) {
                                            action = getAction(currentElement, pathItems[i], req);
                                        }

                                        if (action == null) {
                                            currentElement = getChildElement(currentElement, pathItems[i]);

                                            // add object to request path if suitable
                                            if (currentElement != null) {
                                                // add to requestPath array
                                                requestPath.add(pathItems[i], currentElement);
                                            }
                                        }
                                    }

                                    if (currentElement == null) {
                                        throw new NotFoundException("Object not found.");
                                    }

                                    if (action == null) {
                                        action = getAction(currentElement, null, req);
                                    }

                                    if (action == null) {
                                        throw new NotFoundException("Action not found");
                                    }
                                }
                            } catch (NotFoundException notfound) {
                                if (error != null) {

                                    // we already have an error and the error template wasn't found,
                                    // display it instead of notfound message
                                    throw new RuntimeException();
                                }

                                // The path could not be resolved. Check if there is a "not found" action
                                // specified in the property file.
                                res.setStatus(404);

                                String notFoundAction = app.props.getProperty("notfound", "notfound");

                                currentElement = root;
                                action = getAction(currentElement, notFoundAction, req);

                                if (action == null) {
                                    throw new NotFoundException(notfound.getMessage());
                                }
                            }

                            // register path objects with their prototype names in
                            // res.handlers
                            Map macroHandlers = res.getMacroHandlers();
                            int l = requestPath.size();
                            Prototype[] protos = new Prototype[l];

                            for (int i = 0; i < l; i++) {

                                Object obj = requestPath.get(i);

                                protos[i] = app.getPrototype(obj);

                                // immediately register objects with their direct prototype name
                                if (protos[i] != null) {
                                    macroHandlers.put(protos[i].getName(), obj);
                                    macroHandlers.put(protos[i].getLowerCaseName(), obj);
                                }
                            }

                            // in a second pass, we register path objects with their indirect
                            // (i.e. parent prototype) names, starting at the end and only
                            // if the name isn't occupied yet.
                            for (int i = l - 1; i >= 0; i--) {
                                if (protos[i] != null) {
                                    protos[i].registerParents(macroHandlers, requestPath.get(i));
                                }
                            }

                            /////////////////////////////////////////////////////////////////////////////
                            // end of path resolution section
                            /////////////////////////////////////////////////////////////////////////////
                            // beginning of execution section

                            // set the req.action property, cutting off the _action suffix
                            req.setAction(action);

                            // reset skin recursion detection counter
                            skinDepth = 0;

                            // try calling onRequest() function on object before
                            // calling the actual action
                            scriptingEngine.invoke(currentElement, "onRequest", EMPTY_ARGS,
                                    ScriptingEngine.ARGS_WRAP_DEFAULT, false);

                            // reset skin recursion detection counter
                            skinDepth = 0;

                            Object actionProcessor = req.getActionHandler() != null ? req.getActionHandler()
                                    : action;

                            // do the actual action invocation
                            if (req.isXmlRpc()) {
                                XmlRpcRequestProcessor xreqproc = new XmlRpcRequestProcessor();
                                XmlRpcServerRequest xreq = xreqproc
                                        .decodeRequest(req.getServletRequest().getInputStream());
                                Vector args = xreq.getParameters();
                                args.add(0, xreq.getMethodName());
                                result = scriptingEngine.invoke(currentElement, actionProcessor, args.toArray(),
                                        ScriptingEngine.ARGS_WRAP_XMLRPC, false);
                                res.writeXmlRpcResponse(result);
                                app.xmlrpcCount += 1;
                            } else {
                                scriptingEngine.invoke(currentElement, actionProcessor, EMPTY_ARGS,
                                        ScriptingEngine.ARGS_WRAP_DEFAULT, false);
                            }

                            // try calling onResponse() function on object before
                            // calling the actual action
                            scriptingEngine.invoke(currentElement, "onResponse", EMPTY_ARGS,
                                    ScriptingEngine.ARGS_WRAP_DEFAULT, false);

                        } catch (RedirectException redirect) {
                            // if there is a message set, save it on the user object for the next request
                            if (res.getRedirect() != null)
                                session.storeResponseMessages(res);
                        }

                        // check if request is still valid, or if the requesting thread has stopped waiting already
                        if (localThread != thread) {
                            return;
                        }
                        commitTransaction();
                        done = true;

                        break;

                    case XMLRPC:
                    case EXTERNAL:

                        try {
                            currentElement = root;

                            if (functionName.indexOf('.') > -1) {
                                StringTokenizer st = new StringTokenizer(functionName, ".");
                                int cnt = st.countTokens();

                                for (int i = 1; i < cnt; i++) {
                                    String next = st.nextToken();
                                    currentElement = getChildElement(currentElement, next);
                                }

                                if (currentElement == null) {
                                    throw new NotFoundException(
                                            "Method name \"" + function + "\" could not be resolved.");
                                }

                                functionName = st.nextToken();
                            }

                            if (reqtype == XMLRPC) {
                                // check XML-RPC access permissions
                                String proto = app.getPrototypeName(currentElement);
                                app.checkXmlRpcAccess(proto, functionName);
                            }

                            // reset skin recursion detection counter
                            skinDepth = 0;
                            if (!scriptingEngine.hasFunction(currentElement, functionName, false)) {
                                throw new NotFoundException(
                                        missingFunctionMessage(currentElement, functionName));
                            }
                            result = scriptingEngine.invoke(currentElement, functionName, args,
                                    ScriptingEngine.ARGS_WRAP_XMLRPC, false);
                            // check if request is still valid, or if the requesting thread has stopped waiting already
                            if (localThread != thread) {
                                return;
                            }
                            commitTransaction();
                        } catch (Exception x) {
                            // check if request is still valid, or if the requesting thread has stopped waiting already
                            if (localThread != thread) {
                                return;
                            }
                            abortTransaction();
                            app.logError(txname + " " + error, x);

                            // If the transactor thread has been killed by the invoker thread we don't have to
                            // bother for the error message, just quit.
                            if (localThread != thread) {
                                return;
                            }

                            this.exception = x;
                        }

                        done = true;
                        break;

                    case INTERNAL:

                        try {
                            // reset skin recursion detection counter
                            skinDepth = 0;

                            result = scriptingEngine.invoke(thisObject, function, args,
                                    ScriptingEngine.ARGS_WRAP_DEFAULT, true);
                            // check if request is still valid, or if the requesting thread has stopped waiting already
                            if (localThread != thread) {
                                return;
                            }
                            commitTransaction();
                        } catch (Exception x) {
                            // check if request is still valid, or if the requesting thread has stopped waiting already
                            if (localThread != thread) {
                                return;
                            }
                            abortTransaction();
                            app.logError(txname + " " + error, x);

                            // If the transactor thread has been killed by the invoker thread we don't have to
                            // bother for the error message, just quit.
                            if (localThread != thread) {
                                return;
                            }

                            this.exception = x;
                        }

                        done = true;
                        break;

                    } // switch (reqtype)
                } catch (AbortException x) {
                    // res.abort() just aborts the transaction and
                    // leaves the response untouched
                    // check if request is still valid, or if the requesting thread has stopped waiting already
                    if (localThread != thread) {
                        return;
                    }
                    abortTransaction();
                    done = true;
                } catch (ConcurrencyException x) {
                    res.reset();

                    if (++tries < 8) {
                        // try again after waiting some period
                        // check if request is still valid, or if the requesting thread has stopped waiting already
                        if (localThread != thread) {
                            return;
                        }
                        abortTransaction();

                        try {
                            // wait a bit longer with each try
                            int base = 800 * tries;
                            Thread.sleep((long) (base + (Math.random() * base * 2)));
                        } catch (InterruptedException interrupt) {
                            // we got interrrupted, create minimal error message 
                            res.reportError(interrupt);
                            done = true;
                            // and release resources and thread
                            thread = null;
                            transactor = null;
                        }
                    } else {
                        // check if request is still valid, or if the requesting thread has stopped waiting already
                        if (localThread != thread) {
                            return;
                        }
                        abortTransaction();

                        // error in error action. use traditional minimal error message
                        res.reportError("Application too busy, please try again later");
                        done = true;
                    }
                } catch (Throwable x) {
                    // check if request is still valid, or if the requesting thread has stopped waiting already
                    if (localThread != thread) {
                        return;
                    }
                    abortTransaction();

                    // If the transactor thread has been killed by the invoker thread we don't have to
                    // bother for the error message, just quit.
                    if (localThread != thread) {
                        return;
                    }

                    res.reset();

                    // check if we tried to process the error already,
                    // or if this is an XML-RPC request
                    if (error == null) {
                        if (!(x instanceof NotFoundException)) {
                            app.errorCount += 1;
                        }

                        // set done to false so that the error will be processed
                        done = false;
                        error = x;

                        app.logError(txname + " " + error, x);

                        if (req.isXmlRpc()) {
                            // if it's an XML-RPC exception immediately generate error response
                            if (!(x instanceof Exception)) {
                                // we need an exception to pass to XML-RPC responder
                                x = new Exception(x.toString(), x);
                            }
                            res.writeXmlRpcError((Exception) x);
                            done = true;
                        }
                    } else {
                        // error in error action. use traditional minimal error message
                        res.reportError(error);
                        done = true;
                    }
                } finally {
                    app.setCurrentRequestEvaluator(null);
                    // exit execution context
                    if (scriptingEngine != null) {
                        try {
                            scriptingEngine.exitContext();
                        } catch (Throwable t) {
                            // broken rhino, just get out of here
                        }
                    }
                }
            }

            notifyAndWait();

        }
    } finally {
        Transactor tx = Transactor.getInstance();
        if (tx != null)
            tx.closeConnections();
    }
}

From source file:userinterface.graph.Graph.java

/**
 * Exports the current graph to Matlab file format.
 * @param f The file to write the data to.
 *//*from  ww  w.j  ava 2 s. co m*/
public void exportToMatlab(File f) throws IOException {
    PrintWriter out = new PrintWriter(new FileWriter(f));

    out.println("%=========================================");
    out.println("%Generated by PRISM Chart Package");
    out.println("%=========================================");
    out.println();

    //Seriesdata
    synchronized (getSeriesLock()) {
        /* Make sure we preserve ordering. */
        for (int i = 0; i < seriesList.getSize(); i++) {
            StringBuffer x = new StringBuffer("x" + i + " = [");
            StringBuffer y = new StringBuffer("y" + i + " = [");

            SeriesKey key = seriesList.getKeyAt(i);

            XYSeries seriesData = getXYSeries(key);

            for (int j = 0; j < seriesData.getItemCount(); j++) {
                x.append(seriesData.getX(j) + " ");
                y.append(seriesData.getY(j) + " ");
            }

            x.append("];");
            y.append("];");

            out.println(x.toString());
            out.println(y.toString());
        }

        //Create a figure
        out.println();
        out.println(
                "figure1 = figure('Color', [1 1 1], 'PaperPosition',[0.6345 6.345 20.3 15.23],'PaperSize',[20.98 29.68]);");

        //Create axes
        boolean xLog = getXAxisSettings().isLogarithmic();
        boolean yLog = getYAxisSettings().isLogarithmic();

        out.println();

        if (xLog && yLog)
            out.println("axes1 = axes('Parent', figure1, 'FontSize', 16, 'XScale', 'log', 'YScale', 'log');");
        else if (xLog)
            out.println("axes1 = axes('Parent', figure1, 'FontSize', 16, 'XScale', 'log');");
        else if (yLog)
            out.println("axes1 = axes('Parent', figure1, 'FontSize', 16, 'YScale', 'log');");
        else
            out.println("axes1 = axes('Parent', figure1, 'FontSize', 16);");

        out.println("xlabel(axes1, '" + getXAxisSettings().getHeading() + "');");
        out.println("ylabel(axes1, '" + getYAxisSettings().getHeading() + "');");

        out.println("box(axes1, 'on');");
        out.println("hold(axes1, 'all');");

        //Graph title
        out.println();

        String title = "";
        StringTokenizer st = new StringTokenizer(getTitle(), "\n");

        int num = st.countTokens();
        for (int i = 0; i < num; i++) {
            title += "'" + st.nextToken() + "'";
            if (i < num - 1)
                title += ", char(10),";
        }

        out.println("title(axes1,[" + title + "])");

        //Sort out logarithmic scales
        String scaleType = "plot";
        if (seriesList.getSize() > 0) {
            if (xLog && yLog)
                scaleType = "loglog";
            else if (xLog)
                scaleType = "semilogx";
            else if (yLog)
                scaleType = "semilogy";
        }

        //Create plots
        for (int i = 0; i < seriesList.getSize(); i++) {
            SeriesKey key = seriesList.getKeyAt(i);
            SeriesSettings seriesSettings = getGraphSeries(key);

            String marker = "'";
            if (seriesSettings.showPoints() && seriesSettings.getSeriesShape() != SeriesSettings.NONE) {
                switch (seriesSettings.getSeriesShape()) {
                case SeriesSettings.CIRCLE:
                    marker += "o";
                    break;
                case SeriesSettings.SQUARE:
                    marker += "s";
                    break;
                case SeriesSettings.TRIANGLE:
                    marker += "^";
                    break;
                case SeriesSettings.RECTANGLE_H:
                    marker += "d";
                    break;
                case SeriesSettings.RECTANGLE_V:
                    marker += "x";
                    break;
                }
            }

            if (seriesSettings.showLines()) {
                switch (seriesSettings.getLineStyle()) {
                case SeriesSettings.SOLID:
                    marker += "-";
                    break;
                case SeriesSettings.DASHED:
                    marker += "--";
                    break;
                case SeriesSettings.DOT_DASHED:
                    marker += "-.";
                    break;
                }
            }
            marker += "'";
            out.println("plot" + i + " = " + scaleType + "(x" + i + ", y" + i + ", " + marker
                    + ", 'Parent', axes1, 'LineWidth', 2);");
        }

        //         Create legend
        String seriesNames = "";
        for (int i = 0; i < seriesList.getSize(); i++) {
            SeriesKey key = seriesList.getKeyAt(i);
            SeriesSettings seriesSettings = getGraphSeries(key);

            seriesNames += "'" + seriesSettings.getSeriesHeading() + "'";
            if (i < seriesList.getSize() - 1)
                seriesNames += ", ";
        }

        //Determine location

        String loc = "";
        switch (legendPosition.getCurrentIndex()) {
        case LEFT:
            loc = "'WestOutside'";
            break;
        case RIGHT:
            loc = "'EastOutside'";
            break;
        case BOTTOM:
            loc = "'SouthOutside'";
            break;
        case TOP:
            loc = "'NorthOutside'";
            break;
        }

        if (isLegendVisible())
            out.println("legend1 = legend(axes1,{" + seriesNames + "},'Location', " + loc + ");");

        out.flush();
        out.close();
    }
}

From source file:com.servoy.j2db.util.Utils.java

/**
 * count the numbers in a string/*from ww w .ja  va2 s.c o m*/
 *
 * @param s the string with the numbers
 * @return the count
 */
public static int countNumbers(String s) {
    if (s == null)
        return 0;
    String p = findNumberEx(s);
    StringTokenizer tk = new StringTokenizer(p, " "); //$NON-NLS-1$
    return tk.countTokens();
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.BODispatchGameAction.java

private void copyPackValues(List<PackBean> packList) {
    PackBean packBean = null;//  ww  w  .j a v a2s  .co m

    System.out.println("PackNbr Array::" + getPackNbr());

    String[] packNbr = getPackNbr();
    System.out.println("PackNbr.length:" + packNbr.length);

    HttpSession session = getRequest().getSession();
    OrderedGameBean orderedGameBean = (OrderedGameBean) session.getAttribute("ORDERED_GAME");

    if (packNbr != null) {

        if (packNbr.length == 1) {

            String packVal = null;
            StringTokenizer packTokens = new StringTokenizer(packNbr[0], ",");

            System.out.println("Value Passed::" + packNbr[0]);
            System.out.println("PackTokens::" + packTokens.countTokens());

            int i = 0;
            while (packTokens.hasMoreTokens()) {

                packVal = packTokens.nextToken();

                packVal = packVal.trim();

                if (packVal.indexOf("-") == -1 && packVal.length() > orderedGameBean.getGameNbrDigits()) {
                    packVal = packVal.substring(0, orderedGameBean.getGameNbrDigits()) + "-"
                            + packVal.substring(orderedGameBean.getGameNbrDigits());
                }

                System.out.println(packVal);
                packBean = packList.get(i++);
                packBean.setPackNumber(packVal);
            }
        }
    }
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.BODispatchGameAction.java

private void copyBookValues(List<BookBean> bookList) {
    BookBean bookBean = null;//www.j a  v  a  2  s.  com

    System.out.println("BookNbr Array::" + getBookNbr());

    System.out.println("Nbr of boks to dispatch" + getNoOfBooksToDispatch());

    String[] bookNbr = getBookNbr();
    System.out.println("BookNbr.length:" + bookNbr.length);

    HttpSession session = getRequest().getSession();
    OrderedGameBean orderedGameBean = (OrderedGameBean) session.getAttribute("ORDERED_GAME");

    if (bookNbr != null) {

        if (bookNbr.length == 1) {

            String bookVal = null;
            StringTokenizer bookTokens = new StringTokenizer(bookNbr[0], ",");

            System.out.println("Value Passed::" + bookNbr[0]);
            System.out.println("BookTokens::" + bookTokens.countTokens());

            int i = 0;
            while (bookTokens.hasMoreTokens()) {

                bookVal = bookTokens.nextToken();
                System.out.println(bookVal);

                bookVal = bookVal.trim();

                if (bookVal.indexOf("-") == -1 && bookVal.length() > orderedGameBean.getGameNbrDigits()) {
                    bookVal = bookVal.substring(0, orderedGameBean.getGameNbrDigits()) + "-"
                            + bookVal.substring(orderedGameBean.getGameNbrDigits());
                    bookBean = new BookBean();
                    bookBean.setValid(true);
                    bookBean.setBookNumber(bookVal);
                    bookList.add(bookBean);

                }
                i = i + 1;
            }
            setBookList(bookList);
            System.out.println("After Setting BookList in copyBookValues::" + bookList);
        }
    }

    /*
     * for(String b : bookNbr) { System.out.println("Book:::" + b); }
     * 
     * 
     * 
     * if (bookNbr != null) { System.out.println("Inside NOt Null ---BookNbr
     * Array::" + getBookNbr()); for (int i = 0; i < bookNbr.length; i++) {
     * if (!bookNbr[i].trim().equals("")) { bookBean = new BookBean();
     * bookBean.setBookNumber(bookNbr[i]); bookList.add(bookBean); } } }
     */

}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.BODispatchGameAction.java

public String verifyBookSeries() throws LMSException {

    // global connection to be used everywhere
    Connection connection = null;

    connection = DBConnect.getConnection();

    boolean isValid = false;
    boolean isSeriesValid = true;
    int gameId = getGameId();
    HttpSession session = getRequest().getSession();
    int roleId = ((UserInfoBean) session.getAttribute("USER_INFO")).getRoleId();
    List<BookBean> bookList = new ArrayList();
    List<BookBean> bookSeriesList = new ArrayList();
    List bookSeriesAll = new ArrayList();
    session.setAttribute("BOOK_SERIES_ALL", bookSeriesAll);
    session.setAttribute("BOOK_LIST", bookList);
    session.setAttribute("BOOK_SERIES_LIST", bookSeriesList);
    StringTokenizer bookNbrFrmTok = new StringTokenizer(((String[]) bookNbrFromArr)[0], ",");
    StringTokenizer bookNbrToTok = new StringTokenizer(((String[]) bookNbrToArr)[0], ",");
    bookNbrFrmStr = new String[bookNbrFrmTok.countTokens()];
    bookNbrToStr = new String[bookNbrToTok.countTokens()];
    int frmTok = 0;
    while (bookNbrFrmTok.hasMoreTokens()) {
        bookNbrFrmStr[frmTok] = bookNbrFrmTok.nextToken();
        bookNbrToStr[frmTok] = bookNbrToTok.nextToken();
        frmTok = frmTok + 1;/*ww w . j ava  2 s.co m*/
    }
    System.out.println("---Series length" + bookNbrFrmStr);

    if (bookNbrFrmStr != null) {
        for (int seriesNo = 0; seriesNo < bookNbrFrmStr.length; seriesNo++) {
            if (bookNbrFrmStr[seriesNo] != "") {

                String bookNbrFrom = bookNbrFrmStr[seriesNo];
                String bookNbrTo = bookNbrToStr[seriesNo];

                int bookNbrFrmInt = Integer.parseInt(bookNbrFrom.replaceAll("-", ""));
                int bookNbrToInt = Integer.parseInt(bookNbrTo.replaceAll("-", ""));
                int noOfbooks = bookNbrToInt - bookNbrFrmInt;
                BookSeriesBean bookSeBean = new BookSeriesBean();
                bookSeBean.setBookNbrFrom(bookNbrFrom);
                bookSeBean.setBookNbrTo(bookNbrTo);
                bookSeBean.setStatus("");
                bookSeBean.setValid(isValid);
                for (int i = 0; i < noOfbooks + 1; i++) {
                    String bookNbr = String.valueOf(bookNbrFrmInt);

                    if (bookNbr != null && !bookNbr.trim().equals("")) {
                        // add hyphens if necessary

                        System.out.println(":::::::::" + bookNbr.indexOf("-"));

                        if (bookNbr.indexOf("-") == -1) {
                            OrderedGameBean orderedGameBean = (OrderedGameBean) session
                                    .getAttribute("ORDERED_GAME");

                            bookNbr = bookNbr.substring(0, orderedGameBean.getGameNbrDigits()) + "-"
                                    + bookNbr.substring(orderedGameBean.getGameNbrDigits());

                            System.out.println("New book nbr:::" + bookNbr);

                        }

                        System.out.println("---------------vvvvvvvvvvvvv----------" + bookNbr);
                        BODispatchGameHelper helper = new BODispatchGameHelper();
                        isValid = helper.verifyBook(gameId, bookNbr, connection, roleId);

                        if (isValid) {
                            BookBean bookBean = new BookBean();
                            bookBean.setValid(true);
                            bookBean.setBookNumber(bookNbr);
                            for (BookBean bean : bookSeriesList) {
                                if (bookNbr.equals(bean.getBookNumber())) {
                                    isSeriesValid = false;
                                    bookSeBean.setStatus("Series Contains Tickets of Another Series");
                                    break;// New series contains ticket of
                                    // old series
                                }
                            }
                            if (isSeriesValid) {
                                bookSeriesList.add(bookBean);
                            }

                        } else {
                            isSeriesValid = false;
                            bookSeBean.setStatus("Series Not Valid");
                            break;// Series not valid
                        }
                    }
                    System.out.println("inside for of verifyBookSeries");

                    bookNbrFrmInt++;

                }
                if (isSeriesValid) {
                    bookSeBean.setValid(true);
                    session.setAttribute("BOOK_SERIES_LIST", bookSeriesList);
                }
                bookSeriesAll.add(bookSeBean);
                session.setAttribute("BOOK_SERIES_ALL", bookSeriesAll);
                // changeDispatchBooks();
                System.out.println("@@@@@@@@@@@@@################$$$$$$$$$$$$$%%%%%%%%%%%%%%%%");
            }
        }
    }
    verifyIndividualBooks(bookList, connection, roleId);

    for (int i = 0; i < bookSeriesList.size(); i++) {
        for (int j = 0; j < bookList.size(); j++) {
            // System.out.println(bookSeriesList.size()+"-Gaura
            // Test--"+bookList.size());
            if (((BookBean) bookList.get(j)).getBookNumber()
                    .equals(((BookBean) bookSeriesList.get(i)).getBookNumber())) {
                BookBean bean = (BookBean) bookList.get(j);
                bean.setValid(false);
                bean.setStatus("Book Number already in Book Series");
            }
        }
    }
    setBookList(bookList);
    session.setAttribute("BOOK_LIST", bookList);
    changeDispatchBooks();
    System.out.println("---------Trying to prevent caching------" + bookList);
    HttpServletResponse response = getResponse();
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0
    response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    response.setDateHeader("Expires", 0); // prevents caching at the proxy
    // server
    response.setHeader("Cache-Control", "private"); // HTTP 1.1
    response.setHeader("Cache-Control", "no-store"); // HTTP 1.1
    response.setHeader("Cache-Control", "max-stale=0"); // HTTP 1.1

    return SUCCESS;

}