Example usage for java.io IOException getClass

List of usage examples for java.io IOException getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.facebook.stetho.inspector.ChromeDevtoolsServer.java

@Override
public void onMessage(SimpleSession session, String message) {
    if (LogRedirector.isLoggable(TAG, Log.VERBOSE)) {
        LogRedirector.v(TAG, "onMessage: message=" + message);
    }/*from  ww  w.  j  a  va  2s  . com*/
    try {
        JsonRpcPeer peer = mPeers.get(session);
        Util.throwIfNull(peer);

        handleRemoteMessage(peer, message);
    } catch (IOException e) {
        if (LogRedirector.isLoggable(TAG, Log.VERBOSE)) {
            LogRedirector.v(TAG, "Unexpected I/O exception processing message: " + e);
        }
        closeSafely(session, CloseCodes.UNEXPECTED_CONDITION, e.getClass().getSimpleName());
    } catch (MessageHandlingException e) {
        LogRedirector.i(TAG, "Message could not be processed by implementation: " + e);
        closeSafely(session, CloseCodes.UNEXPECTED_CONDITION, e.getClass().getSimpleName());
    } catch (JSONException e) {
        LogRedirector.v(TAG, "Unexpected JSON exception processing message", e);
        closeSafely(session, CloseCodes.UNEXPECTED_CONDITION, e.getClass().getSimpleName());
    }
}

From source file:photosharing.api.conx.RecommendationDefinition.java

/**
 * get nonce as described with nonce <a href="http://ibm.co/1fG83gY">Get a
 * Cryptographic Key</a>//from   w  w w .  j a va 2  s .  c  om
 * 
 * @param bearer
 */
private String getNonce(String bearer, HttpServletResponse response) {
    String nonce = "";

    // Build the Request
    Request get = Request.Get(getNonceUrl());
    get.addHeader("Authorization", "Bearer " + bearer);

    try {
        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(get);

        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes and if SC_OK (200), convert to String
         */
        int code = hr.getStatusLine().getStatusCode();

        // Session is no longer valid or access token is expired
        if (code == HttpStatus.SC_FORBIDDEN) {
            response.sendRedirect("./api/logout");
        }

        // User is not authorized
        else if (code == HttpStatus.SC_UNAUTHORIZED) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        else if (code == HttpStatus.SC_OK) {
            InputStream in = hr.getEntity().getContent();
            nonce = IOUtils.toString(in);
        } else {
            //Given a bad proxied request
            response.setStatus(HttpStatus.SC_BAD_GATEWAY);
        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("IOException " + e.toString());
    }

    return nonce;
}

From source file:com.iggroup.oss.restdoclet.plugin.mojo.RestDocumentationMojo.java

/**
 * {@inheritDoc}//from  ww w .j  a va 2  s . co m
 */
@Override
public void execute() throws MojoExecutionException {

    try {

        DocletUtils.initialiseLogging();

        if (MavenUtils.WAR_PACKAGING.equalsIgnoreCase(packaging)) {
            build();
        }
    } catch (final IOException e) {
        throw new MojoExecutionException(e.getClass().getName() + ": " + e.getMessage(), e);
    } catch (final JiBXException e) {
        throw new MojoExecutionException(e.getClass().getName() + ": " + e.getMessage(), e);
    } catch (final JavadocNotFoundException e) {
        throw new MojoExecutionException(e.getClass().getName() + ": " + e.getMessage(), e);
    } catch (final CloneNotSupportedException e) {
        throw new MojoExecutionException(e.getClass().getName() + ": " + e.getMessage(), e);
    } catch (final Exception e) {
        throw new MojoExecutionException(e.getClass().getName() + ": " + e.getMessage(), e);
    }

}

From source file:photosharing.api.conx.RecommendationDefinition.java

/**
 * unlike a file/*from  ww  w  .ja  v a 2 s . c  o m*/
 * 
 * Example URL
 * http://localhost:9080/photoSharing/api/like?r=off&lid=f8ad2a54
 * -4d20-4b3b-ba3f-834e0b0cf90b&uid=bec24e93-8165-431d-bf38-0c668a5e6727
 * maps to
 * https://apps.collabservdaily.swg.usma.ibm.com/files/basic/api/library/00c129c9-f3b6-4d22-9988-99e69d16d7a7/document/bf33a9b5-3042-46f0-a96e-b8742fced7a4/feed
         
 * 
 * @param bearer
 * @param lid
 * @param uid
 * @param nonce
 * @param response
 */
public void unlike(String bearer, String pid, String lid, String nonce, HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/library/" + lid + "/document/" + pid + "/feed";

    try {

        String recommendation = generateRecommendationContent();
        logger.info("like -> " + apiUrl + " " + recommendation);

        // Generate the
        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("X-METHOD-OVERRIDE", "DELETE");
        post.addHeader("Content-Type", "application/atom+xml");

        ByteArrayEntity entity = new ByteArrayEntity(recommendation.getBytes("UTF-8"));
        post.body(entity);

        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(post);
        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes
         */
        int code = hr.getStatusLine().getStatusCode();

        // Session is no longer valid or access token is expired
        if (code == HttpStatus.SC_FORBIDDEN) {
            response.sendRedirect("./api/logout");
        }

        // User is not authorized
        else if (code == HttpStatus.SC_UNAUTHORIZED) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        // Default to SC_NO_CONTENT (204)
        else {
            response.setStatus(HttpStatus.SC_NO_CONTENT);

        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("IOException " + e.toString());
    }
}

From source file:ch.njol.skript.Updater.java

/**
 * @param sender Sender to receive messages
 * @param download Whether to directly download the newest version if one is found
 * @param isAutomatic//  ww w . j  ava 2s  . c  o m
 */
static void check(final CommandSender sender, final boolean download, final boolean isAutomatic) {
    stateLock.writeLock().lock();
    try {
        if (state == UpdateState.CHECK_IN_PROGRESS || state == UpdateState.DOWNLOAD_IN_PROGRESS)
            return;
        state = UpdateState.CHECK_IN_PROGRESS;
    } finally {
        stateLock.writeLock().unlock();
    }
    if (!isAutomatic || Skript.logNormal())
        Skript.info(sender, "" + m_checking);
    Skript.newThread(new Runnable() {
        @Override
        public void run() {
            infos.clear();

            InputStream in = null;
            try {
                final URLConnection conn = new URL(filesURL).openConnection();
                conn.setRequestProperty("User-Agent", "Skript/v" + Skript.getVersion() + " (by Njol)");
                in = conn.getInputStream();
                final BufferedReader reader = new BufferedReader(new InputStreamReader(in,
                        conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding()));
                try {
                    final String line = reader.readLine();
                    if (line != null) {
                        final JSONArray a = (JSONArray) JSONValue.parse(line);
                        for (final Object o : a) {
                            final Object name = ((JSONObject) o).get("name");
                            if (!(name instanceof String)
                                    || !((String) name).matches("\\d+\\.\\d+(\\.\\d+)?( \\(jar( only)?\\))?"))// not the default version pattern to not match beta/etc. versions
                                continue;
                            final Object url = ((JSONObject) o).get("downloadUrl");
                            if (!(url instanceof String))
                                continue;

                            final Version version = new Version(((String) name).contains(" ")
                                    ? "" + ((String) name).substring(0, ((String) name).indexOf(' '))
                                    : ((String) name));
                            if (version.compareTo(Skript.getVersion()) > 0) {
                                infos.add(new VersionInfo((String) name, version, (String) url));
                            }
                        }
                    }
                } finally {
                    reader.close();
                }

                if (!infos.isEmpty()) {
                    Collections.sort(infos);
                    latest.set(infos.get(0));
                } else {
                    latest.set(null);
                }

                getChangelogs(sender);

                final String message = infos.isEmpty()
                        ? (Skript.getVersion().isStable() ? "" + m_running_latest_version
                                : "" + m_running_latest_version_beta)
                        : "" + m_update_available;
                if (isAutomatic && !infos.isEmpty()) {
                    Skript.adminBroadcast(message);
                } else {
                    Skript.info(sender, message);
                }

                if (download && !infos.isEmpty()) {
                    stateLock.writeLock().lock();
                    try {
                        state = UpdateState.DOWNLOAD_IN_PROGRESS;
                    } finally {
                        stateLock.writeLock().unlock();
                    }
                    download_i(sender, isAutomatic);
                } else {
                    stateLock.writeLock().lock();
                    try {
                        state = UpdateState.CHECKED_FOR_UPDATE;
                    } finally {
                        stateLock.writeLock().unlock();
                    }
                }
            } catch (final IOException e) {
                stateLock.writeLock().lock();
                try {
                    state = UpdateState.CHECK_ERROR;
                    error.set(ExceptionUtils.toString(e));
                    if (sender != null)
                        Skript.error(sender, m_check_error.toString());
                } finally {
                    stateLock.writeLock().unlock();
                }
            } catch (final Exception e) {
                if (sender != null)
                    Skript.error(sender, m_internal_error.toString());
                Skript.exception(e, "Unexpected error while checking for a new version of Skript");
                stateLock.writeLock().lock();
                try {
                    state = UpdateState.CHECK_ERROR;
                    error.set(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage());
                } finally {
                    stateLock.writeLock().unlock();
                }
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (final IOException e) {
                    }
                }
            }
        }
    }, "Skript update thread").start();
}

From source file:fr.isen.browser5.Util.UrlLoader.java

public void parseResponse() {
    doc = null;/*ww w.  j a  v  a  2  s. com*/
    try {
        System.out.println("Response url: " + pageUrl);
        tabView.syncTabHistory(pageUrl.toString());
        tabView.removeAll();
        if (tabView.getCurrentFrame().getTabPane().getSelectedIndex() == tabView.getCurrentTabIndex()) {
            tabView.getCurrentFrame().setUrl(pageUrl.toString());
        }
        tabView.setUrl(pageUrl);
        checkHtmlCharset();
        tabView.setDoc(doc);
        setTabTitleFavicon();
        tabView.getCurrentScrollPane().getViewport().setBackground(Color.WHITE);
        tabView.getDevView().clear();
        elementVisitor = new ElementVisitor(tabView);
        doc.body().traverse(elementVisitor);
        getScripts();
        tabView.removeAll();
        movePanel();
        tabView.getDevView().load(tabView);
        tabView.getDevView().executeScripts(script);
        tabView.revalidate();
        tabView.repaint();
    } catch (IOException e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, e.getMessage(), e.getClass().getSimpleName(),
                JOptionPane.ERROR_MESSAGE);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.netflix.spinnaker.clouddriver.aws.security.AmazonClientInvocationHandler.java

private byte[] getJson(String objectName, String key) throws IOException {
    final String url = edda + "/REST/v2/aws/" + objectName + (key == null ? ";_expand" : "/" + key) + ";_meta";
    HttpGet get = new HttpGet(url);
    get.setConfig(RequestConfig.custom().setConnectTimeout(eddaTimeoutConfig.getConnectTimeout())
            .setSocketTimeout(eddaTimeoutConfig.getSocketTimeout()).build());

    long retryDelay = eddaTimeoutConfig.getRetryBase();
    int retryAttempts = 0;
    String lastException = "";
    Random r = new Random();
    Exception ex;//from   www.j  a  va 2 s  .  c  o  m
    while (retryAttempts < eddaTimeoutConfig.getMaxAttempts()) {
        ex = null;
        HttpEntity entity = null;
        try {
            HttpResponse response = httpClient.execute(get);
            entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                lastException = response.getProtocolVersion().toString() + " "
                        + response.getStatusLine().getStatusCode() + " "
                        + response.getStatusLine().getReasonPhrase();
            } else {
                return getBytesFromInputStream(entity.getContent(), entity.getContentLength());
            }
        } catch (IOException ioe) {
            lastException = ioe.getClass().getSimpleName() + ": " + ioe.getMessage();
            ex = ioe;
        } finally {
            EntityUtils.consume(entity);
        }
        final String exceptionFormat = "Edda request {} failed with {}";
        if (ex == null) {
            log.warn(exceptionFormat, url, lastException);
        } else {
            log.warn(exceptionFormat, url, lastException, ex);
        }
        try {
            Thread.sleep(retryDelay);
        } catch (InterruptedException inter) {
            break;
        }
        retryAttempts++;
        retryDelay += r.nextInt(eddaTimeoutConfig.getBackoffMillis());
    }
    throw new IOException(lastException);
}

From source file:photosharing.api.conx.RecommendationDefinition.java

/**
 * like a file//  w  ww  .  j  ava2  s.c o m
 * 
 * Example URL
 * http://localhost:9080/photoSharing/api/like?r=on&lid=f8ad2a54-
 * 4d20-4b3b-ba3f-834e0b0cf90b&uid=bec24e93-8165-431d-bf38-0c668a5e6727 maps
 * to
 * https://apps.collabservdaily.swg.usma.ibm.com/files/basic/api/library/00c129c9-f3b6-4d22-9988-99e69d16d7a7/document/bf33a9b5-3042-46f0-a96e-b8742fced7a4/feed
 * 
 * 
 * @param bearer
 * @param pid
 * @param lid
 * @param nonce
 * @param response
 */
public void like(String bearer, String pid, String lid, String nonce, HttpServletResponse response) {
    String apiUrl = getApiUrl() + "/library/" + lid + "/document/" + pid + "/feed";

    try {

        String recommendation = generateRecommendationContent();
        logger.info("like -> " + apiUrl + " " + recommendation);

        // Generate the apiUrl for like
        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("Content-Type", "application/atom+xml");

        ByteArrayEntity entity = new ByteArrayEntity(recommendation.getBytes("UTF-8"));
        post.body(entity);

        Executor exec = ExecutorUtil.getExecutor();
        Response apiResponse = exec.execute(post);
        HttpResponse hr = apiResponse.returnResponse();

        /**
         * Check the status codes
         */
        int code = hr.getStatusLine().getStatusCode();
        logger.info("code " + code);

        // Session is no longer valid or access token is expired
        if (code == HttpStatus.SC_FORBIDDEN) {
            response.sendRedirect("./api/logout");
        }

        // User is not authorized
        else if (code == HttpStatus.SC_UNAUTHORIZED) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }

        // Default to SC_NO_CONTENT (204)
        else {
            response.setStatus(HttpStatus.SC_NO_CONTENT);

        }

    } catch (IOException e) {
        response.setHeader("X-Application-Error", e.getClass().getName());
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        logger.severe("IOException " + e.toString());
        e.printStackTrace();
    }
}

From source file:org.zaproxy.zap.extension.websocket.client.ServerConnectionEstablisher.java

/**
 * Sends and receives the handshake and sets up a new WebSocket channel with method {@link
 * ServerConnectionEstablisher#setUpChannel}
 *
 * @param handshakeConfig Wrap the Http Handshake and the other available options
 * @return Either a new WebSocketProxy which is acts as a client or null if something went wrong
 *///from   w w w.  j a v  a 2 s.com
private WebSocketProxy handleSendMessage(HandshakeConfig handshakeConfig)
        throws RequestOutOfScopeException, IOException {

    // Reset the user before sending (e.g. Forced User mode sets the user, if needed).
    handshakeConfig.getHttpMessage().setRequestingUser(null);
    WebSocketProxy webSocketProxy;

    try {
        final ModeRedirectionValidator redirectionValidator = new ModeRedirectionValidator();
        if (handshakeConfig.isFollowRedirects()) {
            getDelegate(handshakeConfig).sendAndReceive(handshakeConfig.getHttpMessage(),
                    HttpRequestConfig.builder().setRedirectionValidator(redirectionValidator).build());
        } else {
            getDelegate(handshakeConfig).sendAndReceive(handshakeConfig.getHttpMessage(), false);
        }
        if (!handshakeConfig.getHttpMessage().getResponseHeader().isEmpty()) {
            if (!redirectionValidator.isRequestValid()) {
                throw new RequestOutOfScopeException(
                        Constant.messages.getString("manReq.outofscope.redirection.warning"),
                        redirectionValidator.getInvalidRedirection());
            }
        }
    } catch (final HttpMalformedHeaderException mhe) {
        throw new IllegalArgumentException("Malformed header error.", mhe);
    } catch (final UnknownHostException uhe) {
        throw new IOException("Error forwarding to an Unknown host: " + uhe.getMessage(), uhe);
    } catch (final SSLException sslEx) {
        throw sslEx;
    } catch (final IOException ioe) {
        throw new IOException("IO error in sending request: " + ioe.getClass() + ": " + ioe.getMessage(), ioe);
    }

    ZapGetMethod method = (ZapGetMethod) handshakeConfig.getHttpMessage().getUserObject();
    webSocketProxy = setUpChannel(handshakeConfig, method);

    return webSocketProxy;
}

From source file:com.fheebiy.http.lite.apache.DefaultHttpRequestRetryHandler.java

/**
 * Used <code>retryCount</code> and <code>requestSentRetryEnabled</code> to determine
 * if the given method should be retried.
 *//*from   w  w  w .j  a  v a 2 s. com*/
public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) {
    if (executionCount > this.retryCount) {
        // Do not retry if over max retry count
        return false;
    }
    if (this.nonRetriableClasses.contains(exception.getClass())) {
        return false;
    } else {
        for (final Class<? extends IOException> rejectException : this.nonRetriableClasses) {
            if (rejectException.isInstance(exception)) {
                return false;
            }
        }
    }
    return retryRequest(context);
}