Example usage for java.lang.reflect InvocationTargetException getCause

List of usage examples for java.lang.reflect InvocationTargetException getCause

Introduction

In this page you can find the example usage for java.lang.reflect InvocationTargetException getCause.

Prototype

public Throwable getCause() 

Source Link

Document

Returns the cause of this exception (the thrown target exception, which may be null ).

Usage

From source file:net.refractions.udig.catalog.ui.wizard.DataBaseRegistryWizardPage.java

/**
 * This method will run the provided activity using the
 * wizard page progress bar; and wait for the result to
 * complete.//from  ww w .j a  v  a 2 s.  c o m
 * <p>
 * If anything goes wrong the message will be shown to the user
 * 
 * @param activity
 */
protected void runInPage(final IRunnableWithProgress activity) {
    // on a technical level I am not sure which one of these we should use
    //
    boolean guess = true;
    try {
        if (guess) {
            // This is what I think PostGIS wizard page does
            getContainer().run(false, true, activity);
        } else {
            // This is what the origional wizard pages did
            // note the use of an internal blocking call to run the activity
            // and wait for it to complete?
            //
            getContainer().run(false, true, new IRunnableWithProgress() {
                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    PlatformGIS.runBlockingOperation(activity, monitor);
                }
            });
        }
    } catch (InvocationTargetException e2) {
        // log the error
        CatalogUIPlugin.log(e2.getLocalizedMessage(), e2);
        // tell the user
        setErrorMessage(e2.getCause().getLocalizedMessage());

        // preferences.performDefaults();
    } catch (InterruptedException e2) {
        // user got tired of waiting ...
    }
}

From source file:org.kchine.r.server.http.frontend.CommandServlet.java

protected void doAny(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = null;//from   w  w w. j  a  v a  2 s  .  c  om
    Object result = null;

    try {
        final String command = request.getParameter("method");
        do {

            if (command.equals("ping")) {
                result = "pong";
                break;
            } else if (command.equals("logon")) {

                session = request.getSession(false);
                if (session != null) {
                    result = session.getId();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                boolean namedAccessMode = login.contains("@@");
                String sname = null;
                if (namedAccessMode) {
                    sname = login.substring(login.indexOf("@@") + "@@".length());
                    login = login.substring(0, login.indexOf("@@"));
                }

                System.out.println("login :" + login);
                System.out.println("pwd :" + pwd);

                if (_rkit == null && (!login.equals(System.getProperty("login"))
                        || !pwd.equals(System.getProperty("pwd")))) {
                    result = new BadLoginPasswordException();
                    break;
                }

                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                RPFSessionInfo.get().put("LOGIN", login);
                RPFSessionInfo.get().put("REMOTE_ADDR", request.getRemoteAddr());
                RPFSessionInfo.get().put("REMOTE_HOST", request.getRemoteHost());

                boolean nopool = !options.keySet().contains("nopool")
                        || ((String) options.get("nopool")).equals("")
                        || !((String) options.get("nopool")).equalsIgnoreCase("false");
                boolean save = options.keySet().contains("save")
                        && ((String) options.get("save")).equalsIgnoreCase("true");
                boolean selfish = options.keySet().contains("selfish")
                        && ((String) options.get("selfish")).equalsIgnoreCase("true");

                String privateName = (String) options.get("privatename");

                int memoryMin = DEFAULT_MEMORY_MIN;
                int memoryMax = DEFAULT_MEMORY_MAX;
                try {
                    if (options.get("memorymin") != null)
                        memoryMin = Integer.decode((String) options.get("memorymin"));
                    if (options.get("memorymax") != null)
                        memoryMax = Integer.decode((String) options.get("memorymax"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                boolean privateEngineMode = false;
                RServices r = null;
                URL[] codeUrls = null;

                if (_rkit == null) {

                    if (namedAccessMode) {

                        try {
                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    r = (RServices) ((DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                            System.getProperty("submit.ssh.host"),
                                            Integer.decode(System.getProperty("submit.ssh.port")),
                                            System.getProperty("submit.ssh.user"),
                                            System.getProperty("submit.ssh.password"),
                                            System.getProperty("submit.ssh.biocep.home"),
                                            "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                            "db", new Class<?>[] { DBLayerInterface.class })).lookup(sname);
                                }

                            } else {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    if (spFactory == null) {
                                        result = new NoRegistryAvailableException();
                                        break;
                                    }
                                    r = (RServices) spFactory.getServantProvider().getRegistry().lookup(sname);
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        if (nopool) {

                            /*                         
                            ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    
                            if (spFactory == null) {
                               result = new NoRegistryAvailableException();
                               break;
                            }
                                    
                            String nodeName = options.keySet().contains("node") ? (String) options.get("node") : System
                                  .getProperty("private.servant.node.name");
                            Registry registry = spFactory.getServantProvider().getRegistry();
                            NodeManager nm = null;
                            try {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name") + "_" + nodeName);
                            } catch (NotBoundException nbe) {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name"));
                            } catch (Exception e) {
                               result = new NoNodeManagerFound();
                               break;
                            }
                            r = (RServices) nm.createPrivateServant(nodeName);
                             */

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                DBLayerInterface dbLayer = (DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                        System.getProperty("submit.ssh.host"),
                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                        System.getProperty("submit.ssh.user"),
                                        System.getProperty("submit.ssh.password"),
                                        System.getProperty("submit.ssh.biocep.home"),
                                        "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                        "db", new Class<?>[] { DBLayerInterface.class });
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) dbLayer.lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {

                                    final String uid = (privateName != null && !privateName.equals(""))
                                            ? privateName
                                            : UUID.randomUUID().toString();
                                    final String[] jobIdHolder = new String[1];
                                    new Thread(new Runnable() {
                                        public void run() {
                                            try {

                                                String command = "java -Dlog.file="
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/log/%{uid}.log" + " -Drmi.port.start="
                                                        + System.getProperty("submit.ssh.rmi.port.start")
                                                        + " -Dname=%{uid}" + " -Dnaming.mode=db" + " -Ddb.host="
                                                        + System.getProperty("submit.ssh.host") + " -Dwait=true"
                                                        + " -jar "
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/biocep-core.jar";

                                                jobIdHolder[0] = SSHUtils.execSshBatch(command, uid,
                                                        System.getProperty("submit.ssh.prefix"),
                                                        System.getProperty("submit.ssh.host"),
                                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                                        System.getProperty("submit.ssh.user"),
                                                        System.getProperty("submit.ssh.password"),
                                                        System.getProperty("submit.ssh.biocep.home"));
                                                System.out.println("jobId:" + jobIdHolder[0]);

                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).start();

                                    long TIMEOUT = Long.decode(System.getProperty("submit.ssh.timeout"));
                                    long tStart = System.currentTimeMillis();
                                    while ((System.currentTimeMillis() - tStart) < TIMEOUT) {
                                        try {
                                            r = (RServices) dbLayer.lookup(uid);
                                        } catch (Exception e) {

                                        }
                                        if (r != null)
                                            break;
                                        try {
                                            Thread.sleep(10);
                                        } catch (Exception e) {
                                        }
                                    }

                                    if (r != null) {
                                        try {
                                            r.setJobId(jobIdHolder[0]);
                                        } catch (Exception e) {
                                            r = null;
                                        }
                                    }

                                }

                            } else {
                                System.out.println("LocalHttpServer.getLocalHttpServerPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                System.out.println("LocalRmiRegistry.getLocalRmiRegistryPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) LocalRmiRegistry.getInstance().lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {
                                    codeUrls = (URL[]) options.get("urls");
                                    System.out.println("CODE URL->" + Arrays.toString(codeUrls));
                                    //String 
                                    r = ServerManager.createR(System.getProperty("r.binary"), false, false,
                                            PoolUtils.getHostIp(), LocalHttpServer.getLocalHttpServerPort(),
                                            ServerManager.getRegistryNamingInfo(PoolUtils.getHostIp(),
                                                    LocalRmiRegistry.getLocalRmiRegistryPort()),
                                            memoryMin, memoryMax, privateName, false, codeUrls, null,
                                            (_webAppMode ? "javaws" : "standard"), null, "127.0.0.1");
                                }

                                privateEngineMode = true;
                            }

                        } else {

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                ServantProvider servantProvider = (ServantProvider) SSHTunnelingProxy
                                        .getDynamicProxy(System.getProperty("submit.ssh.host"),
                                                Integer.decode(System.getProperty("submit.ssh.port")),
                                                System.getProperty("submit.ssh.user"),
                                                System.getProperty("submit.ssh.password"),
                                                System.getProperty("submit.ssh.biocep.home"),
                                                "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                                "servant.provider", new Class<?>[] { ServantProvider.class });
                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxy()
                                            : servantProvider.borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxyNoWait()
                                            : servantProvider.borrowServantProxyNoWait(poolname));
                                }

                                System.out.println("---> borrowed : " + r);

                            } else {
                                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();

                                if (spFactory == null) {
                                    result = new NoRegistryAvailableException();
                                    break;
                                }

                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxy()
                                            : spFactory.getServantProvider().borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxyNoWait()
                                            : spFactory.getServantProvider()
                                                    .borrowServantProxyNoWait(poolname));
                                }
                            }
                        }
                    }
                } else {
                    r = _rkit.getR();
                }

                if (r == null) {
                    result = new NoServantAvailableException();
                    break;
                }

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "RS");
                session.setAttribute("R", r);
                session.setAttribute("NOPOOL", nopool);
                session.setAttribute("SAVE", save);
                session.setAttribute("LOGIN", login);
                session.setAttribute("NAMED_ACCESS_MODE", namedAccessMode);
                session.setAttribute("PROCESS_ID", r.getProcessId());
                session.setAttribute("JOB_ID", r.getJobId());
                session.setAttribute("SELFISH", selfish);
                session.setAttribute("IS_RELAY", _rkit != null);

                if (privateName != null)
                    session.setAttribute("PRIVATE_NAME", privateName);

                if (codeUrls != null && codeUrls.length > 0) {
                    session.setAttribute("CODEURLS", codeUrls);
                }

                session.setAttribute("THREADS", new ThreadsHolder());

                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                Vector<HttpSession> sessionVector = ((HashMap<RServices, Vector<HttpSession>>) getServletContext()
                        .getAttribute("R_SESSIONS")).get(r);
                if (sessionVector == null) {
                    sessionVector = new Vector<HttpSession>();
                    ((HashMap<RServices, Vector<HttpSession>>) getServletContext().getAttribute("R_SESSIONS"))
                            .put(r, sessionVector);
                }

                sessionVector.add(session);

                if (_rkit == null && save) {
                    UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), r);
                }

                System.out.println("---> Has Collaboration Listeners:" + r.hasRCollaborationListeners());
                if (selfish || !r.hasRCollaborationListeners()) {
                    try {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                        GDDevice[] devices = r.listDevices();
                        for (int i = 0; i < devices.length; ++i) {
                            String deviceName = devices[i].getId();
                            System.out.println("??? ---- deviceName=" + deviceName);
                            session.setAttribute(deviceName, devices[i]);
                        }

                    } finally {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                    }
                }

                if (privateEngineMode) {

                    if (options.get("newdevice") != null) {
                        GDDevice deviceProxy = null;
                        GDDevice[] dlist = r.listDevices();
                        if (dlist == null || dlist.length == 0) {
                            deviceProxy = r.newDevice(480, 480);
                        } else {
                            deviceProxy = dlist[0];
                        }
                        String deviceName = deviceProxy.getId();
                        session.setAttribute(deviceName, deviceProxy);
                        session.setAttribute("maindevice", deviceProxy);
                        saveSessionAttributes(session);
                    }

                    if (options.get("newgenericcallbackdevice") != null) {
                        GenericCallbackDevice genericCallBackDevice = null;
                        GenericCallbackDevice[] clist = r.listGenericCallbackDevices();
                        if (clist == null || clist.length == 0) {
                            genericCallBackDevice = r.newGenericCallbackDevice();
                        } else {
                            genericCallBackDevice = clist[0];
                        }
                        String genericCallBackDeviceName = genericCallBackDevice.getId();
                        session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                        session.setAttribute("maingenericcallbackdevice", genericCallBackDevice);
                        saveSessionAttributes(session);
                    }

                }

                result = session.getId();

                break;

            } else if (command.equals("logondb")) {

                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "DBS");
                session.setAttribute("REGISTRY", (DBLayer) spFactory.getServantProvider().getRegistry());
                session.setAttribute("SUPERVISOR",
                        new SupervisorUtils((DBLayer) spFactory.getServantProvider().getRegistry()));
                session.setAttribute("THREADS", new ThreadsHolder());
                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                result = session.getId();

                break;

            }

            session = request.getSession(false);
            if (session == null) {
                result = new NotLoggedInException();
                break;
            }

            if (command.equals("logoff")) {

                if (session.getAttribute("TYPE").equals("RS")) {
                    if (_rkit != null) {
                        /*
                        Enumeration<String> attributeNames = session.getAttributeNames();
                        while (attributeNames.hasMoreElements()) {
                           String aname = attributeNames.nextElement();
                           if (session.getAttribute(aname) instanceof GDDevice) {
                              try {
                                 _rkit.getRLock().lock();
                                 ((GDDevice) session.getAttribute(aname)).dispose();
                              } catch (Exception e) {
                                 e.printStackTrace();
                              } finally {
                                 _rkit.getRLock().unlock();
                              }
                           }
                        }
                        */
                    }
                }

                try {

                    session.invalidate();

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                result = null;
                break;
            }

            final boolean[] stop = { false };
            final HttpSession currentSession = session;

            if (command.equals("invoke")) {

                String servantName = (String) PoolUtils.hexToObject(request.getParameter("servantname"));
                final Object servant = session.getAttribute(servantName);
                if (servant == null) {
                    throw new Exception("Bad Servant Name :" + servantName);
                }
                String methodName = (String) PoolUtils.hexToObject(request.getParameter("methodname"));

                ClassLoader urlClassLoader = this.getClass().getClassLoader();
                if (session.getAttribute("CODEURLS") != null) {
                    urlClassLoader = new URLClassLoader((URL[]) session.getAttribute("CODEURLS"),
                            this.getClass().getClassLoader());
                }

                Class<?>[] methodSignature = (Class[]) PoolUtils
                        .hexToObject(request.getParameter("methodsignature"));

                final Method m = servant.getClass().getMethod(methodName, methodSignature);
                if (m == null) {
                    throw new Exception("Bad Method Name :" + methodName);
                }
                final Object[] methodParams = (Object[]) PoolUtils
                        .hexToObject(request.getParameter("methodparameters"), urlClassLoader);
                final Object[] resultHolder = new Object[1];
                Runnable rmiRunnable = new Runnable() {
                    public void run() {
                        try {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                            resultHolder[0] = m.invoke(servant, methodParams);
                            if (resultHolder[0] == null)
                                resultHolder[0] = RMICALL_DONE;
                        } catch (InvocationTargetException ite) {
                            if (ite.getCause() instanceof ConnectException) {
                                currentSession.invalidate();
                                resultHolder[0] = new NotLoggedInException();
                            } else {
                                resultHolder[0] = ite.getCause();
                            }
                        } catch (Exception e) {
                            final boolean wasInterrupted = Thread.interrupted();
                            if (wasInterrupted) {
                                resultHolder[0] = new RmiCallInterrupted();
                            } else {
                                resultHolder[0] = e;
                            }
                        } finally {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                        }
                    }
                };

                Thread rmiThread = InterruptibleRMIThreadFactory.getInstance().newThread(rmiRunnable);
                ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().add(rmiThread);
                rmiThread.start();

                long t1 = System.currentTimeMillis();

                while (resultHolder[0] == null) {

                    if ((System.currentTimeMillis() - t1) > RMICALL_TIMEOUT_MILLISEC || stop[0]) {
                        rmiThread.interrupt();
                        resultHolder[0] = new RmiCallTimeout();
                        break;
                    }

                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {
                    }
                }
                try {
                    ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().remove(rmiThread);
                } catch (IllegalStateException e) {
                }

                if (resultHolder[0] instanceof Throwable) {
                    throw (Throwable) resultHolder[0];
                }

                if (resultHolder[0] == RMICALL_DONE) {
                    result = null;
                } else {
                    result = resultHolder[0];
                }

                break;

            }

            if (command.equals("interrupt")) {
                final Vector<Thread> tvec = (Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS"))
                        .getThreads().clone();
                for (int i = 0; i < tvec.size(); ++i) {
                    try {
                        tvec.elementAt(i).interrupt();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                stop[0] = true;
                ((Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")).getThreads())
                        .removeAllElements();
                result = null;
                break;
            } else if (command.equals("saveimage")) {
                UserUtils.saveWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("loadimage")) {
                UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("newdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    boolean broadcasted = new Boolean(request.getParameter("broadcasted"));
                    GDDevice deviceProxy = null;
                    if (broadcasted) {
                        deviceProxy = ((RServices) session.getAttribute("R")).newBroadcastedDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    } else {
                        deviceProxy = ((RServices) session.getAttribute("R")).newDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    }

                    String deviceName = deviceProxy.getId();
                    System.out.println("deviceName=" + deviceName);
                    session.setAttribute(deviceName, deviceProxy);
                    saveSessionAttributes(session);
                    result = deviceName;
                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("listdevices")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                    result = new Vector<String>();
                    for (Enumeration<String> e = session.getAttributeNames(); e.hasMoreElements();) {
                        String attributeName = e.nextElement();
                        if (attributeName.startsWith("device_")) {
                            ((Vector<String>) result).add(attributeName);
                        }
                    }

                    break;

                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newgenericcallbackdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    GenericCallbackDevice genericCallBackDevice = ((RServices) session.getAttribute("R"))
                            .newGenericCallbackDevice();

                    String genericCallBackDeviceName = genericCallBackDevice.getId();
                    session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                    saveSessionAttributes(session);

                    result = genericCallBackDeviceName;

                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newspreadsheetmodeldevice")) {

                String spreadsheetModelDeviceId = request.getParameter("id");
                SpreadsheetModelRemote model = null;

                if (spreadsheetModelDeviceId == null || spreadsheetModelDeviceId.equals("")) {
                    model = ((RServices) session.getAttribute("R")).newSpreadsheetTableModelRemote(
                            Integer.decode(request.getParameter("rowcount")),
                            Integer.decode(request.getParameter("colcount")));
                } else {
                    model = ((RServices) session.getAttribute("R"))
                            .getSpreadsheetTableModelRemote(spreadsheetModelDeviceId);
                }

                SpreadsheetModelDevice spreadsheetDevice = model.newSpreadsheetModelDevice();
                String spreadsheetDeviceId = spreadsheetDevice.getId();
                session.setAttribute(spreadsheetDeviceId, spreadsheetDevice);
                saveSessionAttributes(session);
                result = spreadsheetDeviceId;
                break;

            } else if (command.equals("list")) {
                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }
                result = spFactory.getServantProvider().getRegistry().list();
                break;
            }

        } while (true);

    } catch (TunnelingException te) {
        result = te;
        te.printStackTrace();
    } catch (Throwable e) {
        result = new TunnelingException("Server Side", e);
        e.printStackTrace();
    }
    response.setContentType("application/x-java-serialized-object");
    new ObjectOutputStream(response.getOutputStream()).writeObject(result);
    response.flushBuffer();

}

From source file:org.sigmah.server.servlet.base.AbstractServlet.java

/**
 * Secures the given {@code servletMethod} execution.
 * /*ww w .ja v a  2s  .  c o m*/
 * @param request
 *          The HTTP request.
 * @param response
 *          The HTTP response.
 * @param servletMethod
 *          Java servlet method to execute once user session has been secured.
 * @throws ServletException
 *           If the servlet execution fails.
 */
private void secureServlet(final HttpServletRequest request, final HttpServletResponse response,
        final Method servletMethod) throws ServletException {

    if (servletMethod == null) {
        if (LOG.isErrorEnabled()) {
            LOG.error("The given servlet method {} is null.", servletMethod);
        }
        throw new IllegalArgumentException("Servlet method is required.");
    }

    User user = null;

    try {

        // Validates the user session and user access.
        final String authenticationToken = request.getParameter(ServletConstants.AUTHENTICATION_TOKEN);
        final String originPageToken = request.getParameter(ServletConstants.ORIGIN_PAGE_TOKEN);

        final String servletPath = request.getRequestURI().replaceFirst(ServletModule.ENDPOINT, "");
        final Servlet servletEnum = Servlet.fromPathName(servletPath);
        final ServletMethod servletMethodEnum = ServletMethod.fromMethodName(servletMethod.getName());

        final Access access = secureSessionValidator.validate(authenticationToken, servletEnum,
                servletMethodEnum, originPageToken);
        user = access.getUser();

        switch (access.getAccessType()) {

        case INVALID_SESSION:

            if (LOG.isDebugEnabled()) {
                LOG.debug(
                        "SERVLET METHOD EXECUTION FAILED - Servlet method: '{}' ; User: '{}' ; Error: Invalid auth token '{}'.",
                        servletMethod, Servlets.logUser(user), authenticationToken);
            }

            throw new InvalidSessionException("Your session is no longer valid.");

        case UNAUTHORIZED_ACCESS:

            if (LOG.isDebugEnabled()) {
                LOG.debug(
                        "SERVLET METHOD EXECUTION FAILED - Servlet method: '{}' ; User: '{}' ; Error: Unauthorized process.",
                        servletMethod, Servlets.logUser(user));
            }

            throw new UnauthorizedAccessException("You are not authorized to execute this process.");

        default:

            // Access granted, executes servlet method.
            if (LOG.isDebugEnabled()) {
                LOG.debug("SERVLET METHOD EXECUTION GRANTED - Servlet method: '{}' ; User: '{}'.",
                        servletMethod, Servlets.logUser(user));
            }

            // Activate filters into hibernate session.
            DomainFilters.applyUserFilter(user, entityManagerProvider.get());

            final StopWatch chrono = new StopWatch();
            chrono.start();

            servletMethod.setAccessible(true);
            servletMethod.invoke(this, request, response,
                    new ServletExecutionContext(access.getUser(), request, originPageToken));

            if (LOG.isDebugEnabled()) {
                LOG.debug("SERVLET METHOD '{}' EXECUTED IN {} MS.", servletMethod, chrono.getTime());
            }
        }

    } catch (final InvocationTargetException e) {

        // NO NEED TO LOG EXCEPTION HERE.

        if (e.getTargetException() instanceof ServletException) {
            // Servlet exception.
            throw (ServletException) e.getTargetException();

        } else if (e.getTargetException() instanceof ConstraintViolationException) {
            // Bean validation failed.
            final ConstraintViolationException cve = (ConstraintViolationException) e.getTargetException();

            if (LOG.isErrorEnabled()) {
                LOG.error("SERVLET METHOD EXECUTION FAILED - Servlet method: '" + servletMethod + "' ; User: '"
                        + Servlets.logUser(user)
                        + "' ; Error: A bean validation failed during servlet method execution. Consider performing the validation on client-side.\n"
                        + Servlets.logConstraints(cve.getConstraintViolations()));
            }

            throw new ServletException(e.getCause().getMessage(), cve);

        } else {
            throw new ServletException(e.getCause().getMessage(), e.getTargetException());
        }

    } catch (final Throwable e) {
        // Server unknown error.
        throw new ServletException(e.getMessage(), e);
    }
}

From source file:org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin.java

/**
 * Persist <code>path</code> as data directory and loads data from <code>path</code>. This method may block if other
 * jobs are running that modify tasks data. This method will only execute after all conflicting jobs have been
 * completed./* w ww .java  2s .c  om*/
 *
 * @throws CoreException
 *             in case setting of the data directory did not complete normally
 * @throws OperationCanceledException
 *             if the operation is cancelled by the user
 */
public void setDataDirectory(final String path) throws CoreException {
    Assert.isNotNull(path);
    IRunnableWithProgress runner = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                monitor.beginTask(Messages.TasksUiPlugin_Load_Data_Directory, IProgressMonitor.UNKNOWN);
                if (monitor.isCanceled()) {
                    throw new InterruptedException();
                }

                TasksUi.getTaskActivityManager().deactivateActiveTask();

                // set new preference in case of a change
                if (!path.equals(getDataDirectory())) {
                    getPreferenceStore().setValue(ITasksUiPreferenceConstants.PREF_DATA_DIR, path);
                }

                // reload data from new directory
                initializeDataSources();
            } finally {
                // FIXME roll back preferences change in case of an error?
                monitor.done();
            }
        }
    };

    IProgressService service = PlatformUI.getWorkbench().getProgressService();
    try {
        service.runInUI(service, runner, ITasksCoreConstants.ROOT_SCHEDULING_RULE);
    } catch (InvocationTargetException e) {
        throw new CoreException(
                new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Failed to set data directory", //$NON-NLS-1$
                        e.getCause()));
    } catch (InterruptedException e) {
        throw new OperationCanceledException();
    }
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

/**
 * Handles a YaCy servlet template, reads the template and replaces the template
 * items with actual values. Because of supported server side includes target 
 * might not be the same as request.getPathInfo
 * /*from ww  w  .  j a v  a 2  s . co m*/
 * @param target the path to the template
 * @param request the remote servlet request
 * @param response
 * @throws IOException
 * @throws ServletException
 */
protected void handleTemplate(String target, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Switchboard sb = Switchboard.getSwitchboard();

    String localeSelection = sb.getConfig("locale.language", "browser");
    if (localeSelection.endsWith("browser")) {
        String lng = request.getLocale().getLanguage();
        if (lng.equalsIgnoreCase("en")) { // because en is handled as "default" in localizer
            localeSelection = "default";
        } else {
            localeSelection = lng;
        }
    }
    File targetFile = getLocalizedFile(target, localeSelection);
    File targetClass = rewriteClassFile(_resourceBase.addPath(target).getFile());
    String targetExt = target.substring(target.lastIndexOf('.') + 1);

    long now = System.currentTimeMillis();
    if (target.endsWith(".css")) {
        response.setDateHeader(HeaderFramework.LAST_MODIFIED, now);
        response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour (which is still often, others use 1 week, month or year)
    } else if (target.endsWith(".png")) {
        // expires in 1 minute (reduce heavy image creation load)
        if (response.containsHeader(HeaderFramework.LAST_MODIFIED)) {
            response.getHeaders(HeaderFramework.LAST_MODIFIED).clear();
        }
        response.setHeader(HeaderFramework.CACHE_CONTROL, "public, max-age=" + Integer.toString(60));
    } else {
        response.setDateHeader(HeaderFramework.LAST_MODIFIED, now);
        response.setDateHeader(HeaderFramework.EXPIRES, now); // expires now
    }

    if ((targetClass != null)) {
        serverObjects args = new serverObjects();
        Enumeration<String> argNames = request.getParameterNames(); // on ssi jetty dispatcher merged local ssi query parameters
        while (argNames.hasMoreElements()) {
            String argName = argNames.nextElement();
            // standard attributes are just pushed as string
            args.put(argName, request.getParameter(argName));
        }
        RequestHeader legacyRequestHeader = generateLegacyRequestHeader(request, target, targetExt);
        // add multipart-form fields to parameter
        if (ServletFileUpload.isMultipartContent(request)) {
            final String bodyEncoding = request.getHeader(HeaderFramework.CONTENT_ENCODING);
            if (HeaderFramework.CONTENT_ENCODING_GZIP.equalsIgnoreCase(bodyEncoding)) {
                parseMultipart(new GZIPRequestWrapper(request), args);
            } else {
                parseMultipart(request, args);
            }
        }
        // eof modification to read attribute
        Object tmp;
        try {
            if (args.isEmpty()) {
                // yacy servlets typically test for args != null (but not for args .isEmpty())
                tmp = invokeServlet(targetClass, legacyRequestHeader, null);
            } else {
                tmp = invokeServlet(targetClass, legacyRequestHeader, args);
            }
        } catch (InvocationTargetException e) {
            if (e.getCause() instanceof InvalidURLLicenceException) {
                /* A non authaurized user is trying to fetch a image with a bad or already released license code */
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage());
                return;
            }
            if (e.getCause() instanceof TemplateMissingParameterException) {
                /* A template is used but miss some required parameter */
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage());
                return;
            }
            ConcurrentLog.logException(e);
            throw new ServletException(targetFile.getAbsolutePath());
        } catch (IllegalArgumentException | IllegalAccessException e) {
            ConcurrentLog.logException(e);
            throw new ServletException(targetFile.getAbsolutePath());
        }

        if (tmp instanceof RasterPlotter || tmp instanceof EncodedImage || tmp instanceof Image) {

            net.yacy.cora.util.ByteBuffer result = null;

            if (tmp instanceof RasterPlotter) {
                final RasterPlotter yp = (RasterPlotter) tmp;
                // send an image to client
                result = RasterPlotter.exportImage(yp.getImage(), "png");
            } else if (tmp instanceof EncodedImage) {
                final EncodedImage yp = (EncodedImage) tmp;
                result = yp.getImage();
                /** When encodedImage is empty, return a code 500 rather than only an empty response 
                 * as it is better handled across different browsers */
                if (result == null || result.length() == 0) {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    result.close();
                    return;
                }
                if (yp.isStatic()) { // static image never expires
                    response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour
                }
            } else if (tmp instanceof Image) {
                final Image i = (Image) tmp;

                // generate an byte array from the generated image
                int width = i.getWidth(null);
                if (width < 0) {
                    width = 96; // bad hack
                }
                int height = i.getHeight(null);
                if (height < 0) {
                    height = 96; // bad hack
                }
                final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
                bi.createGraphics().drawImage(i, 0, 0, width, height, null);
                result = RasterPlotter.exportImage(bi, targetExt);
            }

            updateRespHeadersForImages(target, response);
            final String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString());
            response.setContentType(mimeType);
            response.setContentLength(result.length());
            response.setStatus(HttpServletResponse.SC_OK);

            result.writeTo(response.getOutputStream());
            result.close();
            return;
        }

        if (tmp instanceof InputStream) {
            /* Images and favicons can also be written directly from an inputStream */
            updateRespHeadersForImages(target, response);

            writeInputStream(response, targetExt, (InputStream) tmp);
            return;
        }

        servletProperties templatePatterns;
        if (tmp == null) {
            // if no args given, then tp will be an empty Hashtable object (not null)
            templatePatterns = new servletProperties();
        } else if (tmp instanceof servletProperties) {
            templatePatterns = (servletProperties) tmp;

            if (templatePatterns.getOutgoingHeader() != null) {
                // handle responseHeader entries set by servlet
                ResponseHeader tmpouthdr = templatePatterns.getOutgoingHeader();
                for (String hdrkey : tmpouthdr.keySet()) {
                    if (!HeaderFramework.STATUS_CODE.equals(hdrkey)) { // skip default init response status value (not std. )
                        String val = tmpouthdr.get(hdrkey);
                        if (!response.containsHeader(hdrkey) && val != null) { // to be on the safe side, add only new hdr (mainly used for CORS_ALLOW_ORIGIN)
                            response.setHeader(hdrkey, tmpouthdr.get(hdrkey));
                        }
                    }
                }
                // handle login cookie
                if (tmpouthdr.getCookiesEntries() != null) {
                    for (Cookie c : tmpouthdr.getCookiesEntries()) {
                        response.addCookie(c);
                    }
                }
            }
        } else {
            templatePatterns = new servletProperties((serverObjects) tmp);
        }

        // handle YaCy http commands
        // handle action auth: check if the servlets requests authentication
        if (templatePatterns.containsKey(serverObjects.ACTION_AUTHENTICATE)) {
            if (!request.authenticate(response)) {
                return;
            }
            //handle action forward
        } else if (templatePatterns.containsKey(serverObjects.ACTION_LOCATION)) {
            String location = templatePatterns.get(serverObjects.ACTION_LOCATION, "");

            if (location.isEmpty()) {
                location = request.getPathInfo();
            }
            //TODO: handle equivalent of this from httpdfilehandler
            // final ResponseHeader headers = getDefaultHeaders(request.getPathInfo());
            // headers.setAdditionalHeaderProperties(templatePatterns.getOutgoingHeader().getAdditionalHeaderProperties()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?

            response.setHeader(HeaderFramework.LOCATION, location);
            response.setStatus(HttpServletResponse.SC_FOUND);
            return;
        }

        if (targetFile.exists() && targetFile.isFile() && targetFile.canRead()) {

            sb.setConfig("server.servlets.called",
                    appendPath(sb.getConfig("server.servlets.called", ""), target));
            if (args != null && !args.isEmpty()) {
                sb.setConfig("server.servlets.submitted",
                        appendPath(sb.getConfig("server.servlets.submitted", ""), target));
            }

            // add the application version, the uptime and the client name to every rewrite table
            templatePatterns.put(servletProperties.PEER_STAT_VERSION, yacyBuildProperties.getVersion());
            templatePatterns.put(servletProperties.PEER_STAT_UPTIME,
                    ((System.currentTimeMillis() - sb.startupTime) / 1000) / 60); // uptime in minutes
            templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTNAME, sb.peers.mySeed().getName());
            templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTID, sb.peers.myID());
            templatePatterns.put(servletProperties.PEER_STAT_MYTIME,
                    GenericFormatter.SHORT_SECOND_FORMATTER.format());
            templatePatterns.put(servletProperties.RELATIVE_BASE, YaCyDefaultServlet.getRelativeBase(target));
            Seed myPeer = sb.peers.mySeed();
            templatePatterns.put("newpeer", myPeer.getAge() >= 1 ? 0 : 1);
            templatePatterns.putHTML("newpeer_peerhash", myPeer.hash);
            boolean authorized = sb.adminAuthenticated(legacyRequestHeader) >= 2;
            templatePatterns.put("authorized", authorized ? 1 : 0); // used in templates and other html (e.g. to display lock/unlock symbol)

            templatePatterns.put("simpleheadernavbar",
                    sb.getConfig("decoration.simpleheadernavbar", "navbar-default"));

            // add navigation keys to enable or disable menu items
            templatePatterns.put("navigation-p2p",
                    sb.getConfigBool(SwitchboardConstants.DHT_ENABLED, true) || !sb.isRobinsonMode() ? 1 : 0);
            templatePatterns.put("navigation-p2p_authorized", authorized ? 1 : 0);
            String submitted = sb.getConfig("server.servlets.submitted", "");
            boolean crawler_enabled = true; /*
                                            submitted.contains("Crawler_p") ||
                                            submitted.contains("ConfigBasic") ||
                                            submitted.contains("Load_RSS_p");*/
            boolean advanced_enabled = crawler_enabled || submitted.contains("IndexImportMediawiki_p")
                    || submitted.contains("CrawlStart");
            templatePatterns.put("navigation-crawlmonitor", crawler_enabled);
            templatePatterns.put("navigation-crawlmonitor_authorized", authorized ? 1 : 0);
            templatePatterns.put("navigation-advanced", advanced_enabled);
            templatePatterns.put("navigation-advanced_authorized", authorized ? 1 : 0);
            templatePatterns.put(SwitchboardConstants.GREETING_HOMEPAGE,
                    sb.getConfig(SwitchboardConstants.GREETING_HOMEPAGE, ""));
            templatePatterns.put(SwitchboardConstants.GREETING_SMALL_IMAGE,
                    sb.getConfig(SwitchboardConstants.GREETING_SMALL_IMAGE, ""));
            templatePatterns.put(SwitchboardConstants.GREETING_IMAGE_ALT,
                    sb.getConfig(SwitchboardConstants.GREETING_IMAGE_ALT, ""));
            templatePatterns.put("clientlanguage", localeSelection);

            String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString());

            InputStream fis;
            long fileSize = targetFile.length();

            if (fileSize <= Math.min(4 * 1024 * 1204, MemoryControl.available() / 100)) {
                // read file completely into ram, avoid that too many files are open at the same time
                fis = new ByteArrayInputStream(FileUtils.read(targetFile));
            } else {
                fis = new BufferedInputStream(new FileInputStream(targetFile));
            }

            // set response header
            response.setContentType(mimeType);
            response.setStatus(HttpServletResponse.SC_OK);
            ByteArrayOutputStream bas = new ByteArrayOutputStream(4096);
            try {
                // apply templates
                TemplateEngine.writeTemplate(targetFile.getName(), fis, bas, templatePatterns);

                // handle SSI
                parseSSI(bas.toByteArray(), request, response);
            } finally {
                try {
                    fis.close();
                } catch (IOException ignored) {
                    ConcurrentLog.warn("FILEHANDLER",
                            "YaCyDefaultServlet: could not close target file " + targetFile.getName());
                }

                try {
                    bas.close();
                } catch (IOException ignored) {
                    /* Should never happen with a ByteArrayOutputStream */
                }
            }
        }
    }
}

From source file:com.newmainsoftech.spray.slingong.datastore.Slim3PlatformTransactionManagerTest.java

@Test
public void testRequiresNewPropagationOnExistingTransaction() throws Throwable {
    Method requiresNewPropagationOnExistingTransactionMethod = this.getClass()
            .getDeclaredMethod("requiresNewPropagationOnExistingTransaction", new Class<?>[] {});
    try {//  www.j a v a  2s  .com
        prepTransactionForPropergation(requiresNewPropagationOnExistingTransactionMethod);
        Assert.fail("TransactionSuspensionNotSupportedException exception wasn't thrown by "
                + requiresNewPropagationOnExistingTransactionMethod.getName() + " method");
    } catch (InvocationTargetException exception) {
        Throwable cause = exception.getCause();
        // TransactionSuspensionNotSupportedException is expected 
        if (!(cause instanceof TransactionSuspensionNotSupportedException)) {
            throw cause;
        }
    }

    verifyNoActiveGlobalTransaction();

    Assert.assertNull(Datastore.getCurrentGlobalTransaction());
    List<Author> authorList = Datastore.query(Author.class).asList();
    Assert.assertEquals(0, authorList.size());
    List<Book> bookList = Datastore.query(Book.class).asList();
    Assert.assertEquals(0, bookList.size());
    List<Chapter> chapterList = Datastore.query(Chapter.class).asList();
    Assert.assertEquals(0, chapterList.size());

    verifyGetNewTransactionProcess(TransactionAttribute.ISOLATION_DEFAULT,
            TransactionAttribute.PROPAGATION_REQUIRES_NEW, TransactionAttribute.TIMEOUT_DEFAULT,
            debugEnabledInAbstractPlatformTransactionManager, false);
    verifySuspendProcess();
    verifyRollbackProcess(false, false, debugEnabledInAbstractPlatformTransactionManager);
    verifyCommitProcess(false);

    verifyNoActiveGlobalTransaction();
}

From source file:com.newmainsoftech.spray.slingong.datastore.Slim3PlatformTransactionManagerTest.java

@Test
public void testNotSupportedPropagationOnExistingTransaction() throws Throwable {
    Method notSupportedPropagationOnExistingTransactionMethod = this.getClass()
            .getDeclaredMethod("notSupportedPropagationOnExistingTransaction", new Class<?>[] {});
    try {// w  w w .  j av  a 2s .  c o m
        prepTransactionForPropergation(notSupportedPropagationOnExistingTransactionMethod);
        Assert.fail("TransactionSuspensionNotSupportedException exception wasn't thrown by "
                + "notSupportedPropagationOnExistingTransaction method");
    } catch (InvocationTargetException exception) {
        Throwable cause = exception.getCause();
        // TransactionSuspensionNotSupportedException is expected 
        if (!(cause instanceof TransactionSuspensionNotSupportedException)) {
            throw cause;
        }
    }

    verifyNoActiveGlobalTransaction();

    Assert.assertNull(Datastore.getCurrentGlobalTransaction());
    List<Author> authorList = Datastore.query(Author.class).asList();
    Assert.assertEquals(0, authorList.size());
    List<Book> bookList = Datastore.query(Book.class).asList();
    Assert.assertEquals(0, bookList.size());
    List<Chapter> chapterList = Datastore.query(Chapter.class).asList();
    Assert.assertEquals(0, chapterList.size());

    verifyGetNewTransactionProcess(TransactionAttribute.ISOLATION_DEFAULT,
            TransactionAttribute.PROPAGATION_REQUIRES_NEW, TransactionAttribute.TIMEOUT_DEFAULT,
            debugEnabledInAbstractPlatformTransactionManager, false);
    verifySuspendProcess();
    verifyRollbackProcess(false, false, debugEnabledInAbstractPlatformTransactionManager);
    verifyCommitProcess(false);

    verifyNoActiveGlobalTransaction();
}

From source file:com.newmainsoftech.spray.slingong.datastore.Slim3PlatformTransactionManagerTest.java

@Test
public void testNeverPropagationOnExistingTransaction() throws Throwable {
    Method neverPropagationOnExistingTransactionMethod = this.getClass()
            .getDeclaredMethod("neverPropagationOnExistingTransaction", new Class<?>[] {});
    try {// w  w  w. j  av a  2 s  .co  m
        prepTransactionForPropergation(neverPropagationOnExistingTransactionMethod);
        Assert.fail("IllegalTransactionStateException exception wasn't thrown by "
                + neverPropagationOnExistingTransactionMethod.getName() + " method");
    } catch (InvocationTargetException exception) {
        // Expected NestedTransactionNotSupportedException exception
        Throwable cause = exception.getCause();
        if (!(cause instanceof IllegalTransactionStateException)) {
            throw cause;
        }
    }

    verifyNoActiveGlobalTransaction();

    Assert.assertNull(Datastore.getCurrentGlobalTransaction());
    List<Author> authorList = Datastore.query(Author.class).asList();
    Assert.assertEquals(0, authorList.size());
    List<Book> bookList = Datastore.query(Book.class).asList();
    Assert.assertEquals(0, bookList.size());
    List<Chapter> chapterList = Datastore.query(Chapter.class).asList();
    Assert.assertEquals(0, chapterList.size());

    verifyGetNewTransactionProcess(TransactionAttribute.ISOLATION_DEFAULT,
            TransactionAttribute.PROPAGATION_REQUIRES_NEW, TransactionAttribute.TIMEOUT_DEFAULT,
            debugEnabledInAbstractPlatformTransactionManager, false);

    // public final TransactionStatus getTransaction(TransactionDefinition definition)

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1)).doGetTransaction();

    ArgumentCaptor<Object> objectArgumentCaptor = ArgumentCaptor.forClass(Object.class);
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .isExistingTransaction(objectArgumentCaptor.capture());
    Assert.assertTrue(objectArgumentCaptor.getValue() instanceof GlobalTransaction);

    // private TransactionStatus handleExistingTransaction( TransactionDefinition definition, Object transaction, boolean debugEnabled)

    verifyRollbackProcess(false, false, debugEnabledInAbstractPlatformTransactionManager);
    verifyCommitProcess(false);

    verifyNoActiveGlobalTransaction();
}

From source file:com.newmainsoftech.spray.slingong.datastore.Slim3PlatformTransactionManagerTest.java

@Test
public void testNestedPropagationOnExistingTransaction1() throws Throwable {
    Method nestedPropagationOnExistingTransactionMethod = this.getClass()
            .getDeclaredMethod("nestedPropagationOnExistingTransaction", new Class<?>[] {});
    try {// ww  w .ja  v  a  2 s.co  m
        prepTransactionForPropergation(nestedPropagationOnExistingTransactionMethod);
        Assert.fail("NestedTransactionNotSupportedException exception wasn't thrown by "
                + nestedPropagationOnExistingTransactionMethod.getName() + " method");
    } catch (InvocationTargetException exception) {
        // Expected NestedTransactionNotSupportedException exception
        Throwable cause = exception.getCause();
        if (!(cause instanceof NestedTransactionNotSupportedException)) {
            throw cause;
        }
    }

    verifyNoActiveGlobalTransaction();

    List<Author> authorList = Datastore.query(Author.class).asList();
    Assert.assertEquals(0, authorList.size());
    List<Book> bookList = Datastore.query(Book.class).asList();
    Assert.assertEquals(0, bookList.size());
    List<Chapter> chapterList = Datastore.query(Chapter.class).asList();
    Assert.assertEquals(0, chapterList.size());

    verifyGetNewTransactionProcess(TransactionAttribute.ISOLATION_DEFAULT,
            TransactionAttribute.PROPAGATION_REQUIRES_NEW, TransactionAttribute.TIMEOUT_DEFAULT,
            debugEnabledInAbstractPlatformTransactionManager, false);

    // public final TransactionStatus getTransaction(TransactionDefinition definition)

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1)).doGetTransaction();

    ArgumentCaptor<Object> objectArgumentCaptor = ArgumentCaptor.forClass(Object.class);
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .isExistingTransaction(objectArgumentCaptor.capture());
    Assert.assertTrue(objectArgumentCaptor.getValue() instanceof GlobalTransaction);

    // private TransactionStatus handleExistingTransaction( TransactionDefinition definition, Object transaction, boolean debugEnabled)
    // public final boolean isNestedTransactionAllowed()

    verifyRollbackProcess(false, false, debugEnabledInAbstractPlatformTransactionManager);
    verifyCommitProcess(false);

    verifyNoActiveGlobalTransaction();
}

From source file:org.codice.ddf.spatial.ogc.wfs.v2_0_0.catalog.source.WfsFilterDelegateTest.java

private void testSequentialPropertyIsNotOfTemporalType(String methName, Object... inputParams)
        throws Throwable {
    String mockMetacardAttribute = "myMetacardAttribute";
    String mockFeatureType = "myFeatureType";
    String mockFeatureProperty = "myFeatureProperty";
    List<String> mockProperties = new ArrayList<>(1);
    mockProperties.add(mockFeatureProperty);
    when(mockFeatureMetacardType.getProperties()).thenReturn(mockProperties);
    when(mockFeatureMetacardType.getName()).thenReturn(mockFeatureType);
    List<String> mockTemporalProperties = Collections.emptyList();
    when(mockFeatureMetacardType.getTemporalProperties()).thenReturn(mockTemporalProperties);
    FeatureAttributeDescriptor mockFeatureAttributeDescriptor = mock(FeatureAttributeDescriptor.class);
    when(mockFeatureAttributeDescriptor.isIndexed()).thenReturn(true);
    when(mockFeatureAttributeDescriptor.getPropertyName()).thenReturn(mockFeatureProperty);
    when(mockFeatureMetacardType.getAttributeDescriptor(mockFeatureProperty))
            .thenReturn(mockFeatureAttributeDescriptor);
    MetacardMapper mockMapper = mock(MetacardMapper.class);
    when(mockMapper.getFeatureProperty(mockMetacardAttribute)).thenReturn(mockFeatureProperty);
    WfsFilterDelegate delegate = new WfsFilterDelegate(mockFeatureMetacardType,
            MockWfsServer.getFilterCapabilities(), GeospatialUtil.EPSG_4326_URN, mockMapper,
            GeospatialUtil.LAT_LON_ORDER);

    try {//w ww . j a va2s .  co  m
        // Inject the mockMetacardAttribute at the head of the array
        Object[] methParams = ObjectArrays.concat(mockMetacardAttribute, inputParams);
        // Generate the array of class types for the reflection call
        Class<?>[] classTypes = FluentIterable.from(Arrays.asList(methParams))
                .transform(new Function<Object, Class>() {
                    @Override
                    public Class<?> apply(Object o) {
                        // Autoboxing is a small problem with reflection when trying to be too clever
                        return (o instanceof Long) ? long.class : o.getClass();
                    }
                }).toArray(Class.class);

        Method method = WfsFilterDelegate.class.getMethod(methName, classTypes);
        method.invoke(delegate, methParams);
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}