Example usage for java.lang.reflect UndeclaredThrowableException UndeclaredThrowableException

List of usage examples for java.lang.reflect UndeclaredThrowableException UndeclaredThrowableException

Introduction

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

Prototype

public UndeclaredThrowableException(Throwable undeclaredThrowable) 

Source Link

Document

Constructs an UndeclaredThrowableException with the specified Throwable .

Usage

From source file:org.opennms.netmgt.selta.scheduler.LegacyScheduler.java

/**
 * The main method of the scheduler. This method is responsible for checking
 * the runnable queues for ready objects and then enqueuing them into the
 * thread pool for execution.//from  www  . j av a  2s  .c  o  m
 */
public void run() {
    synchronized (this) {
        m_status = RUNNING;
    }

    log().debug("run: scheduler running");

    /*
     * Loop until a fatal exception occurs or until
     * the thread is interrupted.
     */
    for (;;) {
        /*
         * Block if there is nothing in the queue(s).
         * When something is added to the queue it
         * signals us to wakeup.
         */
        synchronized (this) {

            if (m_status != RUNNING && m_status != PAUSED && m_status != PAUSE_PENDING
                    && m_status != RESUME_PENDING) {
                if (log().isDebugEnabled()) {
                    log().debug("run: status = " + m_status + ", time to exit");
                }
                break;
            }

            // if paused or pause pending then block
            while (m_status == PAUSE_PENDING || m_status == PAUSED) {
                if (m_status == PAUSE_PENDING) {
                    log().debug("run: pausing.");
                }
                m_status = PAUSED;
                try {
                    wait();
                } catch (InterruptedException ex) {
                    // exit
                    break;
                }
            }

            // if resume pending then change to running

            if (m_status == RESUME_PENDING) {
                log().debug("run: resuming.");

                m_status = RUNNING;
            }

            if (m_scheduled == 0) {
                try {
                    log().debug("run: no ready runnables scheduled, waiting...");
                    wait();
                } catch (InterruptedException ex) {
                    break;
                }
            }
        }

        /*
         * Cycle through the queues checking for
         * what's ready to run.  The queues are keyed
         * by the interval, but the mapped elements
         * are peekable fifo queues.
         */
        int runned = 0;
        synchronized (m_queues) {
            /*
             * Get an iterator so that we can cycle
             * through the queue elements.
             */
            for (Entry<Long, PeekableFifoQueue<ReadyRunnable>> entry : m_queues.entrySet()) {
                /*
                 * Peak for Runnable objects until
                 * there are no more ready runnables.
                 *
                 * Also, only go through each queue once!
                 * if we didn't add a count then it would
                 * be possible to starve other queues.
                 */
                PeekableFifoQueue<ReadyRunnable> in = entry.getValue();
                ReadyRunnable readyRun = null;
                int maxLoops = in.size();
                do {
                    try {
                        readyRun = in.peek();
                        if (readyRun != null && readyRun.isReady()) {
                            if (log().isDebugEnabled()) {
                                log().debug("run: found ready runnable " + readyRun);
                            }

                            /*
                             * Pop the interface/readyRunnable from the
                             * queue for execution.
                             */
                            in.remove();

                            // Add runnable to the execution queue
                            m_runner.execute(readyRun);
                            ++runned;
                        }
                    } catch (InterruptedException e) {
                        return; // jump all the way out
                    } catch (RejectedExecutionException e) {
                        throw new UndeclaredThrowableException(e);
                    }

                } while (readyRun != null && readyRun.isReady() && --maxLoops > 0);
            }
        }

        /*
         * Wait for 1 second if there were no runnables
         * executed during this loop, otherwise just
         * start over.
         */
        synchronized (this) {
            m_scheduled -= runned;
            if (runned == 0) {
                try {
                    wait(1000);
                } catch (InterruptedException ex) {
                    break; // exit for loop
                }
            }
        }

    }

    log().debug("run: scheduler exiting, state = STOPPED");
    synchronized (this) {
        m_status = STOPPED;
    }

}

From source file:com.ibm.jaql.lang.expr.system.RFn.java

@Override
public JsonValue eval(Context context) throws Exception {
    try {/*from ww w . j  a v  a 2s  .c om*/
        if (proc == null) {
            init(context);
        }

        JsonString fn = (JsonString) exprs[INDEX_FN].eval(context);
        if (fn == null) {
            throw new IllegalArgumentException("R(init, fn, ...): R function required");
        }
        binary = ((JsonBool) exprs[INDEX_BINARY].eval(context)).get();
        JsonValue tmp = exprs[INDEX_OUT_SCHEMA].eval(context);
        if (tmp != null) {
            if (!(tmp instanceof JsonSchema))
                throw new IllegalArgumentException("Invalid outSchema.");
            schema = ((JsonSchema) tmp).get();
        } else if (binary) {
            schema = SchemaFactory.binarySchema();
        }
        if (LOG.isDebugEnabled())
            LOG.debug("Initialized outSchema to: " + schema);
        String sep = "";
        File rOut = null;
        if (binary) {
            String tmpFileName = RUtil.getTempFileName();
            rOut = new File(tmpFileName);
            tmpFileName = rOut.getAbsolutePath();
            tmpFileName = tmpFileName.replace('\\', '/');
            rOut.deleteOnExit();
            stdin.print("cat(toBinary(file='");
            stdin.print(tmpFileName);
            stdin.print("',");
        } else {
            stdin.print("cat(toJSON(");
        }
        stdin.print("(");
        stdin.print(fn);
        stdin.print(")");
        tmp = exprs[INDEX_ARGS].eval(context);
        if (tmp != null) // we have args
        {
            if (!(tmp instanceof JsonArray)) {
                throw new IllegalArgumentException(
                        "Arguments to function " + fn + " must be enclosed as an array.");
            }
            JsonArray args = (JsonArray) tmp;
            tmp = exprs[INDEX_IN_SCHEMA].eval(context);
            JsonArray argSchema = null;
            if (tmp != null) {
                if (!(tmp instanceof JsonArray)) {
                    throw new IllegalArgumentException(
                            "Schema for arguments of function " + fn + " must be enclosed in an array");
                }
                argSchema = (JsonArray) tmp;
            }
            Schema inferred = exprs[INDEX_ARGS].getSchema();
            stdin.print("(");
            for (int i = 0; i < args.count(); i++) {
                JsonValue value = args.get(i);
                Schema elemSchema = null;
                if (argSchema != null) {
                    tmp = argSchema.get(i);
                    if (!(tmp instanceof JsonSchema)) {
                        throw new IllegalArgumentException("Argument schema at index " + i
                                + " not an instance of " + JsonSchema.class.getCanonicalName());
                    }
                    elemSchema = ((JsonSchema) tmp).get();
                } else {
                    elemSchema = inferred.element(new JsonLong(i));
                }
                stdin.print(sep);
                processFnArgument(context, value, elemSchema);
                sep = ",";
            }
            stdin.print(")");
        }
        stdin.println("),'\n')");
        stdin.flush();

        // parser.ReInit(stdout); 
        // TODO: we can read directly from the stdout stream, but error reporting is not so good...
        String s = stdout.readLine();
        if (s == null) {
            throw new RuntimeException("unexpected EOF from R");
        }
        if (binary) {
            byte[] buffer = new byte[4096];
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(rOut), 4096);
            int length = 0;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            in.close();
            rOut.delete();
            byte[] rBin = out.toByteArray();
            //System.err.println("Output: " + new String(rBin));
            return new JsonBinary(rBin);
        } else {
            parser.ReInit(new StringReader(s));
            try {
                JsonValue result = parser.JsonVal();
                return result;
            } catch (Exception e) {
                System.err.println("Bad JSON from R:\n" + s);
                throw e;
            }
        }
    } catch (Throwable e) {
        if (error == null) {
            error = e;
        }
        if (stdin != null) {
            try {
                stdin.close();
            } catch (Throwable t) {
            }
            stdin = null;
        }
        if (stdout != null) {
            try {
                stdout.close();
            } catch (Throwable t) {
            }
            stdout = null;
        }
        if (proc != null) {
            try {
                proc.destroy();
            } catch (Throwable t) {
            }
            proc = null;
        }
        if (error instanceof Exception) {
            throw (Exception) error;
        }
        throw new UndeclaredThrowableException(error);
    }
}

From source file:org.vietspider.net.client.impl.AbstractHttpClient.java

public <T> T execute(final HttpHost target, final HttpRequest request,
        final ResponseHandler<? extends T> responseHandler, final HttpContext context)
        throws IOException, ClientProtocolException {
    if (responseHandler == null) {
        throw new IllegalArgumentException("Response handler must not be null.");
    }/*from www. j  ava  2s  . c o  m*/

    HttpResponse response = execute(target, request, context);

    T result;
    try {
        result = responseHandler.handleResponse(response);
    } catch (Throwable t) {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (Throwable t2) {
                // Log this exception. The original exception is more
                // important and will be thrown to the caller.
                //        this.log.warn("Error consuming content after an exception.", t2);
            }
        }

        if (t instanceof Error) {
            throw (Error) t;
        }

        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        }

        if (t instanceof IOException) {
            throw (IOException) t;
        }

        throw new UndeclaredThrowableException(t);
    }

    // Handling the response was successful. Ensure that the content has
    // been fully consumed.
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        // Let this exception go to the caller.
        entity.consumeContent();
    }

    return result;
}

From source file:de.sub.goobi.export.dms.ExportDms.java

/**
 * Download image./*from w w  w.j  ava  2  s.  c o m*/
 *
 * @param process
 *            object
 * @param userHome
 *            File
 * @param atsPpnBand
 *            String
 * @param ordnerEndung
 *            String
 */
public void imageDownload(Process process, URI userHome, String atsPpnBand, final String ordnerEndung)
        throws IOException, InterruptedException {

    /*
     * dann den Ausgangspfad ermitteln
     */
    URI tifOrdner = serviceManager.getProcessService().getImagesTifDirectory(true, process);

    /*
     * jetzt die Ausgangsordner in die Zielordner kopieren
     */
    if (fileService.fileExist(tifOrdner) && fileService.getSubUris(tifOrdner).size() > 0) {
        URI zielTif = userHome.resolve(File.separator + atsPpnBand + ordnerEndung);

        /* bei Agora-Import einfach den Ordner anlegen */
        if (process.getProject().isUseDmsImport()) {
            if (!fileService.fileExist(zielTif)) {
                fileService.createDirectory(userHome, atsPpnBand + ordnerEndung);
            }
        } else {
            /*
             * wenn kein Agora-Import, dann den Ordner mit
             * Benutzerberechtigung neu anlegen
             */
            User myUser = (User) Helper.getManagedBeanValue("#{LoginForm.myBenutzer}");
            try {
                fileService.createDirectoryForUser(zielTif, myUser.getLogin());
            } catch (Exception e) {
                if (exportDmsTask != null) {
                    exportDmsTask.setException(e);
                } else {
                    Helper.setFehlerMeldung("Export canceled, error", "could not create destination directory");
                }
                logger.error("could not create destination directory", e);
                if (e instanceof IOException) {
                    throw (IOException) e;
                } else if (e instanceof InterruptedException) {
                    throw (InterruptedException) e;
                } else if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                } else {
                    throw new UndeclaredThrowableException(e);
                }
            }
        }

        /* jetzt den eigentlichen Kopiervorgang */

        ArrayList<URI> dateien = fileService.getSubUris(Helper.dataFilter, tifOrdner);
        for (int i = 0; i < dateien.size(); i++) {
            if (exportDmsTask != null) {
                exportDmsTask.setWorkDetail(fileService.getFileName(dateien.get(i)));
            }
            URI meinZiel = zielTif.resolve(File.separator + fileService.getFileName(dateien.get(i)));
            fileService.copyFile(dateien.get(i), meinZiel);
            if (exportDmsTask != null) {
                exportDmsTask.setProgress((int) ((i + 1) * 98d / dateien.size() + 1));
                if (exportDmsTask.isInterrupted()) {
                    throw new InterruptedException();
                }
            }
        }
        if (exportDmsTask != null) {
            exportDmsTask.setWorkDetail(null);
        }
    }
}

From source file:Base64.java

/** Converts the given base64 encoded character buffer into a byte array.
 * @param pBuffer The character buffer being decoded.
 * @param pOffset Offset of first character being decoded.
 * @param pLength Number of characters being decoded.
 * @return Converted byte array/* w w w.ja  v  a 2 s  .  c  om*/
 * @throws DecodingException The input character stream contained invalid data.
 */
public static byte[] decode(char[] pBuffer, int pOffset, int pLength) throws DecodingException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Decoder d = new Decoder(1024) {
        protected void writeBuffer(byte[] pBuf, int pOff, int pLen) throws IOException {
            baos.write(pBuf, pOff, pLen);
        }
    };
    try {
        d.write(pBuffer, pOffset, pLength);
        d.flush();
    } catch (DecodingException e) {
        throw e;
    } catch (IOException e) {
        throw new UndeclaredThrowableException(e);
    }
    return baos.toByteArray();
}

From source file:volumesculptor.shell.Main.java

/**
 * Evaluate JavaScript source.//from w ww  .  j a  v a2s .  c o  m
 *
 * @param cx       the current context
 * @param filename the name of the file to compile, or null
 *                 for interactive mode.
 * @throws IOException    if the source could not be read
 * @throws RhinoException thrown during evaluation of source
 */
public static TriangleMesh processSource(Context cx, String filename, Object[] args, boolean show)
        throws IOException {
    if (filename == null || filename.equals("-")) {
        Scriptable scope = getShellScope();
        PrintStream ps = global.getErr();
        if (filename == null) {
            // print implementation version
            ps.println(cx.getImplementationVersion());
        }

        String charEnc = shellContextFactory.getCharacterEncoding();
        if (charEnc == null) {
            charEnc = System.getProperty("file.encoding");
        }
        BufferedReader in;
        try {
            in = new BufferedReader(new InputStreamReader(global.getIn(), charEnc));
        } catch (UnsupportedEncodingException e) {
            throw new UndeclaredThrowableException(e);
        }
        int lineno = 1;
        boolean hitEOF = false;
        while (!hitEOF) {
            String[] prompts = global.getPrompts(cx);
            if (filename == null)
                ps.print(prompts[0]);
            ps.flush();
            String source = "";

            // Collect lines of source to compile.
            while (true) {
                String newline;
                try {
                    newline = in.readLine();
                } catch (IOException ioe) {
                    ps.println(ioe.toString());
                    break;
                }
                if (newline == null) {
                    hitEOF = true;
                    break;
                }
                source = source + newline + "\n";
                lineno++;
                if (cx.stringIsCompilableUnit(source))
                    break;
                ps.print(prompts[1]);
            }
            try {
                Script script = cx.compileString(source, "<stdin>", lineno, null);
                if (script != null) {

                    Object result = script.exec(cx, scope);
                    // Avoid printing out undefined or function definitions.
                    if (result != Context.getUndefinedValue()
                            && !(result instanceof Function && source.trim().startsWith("function"))) {
                        try {
                            ps.println(Context.toString(result));
                        } catch (RhinoException rex) {
                            ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                        }
                    }
                    NativeArray h = global.history;
                    h.put((int) h.getLength(), h, source);
                    return executeMain(cx, scope, show, args);
                }
            } catch (RhinoException rex) {
                ToolErrorReporter.reportException(cx.getErrorReporter(), rex);
                exitCode = EXITCODE_RUNTIME_ERROR;
            } catch (VirtualMachineError ex) {
                // Treat StackOverflow and OutOfMemory as runtime errors
                ex.printStackTrace();
                String msg = ToolErrorReporter.getMessage("msg.uncaughtJSException", ex.toString());
                Context.reportError(msg);
                exitCode = EXITCODE_RUNTIME_ERROR;
            }
        }
        ps.println();
    } else if (useRequire && filename.equals(mainModule)) {
        require.requireMain(cx, filename);
    } else {
        return processFile(cx, getScope(filename), filename, args, show);
    }

    return null;
}

From source file:org.opennms.ng.dao.support.DefaultResourceDao.java

/**
 * Encapsulate the deprecated decode method to fix it in one place.
 *
 * @param string/* w  w  w .j  a va 2s .c o m*/
 *            string to be decoded
 * @return decoded string
 */
public static String decode(String string) {
    try {
        return URLDecoder.decode(string, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // UTF-8 should *never* throw this
        throw new UndeclaredThrowableException(e);
    }
}

From source file:org.apache.http.impl.client.AbstractHttpClient.java

@Override
protected final CloseableHttpResponse doExecute(final HttpHost target, final HttpRequest request,
        final HttpContext context) throws IOException, ClientProtocolException {

    Args.notNull(request, "HTTP request");
    // a null target may be acceptable, this depends on the route planner
    // a null context is acceptable, default context created below

    HttpContext execContext = null;
    RequestDirector director = null;//from  w ww . java 2s. c  om
    HttpRoutePlanner routePlanner = null;
    ConnectionBackoffStrategy connectionBackoffStrategy = null;
    BackoffManager backoffManager = null;

    // Initialize the request execution context making copies of
    // all shared objects that are potentially threading unsafe.
    synchronized (this) {

        final HttpContext defaultContext = createHttpContext();
        if (context == null) {
            execContext = defaultContext;
        } else {
            execContext = new DefaultedHttpContext(context, defaultContext);
        }
        final HttpParams params = determineParams(request);
        final RequestConfig config = HttpClientParamConfig.getRequestConfig(params);
        execContext.setAttribute(ClientContext.REQUEST_CONFIG, config);

        // Create a director for this request
        director = createClientRequestDirector(getRequestExecutor(), getConnectionManager(),
                getConnectionReuseStrategy(), getConnectionKeepAliveStrategy(), getRoutePlanner(),
                getProtocolProcessor(), getHttpRequestRetryHandler(), getRedirectStrategy(),
                getTargetAuthenticationStrategy(), getProxyAuthenticationStrategy(), getUserTokenHandler(),
                params);
        routePlanner = getRoutePlanner();
        connectionBackoffStrategy = getConnectionBackoffStrategy();
        backoffManager = getBackoffManager();
    }

    try {
        if (connectionBackoffStrategy != null && backoffManager != null) {
            final HttpHost targetForRoute = (target != null) ? target
                    : (HttpHost) determineParams(request).getParameter(ClientPNames.DEFAULT_HOST);
            final HttpRoute route = routePlanner.determineRoute(targetForRoute, request, execContext);

            final CloseableHttpResponse out;
            try {
                out = CloseableHttpResponseProxy.newProxy(director.execute(target, request, execContext));
            } catch (final RuntimeException re) {
                if (connectionBackoffStrategy.shouldBackoff(re)) {
                    backoffManager.backOff(route);
                }
                throw re;
            } catch (final Exception e) {
                if (connectionBackoffStrategy.shouldBackoff(e)) {
                    backoffManager.backOff(route);
                }
                if (e instanceof HttpException) {
                    throw (HttpException) e;
                }
                if (e instanceof IOException) {
                    throw (IOException) e;
                }
                throw new UndeclaredThrowableException(e);
            }
            if (connectionBackoffStrategy.shouldBackoff(out)) {
                backoffManager.backOff(route);
            } else {
                backoffManager.probe(route);
            }
            return out;
        } else {
            return CloseableHttpResponseProxy.newProxy(director.execute(target, request, execContext));
        }
    } catch (final HttpException httpException) {
        throw new ClientProtocolException(httpException);
    }
}

From source file:org.opennms.netmgt.collectd.HttpCollector.java

private static void initHttpCollectionConfig() {
    try {/*from ww w  .java  2  s.  c  om*/
        LOG.debug("initialize: Initializing collector: {}", HttpCollector.class.getSimpleName());
        HttpCollectionConfigFactory.init();
    } catch (MarshalException e) {
        LOG.error("initialize: Error marshalling configuration.", e);
        throw new UndeclaredThrowableException(e);
    } catch (ValidationException e) {
        LOG.error("initialize: Error validating configuration.", e);
        throw new UndeclaredThrowableException(e);
    } catch (FileNotFoundException e) {
        LOG.error("initialize: Error locating configuration.", e);
        throw new UndeclaredThrowableException(e);
    } catch (IOException e) {
        LOG.error("initialize: Error reading configuration", e);
        throw new UndeclaredThrowableException(e);
    }
}

From source file:org.apache.http2.impl.client.AbstractHttpClient.java

@Override
public final HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws IOException, ClientProtocolException {

    if (request == null) {
        throw new IllegalArgumentException("Request must not be null.");
    }/*w ww .  ja v a2  s .c  om*/
    // a null target may be acceptable, this depends on the route planner
    // a null context is acceptable, default context created below

    HttpContext execContext = null;
    RequestDirector director = null;
    HttpRoutePlanner routePlanner = null;
    ConnectionBackoffStrategy connectionBackoffStrategy = null;
    BackoffManager backoffManager = null;

    // Initialize the request execution context making copies of
    // all shared objects that are potentially threading unsafe.
    synchronized (this) {

        HttpContext defaultContext = createHttpContext();
        if (context == null) {
            execContext = defaultContext;
        } else {
            execContext = new DefaultedHttpContext(context, defaultContext);
        }
        // Create a director for this request
        director = createClientRequestDirector(getRequestExecutor(), getConnectionManager(),
                getConnectionReuseStrategy(), getConnectionKeepAliveStrategy(), getRoutePlanner(),
                getProtocolProcessor(), getHttpRequestRetryHandler(), getRedirectStrategy(),
                getTargetAuthenticationStrategy(), getProxyAuthenticationStrategy(), getUserTokenHandler(),
                determineParams(request));
        routePlanner = getRoutePlanner();
        connectionBackoffStrategy = getConnectionBackoffStrategy();
        backoffManager = getBackoffManager();
    }

    try {
        if (connectionBackoffStrategy != null && backoffManager != null) {
            HttpHost targetForRoute = (target != null) ? target
                    : (HttpHost) determineParams(request).getParameter(ClientPNames.DEFAULT_HOST);
            HttpRoute route = routePlanner.determineRoute(targetForRoute, request, execContext);

            HttpResponse out;
            try {
                out = director.execute(target, request, execContext);
            } catch (RuntimeException re) {
                if (connectionBackoffStrategy.shouldBackoff(re)) {
                    backoffManager.backOff(route);
                }
                throw re;
            } catch (Exception e) {
                if (connectionBackoffStrategy.shouldBackoff(e)) {
                    backoffManager.backOff(route);
                }
                if (e instanceof HttpException) {
                    throw (HttpException) e;
                }
                if (e instanceof IOException) {
                    throw (IOException) e;
                }
                throw new UndeclaredThrowableException(e);
            }
            if (connectionBackoffStrategy.shouldBackoff(out)) {
                backoffManager.backOff(route);
            } else {
                backoffManager.probe(route);
            }
            return out;
        } else {
            return director.execute(target, request, execContext);
        }
    } catch (HttpException httpException) {
        throw new ClientProtocolException(httpException);
    }
}