Example usage for java.util Vector toArray

List of usage examples for java.util Vector toArray

Introduction

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

Prototype

public synchronized Object[] toArray() 

Source Link

Document

Returns an array containing all of the elements in this Vector in the correct order.

Usage

From source file:org.jfree.data.contour.DefaultContourDataset.java

/**
 * Initialises the dataset./*w  w  w  .  ja  v  a2s. c  o m*/
 *
 * @param xData  the x values.
 * @param yData  the y values.
 * @param zData  the z values.
 */
public void initialize(Object[] xData, Object[] yData, Object[] zData) {

    this.xValues = new Double[xData.length];
    this.yValues = new Double[yData.length];
    this.zValues = new Double[zData.length];

    // We organise the data with the following assumption:
    // 1) the data are sorted by x then y
    // 2) that the data will be represented by a rectangle formed by
    //    using x[i+1], x, y[j+1], and y.
    // 3) we march along the y-axis at the same value of x until a new
    //    value x is found at which point we will flag the index
    //    where x[i+1]<>x[i]

    Vector tmpVector = new Vector(); //create a temporary vector
    double x = 1.123452e31; // set x to some arbitary value (used below)
    for (int k = 0; k < this.xValues.length; k++) {
        if (xData[k] != null) {
            Number xNumber;
            if (xData[k] instanceof Number) {
                xNumber = (Number) xData[k];
            } else if (xData[k] instanceof Date) {
                this.dateAxis[0] = true;
                Date xDate = (Date) xData[k];
                xNumber = new Long(xDate.getTime()); //store data as Long
            } else {
                xNumber = new Integer(0);
            }
            this.xValues[k] = new Double(xNumber.doubleValue());
            // store Number as Double

            // check if starting new column
            if (x != this.xValues[k].doubleValue()) {
                tmpVector.add(new Integer(k)); //store index where new
                                               //column starts
                x = this.xValues[k].doubleValue();
                // set x to most recent value
            }
        }
    }

    Object[] inttmp = tmpVector.toArray();
    this.xIndex = new int[inttmp.length]; // create array xIndex to hold
                                          // new column indices

    for (int i = 0; i < inttmp.length; i++) {
        this.xIndex[i] = ((Integer) inttmp[i]).intValue();
    }
    for (int k = 0; k < this.yValues.length; k++) { // store y and z axes
                                                    // as Doubles
        this.yValues[k] = (Double) yData[k];
        if (zData[k] != null) {
            this.zValues[k] = (Double) zData[k];
        }
    }
}

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

/**
 *
 *//*  w  w  w  .j  a v  a2s  .  c om*/
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:jdao.JDAO.java

public static int insertSet(int dbType, Connection conn, QueryRunner ds, String table, Map cols,
        boolean onDuplicateKeyUpdate, Collection updateFields) throws Exception {
    if (dbType != JDAO.DB_TYPE_MYSQL) {
        throw new IllegalArgumentException("DB TYPE NOT MYSQL");
    }/*w w w . j  a  va  2  s  .co m*/
    Vector vv = new Vector();
    String setqq = buildSet(dbType, vv, cols);
    StringBuilder qq = new StringBuilder();
    qq.append("INSERT INTO " + table + " SET ");
    qq.append(setqq);
    if (onDuplicateKeyUpdate) {
        Map um = new HashMap();
        for (Object o : updateFields) {
            um.put(o, cols.get(o));
        }
        String setuqq = buildSet(dbType, vv, um);
        qq.append(" ON DUPLICATE KEY UPDATE ");
        qq.append(setuqq);
    }

    if (conn == null) {
        return ds.update(qq.toString(), vv.toArray());
    }
    return ds.update(conn, qq.toString(), vv.toArray());
}

From source file:corelyzer.ui.CorelyzerGLCanvas.java

private void handleClastMouseReleased(final MouseEvent e) {
    if (selectedTrackSection != -1) {
        Point releasePos = e.getPoint();
        float[] releaseScenePos = { 0.0f, 0.0f };
        float[] releaseAbsPos = { 0.0f, 0.0f };

        convertMousePointToSceneSpace(releasePos, releaseScenePos);

        if (!SceneGraph.getDepthOrientation()) {
            float t = scenePos[0];
            scenePos[0] = scenePos[1];//from  w w w.  j  a  va 2 s  .  c  o m
            scenePos[1] = -t;
        }

        SceneGraph.addClastPoint2(scenePos[0], scenePos[1]);

        convertScenePointToAbsolute(scenePos, releaseAbsPos);
        CorelyzerApp.getApp().getToolFrame().setClastLowerRight(releaseAbsPos);
        float[] clastUpperLeft = CorelyzerApp.getApp().getToolFrame().getClastUpperLeft();

        String trackname = CorelyzerApp.getApp().getTrackListModel().getElementAt(selectedTrackIndex)
                .toString();
        String secname = CorelyzerApp.getApp().getSectionListModel().getElementAt(selectedTrackSectionIndex)
                .toString();
        String sessionname = CoreGraph.getInstance().getCurrentSession().getName();

        // Different kinds of annotations
        AnnotationTypeDirectory dir = AnnotationTypeDirectory.getLocalAnnotationTypeDirectory();
        if (dir == null) {
            System.out.println("Null AnnotationTypeDirectory abort.");
            return;
        }

        Enumeration<String> keys = dir.keys();
        Vector<String> annotationOptions = new Vector<String>();
        annotationOptions.add("Cancel");

        while (keys.hasMoreElements()) {
            annotationOptions.add(keys.nextElement());
        }

        Object[] options = annotationOptions.toArray();

        int sel = JOptionPane.showOptionDialog(getPopupParent(), "Which kind of Annotation?",
                "Annotation Form Selector", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                options, options[0]);

        if (sel < 0) {
            return;
        }

        try {
            this.handleAnnotationEvent(options[sel].toString(), sessionname, trackname, secname, clastUpperLeft,
                    releaseAbsPos);
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:org.ecocean.MarkedIndividual.java

public JSONObject uiJson(HttpServletRequest request) throws JSONException {
    JSONObject jobj = new JSONObject();
    jobj.put("individualID", this.getIndividualID());
    jobj.put("url", this.getUrl(request));
    jobj.put("sex", this.getSex());
    jobj.put("nickname", this.nickName);

    Vector<String> encIDs = new Vector<String>();
    for (Encounter enc : this.encounters) {
        encIDs.add(enc.getCatalogNumber());
    }//from  w w  w  .  j ava  2 s.  co m
    jobj.put("encounterIDs", encIDs.toArray());
    return sanitizeJson(request, jobj);
}

From source file:jdao.JDAO.java

public static int insert(int dbType, Connection conn, QueryRunner ds, String table, Map cols,
        boolean onDuplicateKeyUpdate, Collection updateFields) throws Exception {
    if (onDuplicateKeyUpdate && (dbType != JDAO.DB_TYPE_MYSQL) && (dbType != JDAO.DB_TYPE_CRATE)) {
        throw new IllegalArgumentException("DB TYPE NOT MYSQL");
    }// ww  w. ja va  2 s. c  o  m
    Vector parm = new Vector();
    StringBuilder qq = new StringBuilder();
    qq.append("INSERT INTO " + table + " ( ");
    boolean op = true;
    for (Object kv : cols.entrySet()) {
        parm.add(((Map.Entry) kv).getValue());
        if (!op) {
            qq.append(",");
        }
        qq.append(((Map.Entry) kv).getKey());
        op = false;
    }
    qq.append(" ) VALUES (");
    op = true;
    for (Object v : parm) {
        if (!op) {
            qq.append(",");
        }
        qq.append("?");
        op = false;
    }
    qq.append(" ) ");

    if (onDuplicateKeyUpdate) {
        Map um = new HashMap();
        for (Object o : updateFields) {
            um.put(o, cols.get(o));
        }
        String setuqq = buildSet(dbType, parm, um);
        qq.append(" ON DUPLICATE KEY UPDATE ");
        qq.append(setuqq);
    }

    if (conn == null) {
        return ds.update(qq.toString(), parm.toArray());
    }
    return ds.update(conn, qq.toString(), parm.toArray());
}

From source file:jdao.JDAO.java

public static <T> T insertWithPK(int dbType, Connection conn, QueryRunner ds, String table, Map cols,
        boolean onDuplicateKeyUpdate, Collection updateFields, Class<T> clazz) throws Exception {
    if (onDuplicateKeyUpdate && (dbType != JDAO.DB_TYPE_MYSQL) && (dbType != JDAO.DB_TYPE_CRATE)) {
        throw new IllegalArgumentException("DB TYPE NOT MYSQL");
    }/*  ww w .  ja v  a  2 s  .co m*/
    Vector parm = new Vector();
    StringBuilder qq = new StringBuilder();
    qq.append("INSERT INTO " + table + " ( ");
    boolean op = true;
    for (Object kv : cols.entrySet()) {
        parm.add(((Map.Entry) kv).getValue());
        if (!op) {
            qq.append(",");
        }
        qq.append(((Map.Entry) kv).getKey());
        op = false;
    }
    qq.append(" ) VALUES (");
    op = true;
    for (Object v : parm) {
        if (!op) {
            qq.append(",");
        }
        qq.append("?");
        op = false;
    }
    qq.append(" ) ");

    if (onDuplicateKeyUpdate) {
        Map um = new HashMap();
        for (Object o : updateFields) {
            um.put(o, cols.get(o));
        }
        String setuqq = buildSet(dbType, parm, um);
        qq.append(" ON DUPLICATE KEY UPDATE ");
        qq.append(setuqq);
    }

    if (conn == null) {
        return ds.insert(qq.toString(), new ScalarHandler<T>(), parm.toArray());
    }
    return ds.insert(conn, qq.toString(), new ScalarHandler<T>(), parm.toArray());
}

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

public Object executeExternal(String method, Vector args) throws Exception {
    Object retval = null;//  w ww. j av  a  2  s  .co  m
    RequestEvaluator ev = null;
    try {
        // check if the properties file has been updated
        updateProperties();
        // get evaluator and invoke
        ev = getEvaluator();
        retval = ev.invokeExternal(method, args.toArray());
    } finally {
        releaseEvaluator(ev);
    }
    return retval;
}

From source file:jdao.JDAO.java

public <T> int updateBean(String table, Object _bean, Class<T> _beanClazz) throws Exception {
    Map<String, Object> keyCol = extractIdKvFromBean(_bean, _beanClazz);
    Map cols = extractColsFromBean(_bean, _beanClazz, false);

    Vector vv = new Vector();
    String setqq = buildSet(this.dbType, vv, cols);
    String wqq = buildWhereEqual(this.dbType, vv, keyCol);

    StringBuilder qq = new StringBuilder();

    qq.append("UPDATE " + table + " SET ");
    qq.append(setqq);/*from   ww w.ja v  a  2s .  c  o m*/
    qq.append(" WHERE ");
    qq.append(wqq);

    return this.update(qq.toString(), vv.toArray());
}

From source file:gda.gui.mca.McaGUI.java

private JPanel getRoiPanel() {
    roiLabel = new JLabel("Regions Of Interest");
    refreshButton = new JButton("Refresh");
    refreshButton.addActionListener(new ActionListener() {

        @Override//  w w w.ja  v a2  s .  com
        public void actionPerformed(ActionEvent e) {
            Thread t1 = uk.ac.gda.util.ThreadManager.getThread(new Runnable() {

                @Override
                public void run() {
                    try {

                        // System.out.println("set table data called
                        // from refresh
                        // method");
                        setTableData((EpicsMCARegionOfInterest[]) analyser.getRegionsOfInterest(),
                                analyser.getRegionsOfInterestCount());
                        updateAdcValues();
                        // System.out.println("after setting the table
                        // data " +
                        // analyser);
                    } catch (DeviceException de) {
                        logger.error("Unable to get MCA regions of Interest Information " + de.getMessage());
                    }
                }
            });
            t1.start();

        }

    });
    updateButton = new JButton("Set");
    updateButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Thread t = uk.ac.gda.util.ThreadManager.getThread(new Runnable() {
                @Override
                public void run() {
                    int rows = roiTable.getRowCount();
                    Vector<EpicsMCARegionOfInterest> roi = new Vector<EpicsMCARegionOfInterest>();
                    for (int i = 0; i < rows; i++) {
                        if (((Boolean) model.getValueAt(i, 0)).booleanValue()
                                && regionValid(((Double) model.getValueAt(i, 5)).doubleValue(),
                                        ((Double) model.getValueAt(i, 6)).doubleValue())) {
                            roi.add(new EpicsMCARegionOfInterest(((Integer) model.getValueAt(i, 1)).intValue(),
                                    ((Double) model.getValueAt(i, 5)).doubleValue(),
                                    ((Double) model.getValueAt(i, 6)).doubleValue(),
                                    ((Integer) model.getValueAt(i, 7)).intValue(),
                                    ((Double) model.getValueAt(i, 8)).doubleValue(),
                                    (String) model.getValueAt(i, 2)));
                        }

                    }
                    if (roi.size() > 0) {
                        Object[] obj = roi.toArray();
                        EpicsMCARegionOfInterest eroi[] = new EpicsMCARegionOfInterest[obj.length];
                        for (int j = 0; j < eroi.length; j++) {
                            eroi[j] = (EpicsMCARegionOfInterest) obj[j];
                        }

                        try {
                            tableDataSet = true;
                            analyser.setRegionsOfInterest(eroi);
                            tableDataSet = false;
                        } catch (DeviceException e) {
                            logger.error("Unable to set the table values");
                            tableDataSet = false;
                        }
                    }
                }
            });
            t.start();

        }

    });
    cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Thread t2 = uk.ac.gda.util.ThreadManager.getThread(new Runnable() {
                @Override
                public void run() {
                    int rows = roiTable.getRowCount();
                    Vector<EpicsMCARegionOfInterest> roi = new Vector<EpicsMCARegionOfInterest>();
                    for (int i = 0; i < rows; i++) {
                        if (((Boolean) model.getValueAt(i, 0)).booleanValue()) {
                            // add
                            removeRegionMarkers(((Integer) model.getValueAt(i, 1)).intValue(),
                                    ((Double) model.getValueAt(i, 5)).doubleValue(),
                                    ((Double) model.getValueAt(i, 6)).doubleValue());
                            roi.add(new EpicsMCARegionOfInterest(((Integer) model.getValueAt(i, 1)).intValue(),
                                    -1, -1, -1, -1, ""));
                        }

                    }
                    if (roi.size() > 0) {
                        Object[] obj = roi.toArray();
                        EpicsMCARegionOfInterest eroi[] = new EpicsMCARegionOfInterest[obj.length];
                        for (int j = 0; j < eroi.length; j++) {
                            eroi[j] = (EpicsMCARegionOfInterest) obj[j];
                        }

                        try {
                            tableDataSet = true;
                            analyser.setRegionsOfInterest(eroi);
                            tableDataSet = false;
                        } catch (DeviceException e) {
                            logger.error("Unable to set the table values");
                            tableDataSet = false;
                        }
                    }
                }
            });
            t2.start();

        }

    });
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(refreshButton);
    buttonPanel.add(updateButton);
    buttonPanel.add(cancelButton);
    roiPanel = new JPanel();
    roiPanel.setLayout(new BorderLayout());
    roiPanel.add(roiLabel, BorderLayout.NORTH);
    roiPanel.add(getRoiScrollPane(), BorderLayout.CENTER);
    roiPanel.add(buttonPanel, BorderLayout.SOUTH);
    return roiPanel;
}