Example usage for java.io IOException getCause

List of usage examples for java.io IOException getCause

Introduction

In this page you can find the example usage for java.io IOException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:fr.univrouen.poste.web.candidat.MyPosteCandidatureController.java

@RequestMapping(value = "/{id}/{idFile}")
@PreAuthorize("hasPermission(#id, 'view')")
public void downloadCandidatureFile(@PathVariable("id") Long id, @PathVariable("idFile") Long idFile,
        HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
    try {/* w  w w .j  a  va 2s  . co m*/
        PosteCandidature postecandidature = PosteCandidature.findPosteCandidature(id);
        PosteCandidatureFile postecandidatureFile = PosteCandidatureFile.findPosteCandidatureFile(idFile);
        String filename = postecandidatureFile.getFilename();
        Long size = postecandidatureFile.getFileSize();
        String contentType = postecandidatureFile.getContentType();
        response.setContentType(contentType);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setContentLength(size.intValue());
        IOUtils.copy(postecandidatureFile.getBigFile().getBinaryFile().getBinaryStream(),
                response.getOutputStream());

        Calendar cal = Calendar.getInstance();
        Date currentTime = cal.getTime();

        logService.logActionFile(LogService.DOWNLOAD_ACTION, postecandidature, postecandidatureFile, request,
                currentTime);
    } catch (IOException ioe) {
        String ip = request.getRemoteAddr();
        logger.warn("Download IOException, that can be just because the client [" + ip
                + "] canceled the download process : " + ioe.getCause());
    }
}

From source file:fr.univrouen.poste.web.candidat.MyPosteCandidatureController.java

@RequestMapping(value = "/{id}/reviewFile/{idFile}")
@PreAuthorize("hasPermission(#id, 'review')")
public void downloadReviewFile(@PathVariable("id") Long id, @PathVariable("idFile") Long idFile,
        HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
    try {//from  w ww .  ja v  a 2 s  .  c  o  m
        PosteCandidature postecandidature = PosteCandidature.findPosteCandidature(id);
        MemberReviewFile memberReviewFile = MemberReviewFile.findMemberReviewFile(idFile);
        // byte[] file = postecandidatureFile.getBigFile().getBinaryFile();
        String filename = memberReviewFile.getFilename();
        Long size = memberReviewFile.getFileSize();
        String contentType = memberReviewFile.getContentType();
        response.setContentType(contentType);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setContentLength(size.intValue());
        IOUtils.copy(memberReviewFile.getBigFile().getBinaryFile().getBinaryStream(),
                response.getOutputStream());

        Calendar cal = Calendar.getInstance();
        Date currentTime = cal.getTime();
        //postecandidature.setModification(currentTime);

        logService.logActionFile(LogService.DOWNLOAD_REVIEW_ACTION, postecandidature, memberReviewFile, request,
                currentTime);
    } catch (IOException ioe) {
        String ip = request.getRemoteAddr();
        logger.warn("Download IOException, that can be just because the client [" + ip
                + "] canceled the download process : " + ioe.getCause());
    }
}

From source file:com.fanfou.app.opensource.api.ApiClientImpl.java

/**
 * exec http request/*from   w w  w. ja v  a2 s .c  om*/
 * 
 * @param request
 * @return response object
 * @throws ApiException
 */
private SimpleResponse fetch(final SimpleRequest request) throws ApiException {
    final Context context = getAppContext();
    if (context == null) {
        throw new ApiException(ResponseCode.ERROR_IO_EXCEPTION, "context is null");
    }
    final OAuthToken token = AppContext.getOAuthToken();
    final OAuthService service = new OAuthService(ApiClientImpl.OAUTH_CONFIG, token);
    try {
        service.addOAuthSignature(request);
        final SimpleClient client = new SimpleClient(context);
        final HttpResponse response = client.exec(request);
        final SimpleResponse res = new SimpleResponse(response);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (AppContext.DEBUG) {
            log("fetch() url=" + request.url + " post=" + request.post + " statusCode=" + statusCode);
        }
        if (statusCode == ResponseCode.HTTP_OK) {
            return res;
        } else {
            throw new ApiException(statusCode, ApiParser.error(res.getContent()));
        }
    } catch (final IOException e) {
        if (AppContext.DEBUG) {
            Log.e(ApiClientImpl.TAG, e.toString());
        }
        throw new ApiException(ResponseCode.ERROR_IO_EXCEPTION, e.getMessage(), e.getCause());
    }
}

From source file:org.apache.hadoop.hive.ql.Context.java

/**
 * Create a map-reduce scratch directory on demand and return it.
 *
 *//* www .  jav a2 s  . c o  m*/
public Path getMRScratchDir() {

    // if we are executing entirely on the client side - then
    // just (re)use the local scratch directory
    if (isLocalOnlyExecutionMode()) {
        return getLocalScratchDir(!isExplainSkipExecution());
    }

    try {
        Path dir = FileUtils.makeQualified(nonLocalScratchPath, conf);
        URI uri = dir.toUri();

        Path newScratchDir = getScratchDir(uri.getScheme(), uri.getAuthority(), !isExplainSkipExecution(),
                uri.getPath());
        LOG.info("New scratch dir is " + newScratchDir);
        return newScratchDir;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(
                "Error while making MR scratch " + "directory - check filesystem config (" + e.getCause() + ")",
                e);
    }
}

From source file:ru.tehkode.permissions.backends.hybrid.HybridBackend.java

private void sqlBackend(PermissionManager manager, ConfigurationSection config)
        throws PermissionBackendException {
    final String dbUri = getConfig().getString("uri", "");
    final String dbUser = getConfig().getString("user", "");
    final String dbPassword = getConfig().getString("password", "");

    if (dbUri == null || dbUri.isEmpty()) {
        getConfig().set("uri", "mysql://localhost/exampledb");
        getConfig().set("user", "databaseuser");
        getConfig().set("password", "databasepassword");
        manager.getConfiguration().save();
        throw new PermissionBackendException("SQL connection is not configured, see config.yml");
    }/*from w  w  w .  j a v  a 2 s .co m*/
    dbDriver = dbUri.split(":", 2)[0];

    this.ds = new BasicDataSource();
    String driverClass = getDriverClass(dbDriver);
    if (driverClass != null) {
        this.ds.setDriverClassName(driverClass);
    }
    this.ds.setUrl("jdbc:" + dbUri);
    this.ds.setUsername(dbUser);
    this.ds.setPassword(dbPassword);
    // https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
    this.ds.setMaxActive((Runtime.getRuntime().availableProcessors() * 2) + 1);
    this.ds.setMaxWait(200); // 4 ticks
    this.ds.setValidationQuery("SELECT 1 AS dbcp_validate");
    this.ds.setTestOnBorrow(true);

    InputStream queryLocation = getClass().getResourceAsStream("/sql/" + dbDriver + "/queries.properties");
    if (queryLocation != null) {
        try {
            this.queryCache = new SQLQueryCache(queryLocation, DEFAULT_QUERY_CACHE);
        } catch (IOException e) {
            throw new PermissionBackendException("Unable to access database-specific queries", e);
        }
    } else {
        this.queryCache = DEFAULT_QUERY_CACHE;
    }
    try (SQLConnection conn = getSQL()) {
        conn.checkConnection();
    } catch (Exception e) {
        if (e.getCause() != null && e.getCause() instanceof Exception) {
            e = (Exception) e.getCause();
        }
        throw new PermissionBackendException("Unable to connect to SQL database", e);
    }

    getManager().getLogger().info("Successfully connected to SQL database");

    addSchemaUpdate(new SchemaUpdate(2) {
        @Override
        public void performUpdate() throws PermissionBackendException {
            // Change encoding for all columns to utf8mb4
            // Change collation for all columns to utf8mb4_general_ci
            try (SQLConnection conn = getSQL()) {
                conn.prep(
                        "ALTER TABLE `{permissions}` DROP KEY `unique`, MODIFY COLUMN `permission` TEXT NOT NULL")
                        .execute();
            } catch (SQLException | IOException e) {
                throw new PermissionBackendException(e);
            }
        }
    });
    addSchemaUpdate(new SchemaUpdate(1) {
        @Override
        public void performUpdate() throws PermissionBackendException {
            try (SQLConnection conn = getSQL()) {
                PreparedStatement updateStmt = conn.prep("entity.options.add");
                ResultSet res = conn
                        .prepAndBind("SELECT `name`, `type` FROM `{permissions_entity}` WHERE `default`='1'")
                        .executeQuery();
                while (res.next()) {
                    conn.bind(updateStmt, res.getString("name"), res.getInt("type"), "default", "", "true");
                    updateStmt.addBatch();
                }
                updateStmt.executeBatch();

                // Update tables
                conn.prep("ALTER TABLE `{permissions_entity}` DROP COLUMN `default`").execute();
            } catch (SQLException | IOException e) {
                throw new PermissionBackendException(e);
            }
        }
    });
    addSchemaUpdate(new SchemaUpdate(0) {
        @Override
        public void performUpdate() throws PermissionBackendException {
            try (SQLConnection conn = getSQL()) {
                // TODO: Table modifications not supported in SQLite
                // Prefix/sufix -> options
                PreparedStatement updateStmt = conn.prep("entity.options.add");
                ResultSet res = conn.prepAndBind(
                        "SELECT `name`, `type`, `prefix`, `suffix` FROM `{permissions_entity}` WHERE LENGTH(`prefix`)>0 OR LENGTH(`suffix`)>0")
                        .executeQuery();
                while (res.next()) {
                    String prefix = res.getString("prefix");
                    if (!prefix.isEmpty() && !prefix.equals("null")) {
                        conn.bind(updateStmt, res.getString("name"), res.getInt("type"), "prefix", "", prefix);
                        updateStmt.addBatch();
                    }
                    String suffix = res.getString("suffix");
                    if (!suffix.isEmpty() && !suffix.equals("null")) {
                        conn.bind(updateStmt, res.getString("name"), res.getInt("type"), "suffix", "", suffix);
                        updateStmt.addBatch();
                    }
                }
                updateStmt.executeBatch();

                // Data type corrections

                // Update tables
                conn.prep("ALTER TABLE `{permissions_entity}` DROP KEY `name`").execute();
                conn.prep("ALTER TABLE `{permissions_entity}` DROP COLUMN `prefix`, DROP COLUMN `suffix`")
                        .execute();
                conn.prep(
                        "ALTER TABLE `{permissions_entity}` ADD CONSTRAINT UNIQUE KEY `name` (`name`, `type`)")
                        .execute();

                conn.prep("ALTER TABLE `{permissions}` DROP KEY `unique`").execute();
                conn.prep(
                        "ALTER TABLE `{permissions}` ADD CONSTRAINT UNIQUE `unique` (`name`,`permission`,`world`,`type`)")
                        .execute();
            } catch (SQLException | IOException e) {
                throw new PermissionBackendException(e);
            }
        }
    });
    this.setupAliases();
    this.deployTables();
    performSchemaUpdate();

    try (SQLConnection conn = getSQL()) {
        conn.prep("ALTER TABLE `{permissions}` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci")
                .execute();
        conn.prep(
                "ALTER TABLE `{permissions_entity}` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci")
                .execute();
        conn.prep(
                "ALTER TABLE `{permissions_inheritance}` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci")
                .execute();
    } catch (SQLException | IOException e) {
        // Ignore, this MySQL version just doesn't support it.
    }
}

From source file:com.ning.billing.recurly.RecurlyClient.java

private <T> T callRecurlySafe(final AsyncHttpClient.BoundRequestBuilder builder,
        @Nullable final Class<T> clazz) {
    try {/*  w  w  w . j  a v a  2  s. c  om*/
        return callRecurly(builder, clazz);
    } catch (IOException e) {
        log.warn("Error while calling Recurly", e);
        return null;
    } catch (ExecutionException e) {
        // Extract the errors exception, if any
        if (e.getCause() != null && e.getCause().getCause() != null
                && e.getCause().getCause() instanceof TransactionErrorException) {
            throw (TransactionErrorException) e.getCause().getCause();
        } else if (e.getCause() != null && e.getCause() instanceof TransactionErrorException) {
            // See https://github.com/killbilling/recurly-java-library/issues/16
            throw (TransactionErrorException) e.getCause();
        }
        log.error("Execution error", e);
        return null;
    } catch (InterruptedException e) {
        log.error("Interrupted while calling Recurly", e);
        return null;
    }
}

From source file:com.diversityarrays.update.UpdateDialog.java

private void checkForUpdates(PrintStream ps) {

    StringBuilder sb = new StringBuilder(updateCheckRequest.updateBaseUrl);
    sb.append(updateCheckRequest.versionCode);
    if (RunMode.getRunMode().isDeveloper()) {
        sb.append("-dev"); //$NON-NLS-1$
    }/*from  w  ww .  j a  v  a  2  s .c o m*/
    sb.append(".json"); //$NON-NLS-1$

    final String updateUrl;
    updateUrl = sb.toString();
    // updateUrl = "NONEXISTENT"; // Uncomment to check error

    final ProgressMonitor progressMonitor = new ProgressMonitor(updateCheckRequest.owner,
            Msg.PROGRESS_CHECKING(), null, 0, 0);

    worker = new SwingWorker<String, Void>() {

        @Override
        protected String doInBackground() throws Exception {

            // Thread.sleep(3000); // Uncomment to check delay

            BufferedReader reader = null;
            StringBuffer buffer = new StringBuffer();

            try {
                URL url = new URL(updateUrl);
                reader = new BufferedReader(new InputStreamReader(url.openStream()));
                int read;
                char[] chars = new char[1024];
                while ((read = reader.read(chars)) != -1) {
                    if (progressMonitor.isCanceled()) {
                        cancel(true);
                        return null;
                    }
                    buffer.append(chars, 0, read);
                }
            } catch (IOException e) {
                System.err.println("checkForUpdates: " + e.getMessage()); //$NON-NLS-1$
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }

            return buffer.toString();
        }

        @Override
        protected void done() {
            try {
                String json = get();
                Gson gson = new Gson();
                setKDXploreUpdate(gson.fromJson(json, KDXploreUpdate.class));
            } catch (CancellationException ignore) {
            } catch (InterruptedException ignore) {
            } catch (ExecutionException e) {
                Throwable cause = e.getCause();

                if (cause instanceof UnknownHostException) {
                    String site = extractSite(updateUrl);
                    ps.println(Msg.ERRMSG_UNABLE_TO_CONTACT_UPDATE_SITE(site));
                } else {
                    cause.printStackTrace(ps);
                }

                if (cause instanceof FileNotFoundException) {
                    FileNotFoundException fnf = (FileNotFoundException) cause;
                    if (updateUrl.equals(fnf.getMessage())) {
                        // Well maybe someone forgot to create the file on
                        // the server!
                        System.err.println("Maybe someone forgot to create the file!"); //$NON-NLS-1$
                        System.err.println(fnf.getMessage());

                        setKDXploreUpdate(new KDXploreUpdate(Msg.ERRMSG_PROBLEMS_CONTACTING_UPDATE_SERVER_1()));
                        return;
                    }
                }

                String msg = Msg.HTML_PROBLEMS_CONTACTING_UPDATE_2(StringUtil.htmlEscape(updateUrl),
                        cause.getClass().getSimpleName(), StringUtil.htmlEscape(cause.getMessage()));
                kdxploreUpdate = new KDXploreUpdate(msg);

                kdxploreUpdate.unknownHost = (cause instanceof UnknownHostException);
                return;
            }
        }

        private String extractSite(final String updateUrl) {
            String site = null;
            int spos = updateUrl.indexOf("://");
            if (spos > 0) {
                int epos = updateUrl.indexOf('/', spos + 1);
                if (epos > 0) {
                    site = updateUrl.substring(0, epos);
                }
            }
            if (site == null) {
                site = updateUrl;
            }
            return site;
        }
    };

    Closure<JDialog> onComplete = new Closure<JDialog>() {
        @Override
        public void execute(JDialog d) {
            if (!processReadUrlResult(updateUrl)) {
                d.dispose();
            } else {
                d.setVisible(true);
            }
        }
    };

    SwingWorkerCompletionWaiter waiter = new SwingWorkerCompletionWaiter(this, onComplete);
    worker.addPropertyChangeListener(waiter);

    worker.execute();
}

From source file:org.wisdom.error.DefaultPageErrorHandler.java

/**
 * The interception method. When the request is unbound, generate a 404 page. When the controller throws an
 * exception generates a 500 page./* w w w .  j  a  v a 2s .c  om*/
 *
 * @param route   the route
 * @param context the filter context
 * @return the generated result.
 * @throws Exception if anything bad happen
 */
@Override
public Result call(Route route, RequestContext context) throws Exception {

    // Manage the error file.
    // In dev mode, if the watching pipeline throws an error, this error is stored in the error.json file
    // If this file exist, we should display a page telling the user that something terrible happened in his last
    // change.
    if (configuration.isDev() && context.request().accepts(MimeTypes.HTML) && pipeline != null) {
        // Check whether the error file is there
        File error = getFirstErrorFile();
        if (error != null) {
            logger().debug("Error file detected, preparing rendering");
            try {
                return renderPipelineError(error);
            } catch (IOException e) {
                LOGGER.error("An exception occurred while generating the error page for {} {}",
                        route.getHttpMethod(), route.getUrl(), e);
                return renderInternalError(context.context(), route, e);
            }
        }
    }

    try {
        Result result = context.proceed();
        if (result.getStatusCode() == NOT_FOUND && result.getRenderable() instanceof NoHttpBody) {
            // HEAD Implementation.
            if (route.getHttpMethod() == HttpMethod.HEAD) {
                return switchToGet(route, context);
            }
            return renderNotFound(route, result);
        }
        return result;
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        LOGGER.error("An exception occurred while processing request {} {}", route.getHttpMethod(),
                route.getUrl(), cause);
        // if it is and the cause is a HTTP Exception, return that one
        if (cause instanceof HttpException) {
            // If we catch a HTTP Exception, just return the built result.
            LOGGER.error("A HTTP exception occurred while processing request {} {}", route.getHttpMethod(),
                    route.getUrl(), e);
            return ((HttpException) cause).toResult();
        }

        // if we have a mapper for that exception, use it.
        for (ExceptionMapper mapper : mappers) {
            if (mapper.getExceptionClass().equals(cause.getClass())) {
                //We can safely cast here, as we have the previous class check;
                //noinspection unchecked
                return mapper.toResult((Exception) cause);
            }
        }
        return renderInternalError(context.context(), route, e);
    } catch (Exception e) {
        LOGGER.error("An exception occurred while processing request {} {}", route.getHttpMethod(),
                route.getUrl(), e);
        Throwable cause = e.getCause();
        // if we have a mapper for that exception, use it.
        for (ExceptionMapper mapper : mappers) {
            if (mapper.getExceptionClass().equals(cause.getClass())) {
                //We can safely cast here, as we have the previous class check;
                //noinspection unchecked
                return mapper.toResult((Exception) cause);
            }
        }

        // Used when it's not an invocation target exception, or when it is one but we don't have custom action
        // to handle it.
        return renderInternalError(context.context(), route, e);
    }
}

From source file:org.everrest.websockets.client.WSClient.java

/**
 * Connect to remote server./* w w w . j a  v a  2 s  .com*/
 *
 * @param timeout
 *         connection timeout value in seconds
 * @throws IOException
 *         if connection failed
 * @throws IllegalArgumentException
 *         if <code>timeout</code> zero or negative
 */
public synchronized void connect(long timeout) throws IOException {
    if (timeout < 1) {
        throw new IllegalArgumentException(String.format("Invalid timeout: %d", timeout));
    }

    if (connected) {
        throw new IOException("Already connected.");
    }

    try {
        executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    int port = target.getPort();
                    if (port == -1) {
                        port = 80;
                    }
                    socket = new Socket(target.getHost(), port);
                    in = socket.getInputStream();
                    out = socket.getOutputStream();
                    out.write(getHandshake());
                    validateResponseHeaders();
                    inputBuffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
                    connected = true;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).get(timeout, TimeUnit.SECONDS); // Wait for connection.
    } catch (InterruptedException e) {
        //
        throw new IOException(e.getMessage(), e);
    } catch (ExecutionException e) {
        // It is RuntimeException for sure.
        RuntimeException re = (RuntimeException) e.getCause();
        Throwable cause = re.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        throw re;
    } catch (TimeoutException e) {
        // Connection time out reached.
        throw new SocketTimeoutException("Connection timeout. ");
    } finally {
        if (!connected) {
            executor.shutdown();
        }
    }

    // Start reading from socket.
    executor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                read();
            } catch (ConnectionException e) {
                LOG.error(e.getMessage(), e);
                onClose(e.status, e.getMessage());
            } catch (Exception e) {
                // All unexpected errors represents as protocol error, status: 1002.
                LOG.error(e.getMessage(), e);
                onClose(1002, e.getMessage());
            }
        }
    });

    // Notify listeners about connection open.
    onOpen();
}

From source file:it.geosolutions.geobatch.actions.freemarker.FreeMarkerAction.java

private final File buildOutput(final File outputDir, final Map<String, Object> root) throws ActionException {
    // try to open the file to write into
    FileWriter fw = null;//  w  w  w.j  a  va 2s .  co m
    final File outputFile;
    try {
        final String outputFilePrefix = FilenameUtils.getBaseName(conf.getInput()) + "_";
        final String outputFileSuffix = "." + FilenameUtils.getExtension(conf.getInput());
        outputFile = File.createTempFile(outputFilePrefix, outputFileSuffix, outputDir);
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Output file name: " + outputFile);
        fw = new FileWriter(outputFile);
    } catch (IOException ioe) {
        IOUtils.closeQuietly(fw);
        final String message = "Unable to build the output file writer: " + ioe.getLocalizedMessage();
        if (LOGGER.isErrorEnabled())
            LOGGER.error(message);
        throw new ActionException(this, message);
    }

    /*
     * If available, process the output file using the TemplateModel data
     * structure
     */
    try {
        // process the input template file
        processor.process(processor.wrapRoot(root), fw);

        // flush the buffer
        if (fw != null)
            fw.flush();

    } catch (IOException ioe) {
        throw new ActionException(this,
                "Unable to flush buffer to the output file: " + ioe.getLocalizedMessage(), ioe.getCause());
    } catch (TemplateModelException tme) {
        throw new ActionException(this, "Unable to wrap the passed object: " + tme.getLocalizedMessage(),
                tme.getCause());
    } catch (Exception e) {
        throw new ActionException(this, "Unable to process the input file: " + e.getLocalizedMessage(),
                e.getCause());
    } finally {
        IOUtils.closeQuietly(fw);
    }
    return outputFile;
}