Example usage for java.io IOException initCause

List of usage examples for java.io IOException initCause

Introduction

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

Prototype

public synchronized Throwable initCause(Throwable cause) 

Source Link

Document

Initializes the cause of this throwable to the specified value.

Usage

From source file:ch.cyberduck.core.gdocs.GDPath.java

@Override
public void delete() {
    try {/*from   w w  w .j a v a  2  s .  c  o  m*/
        if (this.attributes().isDuplicate()) {
            log.warn("Cannot delete revision " + this.attributes().getRevision());
            return;
        }
        this.getSession().check();
        this.getSession().message(
                MessageFormat.format(Locale.localizedString("Deleting {0}", "Status"), this.getName()));
        try {
            this.getSession().getClient().delete(new URL(this.getResourceFeed()),
                    this.attributes().getChecksum());
        } catch (ServiceException e) {
            IOException failure = new IOException(e.getMessage());
            failure.initCause(e);
            throw failure;
        } catch (MalformedURLException e) {
            IOException failure = new IOException(e.getMessage());
            failure.initCause(e);
            throw failure;
        }
        // The directory listing is no more current
        this.getParent().invalidate();
    } catch (IOException e) {
        this.error("Cannot delete {0}", e);
    }
}

From source file:ch.cyberduck.core.gdocs.GDPath.java

@Override
public void touch() {
    if (this.attributes().isFile()) {
        try {/*from  w w  w  . ja v a  2 s.  co  m*/
            this.getSession().check();
            this.getSession().message(
                    MessageFormat.format(Locale.localizedString("Uploading {0}", "Status"), this.getName()));

            DocumentListEntry file = new DocumentEntry();
            file.setTitle(new PlainTextConstruct(this.getName()));
            try {
                this.getSession().getClient().insert(new URL(((GDPath) this.getParent()).getFolderFeed()),
                        file);
            } catch (ServiceException e) {
                IOException failure = new IOException(e.getMessage());
                failure.initCause(e);
                throw failure;
            }
            // The directory listing is no more current
            this.getParent().invalidate();
        } catch (IOException e) {
            this.error("Cannot create file {0}", e);
        }
    }
}

From source file:ch.cyberduck.core.gdocs.GDPath.java

@Override
public void mkdir() {
    if (this.attributes().isDirectory()) {
        try {/*from w  w  w  .  j av a 2s  .c  o  m*/
            this.getSession().check();
            this.getSession().message(MessageFormat
                    .format(Locale.localizedString("Making directory {0}", "Status"), this.getName()));

            DocumentListEntry folder = new FolderEntry();
            folder.setTitle(new PlainTextConstruct(this.getName()));
            try {
                this.getSession().getClient().insert(new URL(((GDPath) this.getParent()).getFolderFeed()),
                        folder);
            } catch (ServiceException e) {
                IOException failure = new IOException(e.getMessage());
                failure.initCause(e);
                throw failure;
            }
            this.cache().put(this.getReference(), AttributedList.<Path>emptyList());
            // The directory listing is no more current
            this.getParent().invalidate();
        } catch (IOException e) {
            this.error("Cannot create folder {0}", e);
        }
    }
}

From source file:org.apache.hadoop.hbase.master.assignment.SplitTableRegionProcedure.java

/**
 * Check whether the region is splittable
 * @param env MasterProcedureEnv/*w w w.j  a  v a2s  .co m*/
 * @param regionToSplit parent Region to be split
 * @param splitRow if splitRow is not specified, will first try to get bestSplitRow from RS
 * @throws IOException
 */
private void checkSplittable(final MasterProcedureEnv env, final HRegionInfo regionToSplit,
        final byte[] splitRow) throws IOException {
    // Ask the remote RS if this region is splittable.
    // If we get an IOE, report it along w/ the failure so can see why we are not splittable at this time.
    if (regionToSplit.getReplicaId() != HRegionInfo.DEFAULT_REPLICA_ID) {
        throw new IllegalArgumentException("Can't invoke split on non-default regions directly");
    }
    RegionStateNode node = env.getAssignmentManager().getRegionStates().getRegionNode(getParentRegion());
    IOException splittableCheckIOE = null;
    boolean splittable = false;
    if (node != null) {
        try {
            if (bestSplitRow == null || bestSplitRow.length == 0) {
                LOG.info(
                        "splitKey isn't explicitly specified, " + " will try to find a best split key from RS");
            }
            // Always set bestSplitRow request as true here,
            // need to call Region#checkSplit to check it splittable or not
            GetRegionInfoResponse response = Util.getRegionInfoResponse(env, node.getRegionLocation(),
                    node.getRegionInfo(), true);
            if (bestSplitRow == null || bestSplitRow.length == 0) {
                bestSplitRow = response.hasBestSplitRow() ? response.getBestSplitRow().toByteArray() : null;
            }
            splittable = response.hasSplittable() && response.getSplittable();

            if (LOG.isDebugEnabled()) {
                LOG.debug("Splittable=" + splittable + " " + node.toShortString());
            }
        } catch (IOException e) {
            splittableCheckIOE = e;
        }
    }

    if (!splittable) {
        IOException e = new IOException(regionToSplit.getShortNameToLog() + " NOT splittable");
        if (splittableCheckIOE != null)
            e.initCause(splittableCheckIOE);
        throw e;
    }

    if (bestSplitRow == null || bestSplitRow.length == 0) {
        throw new DoNotRetryIOException("Region not splittable because bestSplitPoint = null");
    }

    if (Bytes.equals(regionToSplit.getStartKey(), bestSplitRow)) {
        throw new DoNotRetryIOException("Split row is equal to startkey: " + Bytes.toStringBinary(splitRow));
    }

    if (!regionToSplit.containsRow(bestSplitRow)) {
        throw new DoNotRetryIOException("Split row is not inside region key range splitKey:"
                + Bytes.toStringBinary(splitRow) + " region: " + regionToSplit);
    }
}

From source file:ch.cyberduck.core.gdocs.GDPath.java

@Override
public void rename(AbstractPath renamed) {
    try {//from   ww  w.j  a  va 2 s  .  c  o m
        this.getSession().check();
        this.getSession().message(MessageFormat.format(Locale.localizedString("Renaming {0} to {1}", "Status"),
                this.getName(), renamed));

        DocumentListEntry moved = new DocumentListEntry();
        moved.setId("https://docs.google.com/feeds/id/" + this.getResourceId());
        if (this.getParent().equals(renamed.getParent())) {
            // Rename file
            moved.setTitle(new PlainTextConstruct(renamed.getName()));
            try {
                // Move into new folder
                this.getSession().getClient().update(new URL(this.getResourceFeed()), moved,
                        this.attributes().getChecksum());
            } catch (ServiceException e) {
                IOException failure = new IOException(e.getMessage());
                failure.initCause(e);
                throw failure;
            } catch (MalformedURLException e) {
                IOException failure = new IOException(e.getMessage());
                failure.initCause(e);
                throw failure;
            }
        } else {
            try {
                // Move into new folder
                final DocumentListEntry update = this.getSession().getClient()
                        .insert(new URL(((GDPath) renamed.getParent()).getFolderFeed()), moved);
                // Move out of previous folder
                this.getSession().getClient().delete(
                        new URL((((GDPath) this.getParent()).getFolderFeed()) + "/" + this.getResourceId()),
                        update.getEtag());
            } catch (ServiceException e) {
                IOException failure = new IOException(e.getMessage());
                failure.initCause(e);
                throw failure;
            } catch (MalformedURLException e) {
                IOException failure = new IOException(e.getMessage());
                failure.initCause(e);
                throw failure;
            }
        }
        // The directory listing of the target is no more current
        renamed.getParent().invalidate();
        // The directory listing of the source is no more current
        this.getParent().invalidate();
    } catch (IOException e) {
        this.error("Cannot rename {0}", e);
    }
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.Hcap2Adapter.java

public ArcMoverFile createArcMoverFileObject(XMLStreamReader xmlr, ArcMoverDirectory caller)
        throws StorageAdapterException {
    ArcMoverFile retVal = null;//from www  . j  a va 2  s.  co  m
    try {
        ArcMoverDirectory rootDir = ArcMoverDirectory.getDirInstance(this.getProfile(), caller.getPath(), this);

        String fileName = xmlr.getAttributeValue(null, HttpGatewayConstants.FILE_NAME);
        try {
            // HCP sends incorrectly encoded filenames. Not all chars are encoded. Fix it.
            fileName = RFC2396Encoder.fixEncoding(fileName);
        } catch (UnsupportedEncodingException e) {
            throw new StorageAdapterException(e.getMessage(), e);
        }

        String fileTypeStr = xmlr.getAttributeValue(null, HttpGatewayConstants.FILE_TYPE);
        FileType fileType = FileType.FILE;
        if (fileTypeStr.equals(DIRECTORY)) {
            fileType = FileType.DIRECTORY;
        } else if (fileTypeStr.equals(SYMLINK)) {
            fileType = FileType.SYMLINK;
        }

        // The time provided by the cluster is in seconds since epoch. Java uses milliseconds
        // since epoch, so we must multiply by 1000
        String modifyTimeString = xmlr.getAttributeValue(null, HttpGatewayConstants.MD_DEFAULT_PARAM_MTIME);
        String accessTimeString = xmlr.getAttributeValue(null, HttpGatewayConstants.MD_DEFAULT_PARAM_ATIME);
        Date modifyTime = (modifyTimeString == null ? null : new Date(Long.parseLong(modifyTimeString) * 1000));
        Date accessTime = (accessTimeString == null ? null : new Date(Long.parseLong(accessTimeString) * 1000));

        long size = 0;
        int mode = 0;
        Long uid = Long.valueOf(0);
        Long gid = Long.valueOf(0);

        try {
            size = Long.parseLong(xmlr.getAttributeValue(null, HttpGatewayConstants.MD_PARAM_SIZE));
        } catch (NumberFormatException e) {
            // do nothing
        }
        try {
            mode = FileMetadata.covertHCAPToUNIX(
                    Integer.parseInt(xmlr.getAttributeValue(null, HttpGatewayConstants.MD_PARAM_PERMS)),
                    fileType);
        } catch (NumberFormatException e) {
            // do nothing
        }
        try {
            uid = UidGidUtil.validateId(xmlr.getAttributeValue(null, HttpGatewayConstants.MD_PARAM_PERMS_UID));
        } catch (NumberFormatException e) {
            // do nothing
        }
        try {
            gid = UidGidUtil.validateId(xmlr.getAttributeValue(null, HttpGatewayConstants.MD_PARAM_PERMS_GID));
        } catch (NumberFormatException e) {
            // do nothing
        }

        FileMetadata metadata = new FileMetadata(fileType, null, // creation time
                null, // ctime
                modifyTime, accessTime, size, fileName.startsWith("."), // hidden
                null, // file perms
                null, // directory perms
                uid, gid, null, // hcap version
                null, // dpl
                null, // hash scheme
                null, // hash value
                null, // shred
                null, // retention
                null, // retention hold
                null, // search index
                null, // replicated
                null, // acl
                null, // owner
                null); // custom metadata
        if (fileType.equals(FileType.DIRECTORY) && !fileName.equals(DOT)) {
            metadata.setDirMode(mode);
            retVal = ArcMoverDirectory.getDirInstance(rootDir, fileName, metadata, this);
        } else if (fileType.equals(FileType.FILE)) {
            metadata.setFileMode(mode);
            ArcMoverFile moverFile = ArcMoverFile.getFileInstance(getProfile(), rootDir, fileName, metadata);
            retVal = moverFile;
        } else if (FileType.SYMLINK == fileType) {
            retVal = ArcMoverSymlink.getSymlinkInstance(rootDir, fileName, null, this);
        }

    } catch (Exception e) {
        String msg = "Error parsing directory for: " + caller.getPath();
        LOG.log(Level.INFO, msg, e);
        IOException e2 = new IOException(msg);
        e2.initCause(e);
        throw new StorageAdapterException(e2.getMessage(), e2);
    }
    return retVal;
}

From source file:cn.isif.util_plus.http.SyncHttpHandler.java

public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {

    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {
        boolean retry = true;
        IOException exception = null;
        try {/*  ww  w  .  j  av  a  2 s  . co m*/
            requestUrl = request.getURI().toString();
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseStream(result);
                }
            }

            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}

From source file:org.openanzo.servlet.EncryptedTokenAuthenticator.java

/**
 * Perform form authentication. Called from SecurityHandler.
 * // w w  w  . j  av a  2s  .  co  m
 * @param servletRequest
 *            request to authenticate
 * @param response
 *            response to send response data
 * 
 * @return UserPrincipal if authenticated else null.
 * @throws IOException
 */
@SuppressWarnings("null")
public boolean authenticate(HttpServletRequest servletRequest, HttpServletResponse response)
        throws IOException {
    // NOTE: Jetty will sometimes call this method with a null response parameter. In particular, from
    // the org.eclipse.jetty.Request#getUserPrincipal() method.
    boolean ret = false;
    Request request = Request.getRequest(servletRequest);
    String uri = request.getServletPath();
    boolean protectedPath = false;
    for (PathSpec spec : protectedPathSpec) {
        if (spec.matches(uri)) {
            protectedPath = true;
            break;
        }
    }
    // Setup some defaults. Unfortunately, this is the only place we really get to set these up since the
    // Authenticator interface doesn't have an 'init'-like method.
    if (tokenTimeout <= 0) {
        tokenTimeout = 30 * DateUtils.MILLIS_PER_MINUTE;
    }
    if (tokenRefreshWindow <= 0) {
        tokenRefreshWindow = 5 * DateUtils.MILLIS_PER_MINUTE;
    }
    if (customTokenRefresh == null) {
        customTokenRefresh = Boolean.FALSE;
    }

    // Now handle the request
    uri = request.getPathInfo();
    if (uri.endsWith(LOGIN_URI_SUFFIX)) {
        // Handle a request for authentication.

        ret = false; // We will entirely handle the request here so return false to stop processing the request.

        String username = request.getParameter(USERNAME_PARAMETER_NAME);
        String password = request.getParameter(PASSWORD_PARAMETER_NAME);

        if (username == null || password == null) {
            log.error(LogUtils.SECURITY_MARKER,
                    "Invalid anzo_authenticate request url:{} username:{} password:{}",
                    new Object[] { uri, username, password == null ? null : "XXXObscuredNonNullPasswordXXX" });
        }

        AnzoPrincipal userPrincipal = null;
        try {
            userPrincipal = realm.authenticate(username, password, request);
        } catch (Exception e) {
            // No matter what sort of failure occurs in the realm we want to make sure to send the  appropriate
            // error response or redirect. So we can't all exceptions here.
            log.debug(LogUtils.SECURITY_MARKER, "Failed authentication call to the realm.", e);
        }
        if (userPrincipal == null) {
            if (log.isDebugEnabled()) {
                log.debug(LogUtils.SECURITY_MARKER, "Authentication request FAILED for {}",
                        StringUtil.printable(username));
            }
            request.setAuthentication(null);

            if (response != null) {
                if (_formErrorPage == null || isRequestSentByXmlHttpRequest(request)) {
                    if (log.isDebugEnabled()) {
                        log.debug(LogUtils.SECURITY_MARKER,
                                "Sending 403 Forbidden error due to invalid credentials for user {}", username);
                    }
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } else {
                    String redirectPath = response
                            .encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage));
                    log.debug(LogUtils.SECURITY_MARKER, "Sending redirect to form error page {}", redirectPath);
                    response.setContentLength(0);
                    response.sendRedirect(redirectPath);
                }
            }
        } else {
            // Authenticated OK
            if (log.isDebugEnabled()) {
                log.debug(LogUtils.SECURITY_MARKER, "Authentication request OK for {}",
                        StringUtil.printable(username));
            }
            request.setAuthentication(new BasicUserAuthorization(userPrincipal, AUTH_METHOD));

            // Set the encrypted token
            if (response != null) {
                try {
                    String token = createEncryptedToken(username, request.getRemoteAddr());
                    Cookie tokenCookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, token);
                    tokenCookie.setPath("/");
                    response.addCookie(tokenCookie);
                    if (isRequestSentByXmlHttpRequest(request)) {
                        // XMLHttpRequests just want a response with the cookie, no fancy redirects or anything like that.
                        // just send back 200 in text.(Need to send back something else firefox reports an error)
                        response.setStatus(HttpServletResponse.SC_OK);
                        response.setContentType("text/plain");
                        PrintWriter out = response.getWriter();
                        out.print(HttpServletResponse.SC_OK);
                        out.flush();
                        out.close();
                    } else {
                        // Redirect to the URL to user wanted to get to initially, or "/" if there isn't any such URL.
                        // We get the URL from a query parameter in the HTTP Referer (sic) header.
                        String referer = request.getHeader(HttpHeaders.REFERER);
                        String redirectPath = null;
                        if (referer != null) {
                            HttpURI refererUri = new HttpURI(referer);
                            MultiMap<String> queryParams = new MultiMap<String>();
                            refererUri.decodeQueryTo(queryParams, null);
                            String desiredUrl = (String) queryParams.getValue(ANZO_URL_QUERY_PARAM, 0);
                            if (desiredUrl != null) {
                                redirectPath = desiredUrl;
                            }
                        }
                        if (redirectPath == null) {
                            redirectPath = URIUtil.addPaths(request.getContextPath(), "/");
                        }
                        redirectPath = response.encodeRedirectURL(redirectPath);
                        log.debug(LogUtils.SECURITY_MARKER,
                                "Sending redirect to root {} after successful login request.", redirectPath);
                        response.sendRedirect(redirectPath);
                    }

                } catch (AnzoException cause) {
                    IOException ex = new IOException("Error creating encrypted authentication token.");
                    ex.initCause(cause);
                    throw ex;
                }
            }
        }

    } else if (isLoginOrErrorPage(uri)) {
        // Don't authenticate authform or errorpage. Just let the system them out.
        ret = true;
    } else if (protectedPath) {
        // This is a regular request for a protected resource, so check whether there is a valid
        // encrypted token in the request.
        AnzoPrincipal userPrincipal = null;

        // Parse and validate the authentication token from the cookie
        Token token = null;
        long currentTime = System.currentTimeMillis();
        Cookie[] cookies = request.getCookies();
        Cookie tokenCookie = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                if (ANZO_TOKEN_COOKIE_NAME.equals(cookieName)) {
                    tokenCookie = cookie;
                    try {
                        token = parseAnzoToken(cookie.getValue());
                        userPrincipal = validateAuthToken(token, realm, request.getRemoteAddr(), currentTime);
                    } catch (AnzoException e) {
                        log.debug(LogUtils.SECURITY_MARKER,
                                "Error decrypting and parsing authentication token.", e);
                    }
                    break;
                }
            }
        }

        if (userPrincipal == null) {
            // Invalid, expired, or non-existent token
            ret = false; // Don't serve the resource

            if (log.isDebugEnabled()) {
                String msg = "Auth token ";
                if (tokenCookie == null) {
                    msg += "MISSING";
                } else {
                    msg += "INVALID";
                }
                log.debug(LogUtils.SECURITY_MARKER, msg + " for URL: {}",
                        StringUtil.printable(request.getRequestURI()));
            }
            if (response != null) {
                Cookie cookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, "");
                cookie.setPath("/");
                cookie.setMaxAge(0);
                response.addCookie(cookie); // adding a cookie with MaxAge=0 tells the client to delete the cookie.
                if (_formLoginPage == null || isRequestSentByXmlHttpRequest(request)) {
                    if (log.isDebugEnabled()) {
                        log.debug(LogUtils.SECURITY_MARKER,
                                "Sending 403 Forbidden error due to invalid auth token. Token: {}", token);
                    }
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } else {
                    // We save the URL the user tried to access into a query parameter in the redirect to the login page.
                    // That way the login page can send the user to the page they wanted after they finish logging in.
                    // First we must reconstruct the URL the user accessed.
                    String requestUrl = uri;
                    if (request.getQueryString() != null) {
                        requestUrl += "?" + request.getQueryString();
                    }
                    requestUrl = request.getScheme() + "://" + request.getServerName() + ":"
                            + request.getServerPort() + URIUtil.addPaths(request.getContextPath(), requestUrl);
                    // Now we add the requested URL as a query parameter to the login URL
                    MultiMap<String> loginPageUrlQueryParams = new MultiMap<String>();
                    loginPageUrlQueryParams.put(ANZO_URL_QUERY_PARAM, requestUrl);
                    String loginPageUrl = URIUtil.addPaths(request.getContextPath(), _formLoginPage);
                    try {
                        loginPageUrl = addQueryParametersToURI(loginPageUrl, loginPageUrlQueryParams);
                    } catch (URISyntaxException e) {
                        log.warn(LogUtils.SECURITY_MARKER,
                                "Error creating login redirect URL. The user's attempted URL won't be saved for use after login.",
                                e);
                    }
                    String redirectPath = response.encodeRedirectURL(loginPageUrl);
                    log.debug(LogUtils.SECURITY_MARKER,
                            "Sending redirect to form login page {} after request without adequate credentials.",
                            redirectPath);
                    response.setContentLength(0);
                    response.sendRedirect(redirectPath);
                }
            }
        } else {
            // Properly authenticated
            if (log.isDebugEnabled()) {
                log.debug(LogUtils.SECURITY_MARKER, "Auth token OK for '{}' for URL:{}",
                        StringUtil.printable(userPrincipal.getName()),
                        StringUtil.printable(request.getRequestURI()));
            }
            if (userPrincipal instanceof AnzoPrincipal) {
                request.setAttribute(SerializationConstants.authenticationURI, (userPrincipal).getUserURI());
            }
            request.setAttribute(SerializationConstants.userPrincipal, userPrincipal);
            request.setAuthentication(new BasicUserAuthorization(userPrincipal, AUTH_METHOD));
            ret = true;

            // Check if the token is older than the refresh window. If so, create a new cookie with an updated timestamp.
            try {
                if (currentTime < token.getTimestamp()
                        || (currentTime - token.getTimestamp() >= tokenRefreshWindow)) { // if current time is less than the token's time, we'll issue a new cookie. That should only ever happen upon overflow of the number of milliseconds from the epoch.
                    String cookieval = createEncryptedToken(token.getUsername(), token.getRemoteAddress());
                    Cookie newTokenCookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, cookieval);
                    newTokenCookie.setPath("/");
                    if (customTokenRefresh) {
                        request.setAttribute(ANZO_REFRESH_COOKIE_ATTRIBUTE, newTokenCookie);
                    } else {
                        response.addCookie(newTokenCookie);
                    }
                }
            } catch (AnzoException e) {
                log.error(LogUtils.SECURITY_MARKER,
                        "Could NOT update timestamp on authentication token. Authentication session may end prematurely.",
                        e);
            }
        }
    } else {
        // This is NOT a protected resource so just let it be served.
        ret = true;
    }

    log.debug(LogUtils.SECURITY_MARKER, "Returning from 'authenticate' with {} for path {}", ret, uri);
    return ret;
}

From source file:com.youzu.android.framework.http.SyncHttpHandler.java

public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {

    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {
        boolean retry = true;
        IOException exception = null;
        try {// w  w  w . j av a  2 s .  c  o  m
            requestUrl = request.toString();
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl + request.toString());
                if (result != null) {
                    return new ResponseStream(result);
                }
            }

            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}

From source file:com.dongfang.net.http.SyncHttpHandler.java

public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {

    boolean retry = true;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        IOException exception = null;
        try {//from w w  w.  ja  v a  2 s .  c om
            // ??
            // requestUrl = request.getURI().toString();
            // if (request.getMethod().equals(HttpRequest.HttpMethod.GET.toString())) {
            // String result = HttpUtils.sHttpGetCache.get(requestUrl);
            // if (result != null) {
            // return new ResponseStream(result);
            // }
            // }

            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        }
        if (!retry && exception != null) {
            throw new HttpException(exception);
        }
    }
    return null;
}