Example usage for org.apache.http.client HttpResponseException HttpResponseException

List of usage examples for org.apache.http.client HttpResponseException HttpResponseException

Introduction

In this page you can find the example usage for org.apache.http.client HttpResponseException HttpResponseException.

Prototype

public HttpResponseException(final int statusCode, final String s) 

Source Link

Usage

From source file:com.fly1tkg.streamfileupload.FileUploadFacade.java

protected void upload(HttpUriRequest request, FileUploadCallback callback) {
    int statusCode = -1;
    String responseBody = null;/*from w  w w  . jav  a2 s  .  c  o m*/
    try {
        HttpResponse httpResponse = mHttpClient.execute(request);
        StatusLine status = httpResponse.getStatusLine();
        statusCode = status.getStatusCode();
        responseBody = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

        if (statusCode >= 300) {
            throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
        }

        sendSuccess(callback, statusCode, responseBody);
    } catch (HttpResponseException e) {
        sendFailure(callback, statusCode, responseBody, e);
    } catch (IOException e) {
        sendFailure(callback, statusCode, responseBody, e);
    }
}

From source file:com.mike.aframe.http.HttpCallBack.java

void sendResponseMessage(String uri, HttpConfig config, HttpResponse response) {
    StatusLine status = response.getStatusLine();
    String responseBody = null;/*from  ww  w.  j ava  2s . c  o  m*/
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
            responseBody = EntityUtils.toString(entity, "UTF-8");
        }
    } catch (IOException e) {
        sendFailureMessage(e, (String) null);
    }
    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                responseBody);
    } else {
        if (config.isUseCache()) {
            config.getCacher().add(uri, responseBody);
        }
        sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
    }
}

From source file:com.esri.geoportal.geoportal.commons.geometry.GeometryService.java

/**
 * Calls the projection service with the given parameters
 * //from  w w w.  j a v  a2s.co  m
 * @param params the parameters for the projection call
 * 
 * @return the reprojected points
 */
private MultiPoint callProjectService(HashMap<String, String> params) throws IOException, URISyntaxException {
    HttpPost request = new HttpPost(createProjectUrl().toURI());

    HttpEntity entrity = new UrlEncodedFormEntity(params.entrySet().stream()
            .map(e -> new BasicNameValuePair(e.getKey(), e.getValue())).collect(Collectors.toList()), "UTF-8");
    request.setEntity(entrity);

    try (CloseableHttpResponse httpResponse = httpClient.execute(request);
            InputStream contentStream = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }
        MultiPointGeometry geom = mapper.readValue(contentStream, MultiPointGeometry.class);
        MultiPoint result = new MultiPoint();
        geom.geometries[0].points.forEach(pt -> result.add(pt[0], pt[1]));
        return result;
    }
}

From source file:com.ab.http.BinaryHttpResponseHandler.java

/**
 * ??TODO//from w  w w  .  j  av a  2 s.  co  m
 * @see com.ab.http.AsyncHttpResponseHandler#sendResponseMessage(org.apache.http.HttpResponse)
 * @author: zhaoqp
 * @date2013-10-22 ?4:23:15
 * @version v1.0
 */
@Override
protected void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(
                status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : mAllowedContentTypes) {
        if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
            foundAllowedContentType = true;
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null,
                new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}

From source file:ch.cyberduck.core.googledrive.DriveReadFeature.java

@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback)
        throws BackgroundException {
    try {/*w w  w .j  a  v a 2s . co  m*/
        if (file.getType().contains(Path.Type.placeholder)) {
            final DescriptiveUrl link = new DriveUrlProvider().toUrl(file).find(DescriptiveUrl.Type.http);
            if (DescriptiveUrl.EMPTY.equals(link)) {
                log.warn(String.format("Missing web link for file %s", file));
                return new NullInputStream(file.attributes().getSize());
            }
            // Write web link file
            return IOUtils.toInputStream(UrlFileWriterFactory.get().write(link), Charset.defaultCharset());
        } else {
            final String base = session.getClient().getRootUrl();
            final HttpUriRequest request = new HttpGet(String.format(
                    String.format("%%s/drive/v3/files/%%s?alt=media&supportsTeamDrives=%s",
                            PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")),
                    base,
                    new DriveFileidProvider(session).getFileid(file, new DisabledListProgressListener())));
            request.addHeader(HTTP.CONTENT_TYPE, MEDIA_TYPE);
            if (status.isAppend()) {
                final HttpRange range = HttpRange.withStatus(status);
                final String header;
                if (-1 == range.getEnd()) {
                    header = String.format("bytes=%d-", range.getStart());
                } else {
                    header = String.format("bytes=%d-%d", range.getStart(), range.getEnd());
                }
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Add range header %s for file %s", header, file));
                }
                request.addHeader(new BasicHeader(HttpHeaders.RANGE, header));
                // Disable compression
                request.addHeader(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "identity"));
            }
            final HttpClient client = session.getHttpClient();
            final HttpResponse response = client.execute(request);
            switch (response.getStatusLine().getStatusCode()) {
            case HttpStatus.SC_OK:
            case HttpStatus.SC_PARTIAL_CONTENT:
                return new HttpMethodReleaseInputStream(response);
            default:
                throw new DriveExceptionMappingService().map(new HttpResponseException(
                        response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
            }
        }
    } catch (IOException e) {
        throw new DriveExceptionMappingService().map("Download {0} failed", e, file);
    }
}

From source file:org.opentestsystem.shared.permissions.security.RolesAndPermissionsServiceImpl.java

public ReturnStatus<List<Role>> getRoles(String roleName, String componentName, String permissionName)
        throws PermissionsRetrievalException, HttpResponseException {
    List<Role> roles;
    if (!StringUtils.isEmpty(componentName)) {
        //if the component does not exist
        if (getPersister().getComponentByComponentName(componentName) == null) {
            throw (new HttpResponseException(404,
                    String.format("Role by component:'%s' is not found.", componentName)));
        }/*  w  w w.j a v a 2s .  c om*/
        if (!StringUtils.isEmpty(permissionName)) {
            // We are going to return roles by component name and
            // permission.
            roles = getPersister().getRoleByComponentandPermission(componentName, permissionName);
        } else {
            // just by component name
            roles = getPersister().getRoleByComponent(componentName);
        }
    } else if (!StringUtils.isEmpty(roleName)) {
        // we have been passed a role name.
        roles = new ArrayList<Role>();
        Role role = getPersister().getRoleByRoleName(roleName);
        if (role == null) {
            throw (new HttpResponseException(404, String.format("Role:'%s' is not found.", roleName)));
        }
        roles.add(role);
    } else {
        // no parameters have been passed. return all roles.
        roles = new ArrayList<Role>();
        roles.addAll(getPersister().getAllRoles());
    }
    ReturnStatus<List<Role>> status = new ReturnStatus<List<Role>>(StatusEnum.SUCCESS, null);
    status.setValue(roles);
    return status;
}

From source file:com.liferay.sync.engine.document.library.handler.BaseJSONHandler.java

@Override
public boolean handlePortalException(String exception) throws Exception {
    if (exception.isEmpty()) {
        return false;
    }/*  w  ww . jav a 2s .  c  o  m*/

    String innerException = "";

    if (exception.contains("$")) {
        String[] exceptionParts = exception.split("\\$");

        exception = exceptionParts[0];
        innerException = exceptionParts[1];
    }

    boolean retryInProgress = ConnectionRetryUtil.retryInProgress(getSyncAccountId());

    if (!retryInProgress && _logger.isDebugEnabled()) {
        _logger.debug("Handling exception {}", exception);
    }

    if (exception.equals("Authenticated access required") || exception.equals("java.lang.SecurityException")) {

        throw new HttpResponseException(HttpStatus.SC_UNAUTHORIZED, "Authenticated access required");
    } else if (exception.endsWith("DuplicateLockException")) {
        SyncFile syncFile = getLocalSyncFile();

        if (syncFile == null) {
            return true;
        }

        syncFile.setState(SyncFile.STATE_ERROR);
        syncFile.setUiEvent(SyncFile.UI_EVENT_DUPLICATE_LOCK);

        SyncFileService.update(syncFile);
    } else if (exception.endsWith("FileExtensionException")) {
        SyncFile syncFile = getLocalSyncFile();

        if (syncFile == null) {
            return true;
        }

        syncFile.setState(SyncFile.STATE_ERROR);
        syncFile.setUiEvent(SyncFile.UI_EVENT_INVALID_FILE_EXTENSION);

        SyncFileService.update(syncFile);
    } else if (exception.endsWith("FileNameException") || exception.endsWith("FolderNameException")) {

        SyncFile syncFile = getLocalSyncFile();

        if (syncFile == null) {
            return true;
        }

        syncFile.setState(SyncFile.STATE_ERROR);
        syncFile.setUiEvent(SyncFile.UI_EVENT_INVALID_FILE_NAME);

        SyncFileService.update(syncFile);
    } else if (exception.equals("java.lang.OutOfMemoryError")) {
        retryServerConnection(SyncAccount.UI_EVENT_CONNECTION_EXCEPTION);
    } else if (exception.endsWith("NoSuchFileEntryException") || exception.endsWith("NoSuchFolderException")) {

        SyncFile syncFile = getLocalSyncFile();

        if (syncFile == null) {
            return true;
        }

        Path filePath = Paths.get(syncFile.getFilePathName());

        if (FileUtil.exists(filePath)) {
            Watcher watcher = WatcherManager.getWatcher(getSyncAccountId());

            watcher.addDeletedFilePathName(syncFile.getFilePathName());

            FileUtil.deleteFile(filePath);
        }

        SyncFileService.deleteSyncFile(syncFile, false);
    } else if (exception.endsWith("NoSuchJSONWebServiceException")) {
        retryServerConnection(SyncAccount.UI_EVENT_SYNC_WEB_MISSING);
    } else if (exception.endsWith("PrincipalException")) {
        SyncFile syncFile = getLocalSyncFile();

        if (syncFile == null) {
            return true;
        }

        SyncFileService.setStatuses(syncFile, SyncFile.STATE_ERROR, SyncFile.UI_EVENT_INVALID_PERMISSIONS);
    } else if (exception.endsWith("SyncClientMinBuildException")) {
        retryServerConnection(SyncAccount.UI_EVENT_MIN_BUILD_REQUIREMENT_FAILED);
    } else if (exception.endsWith("SyncDeviceActiveException")) {
        retryServerConnection(SyncAccount.UI_EVENT_SYNC_ACCOUNT_NOT_ACTIVE);
    } else if (exception.endsWith("SyncDeviceWipeException")) {
        if (_logger.isDebugEnabled()) {
            _logger.debug("Wiping Sync account {}", getSyncAccountId());
        }

        SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(getSyncAccountId());

        syncAccount.setUiEvent(SyncAccount.UI_EVENT_SYNC_ACCOUNT_WIPED);

        SyncAccountService.update(syncAccount);

        SyncAccountService.deleteSyncAccount(getSyncAccountId(), false);
    } else if (exception.endsWith("SyncServicesUnavailableException")) {
        retryServerConnection(SyncAccount.UI_EVENT_SYNC_SERVICES_NOT_ACTIVE);
    } else if (exception.endsWith("SyncSiteUnavailableException")) {
        handleSiteDeactivatedException();
    } else if (exception.endsWith("UploadException") || innerException.equals("SizeLimitExceededException")) {

        SyncFile syncFile = getLocalSyncFile();

        if ((syncFile == null) || syncFile.isSystem()) {
            return true;
        }

        syncFile.setState(SyncFile.STATE_ERROR);
        syncFile.setUiEvent(SyncFile.UI_EVENT_EXCEEDED_SIZE_LIMIT);

        SyncFileService.update(syncFile);
    } else {
        if (retryInProgress && _logger.isDebugEnabled()) {
            _logger.debug("Handling exception {}", exception);
        }

        SyncFile syncFile = getLocalSyncFile();

        if ((syncFile == null) || syncFile.isSystem()) {
            return true;
        }

        syncFile.setState(SyncFile.STATE_ERROR);
        syncFile.setUiEvent(SyncFile.UI_EVENT_NONE);

        SyncFileService.update(syncFile);
    }

    return true;
}

From source file:cn.rongcloud.im.server.network.http.BinaryHttpResponseHandler.java

@Override
public final void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(
                status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;/*ww  w  .j ava  2s .co m*/
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : getAllowedContentTypes()) {
        try {
            if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        } catch (PatternSyntaxException e) {
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null,
                new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}

From source file:com.nutsuser.ridersdomain.http.BinaryHttpResponseHandler.java

@Override
protected void sendResponseMessage(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    if (contentTypeHeaders.length != 1) {
        //malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(
                status.getStatusCode(), "None, or more than one, Content-Type Header found!"));
        return;/*from   ww  w  .  j  a va 2s  .  com*/
    }
    Header contentTypeHeader = contentTypeHeaders[0];
    boolean foundAllowedContentType = false;
    for (String anAllowedContentType : getAllowedContentTypes()) {
        try {
            if (Pattern.matches(anAllowedContentType, contentTypeHeader.getValue())) {
                foundAllowedContentType = true;
            }
        } catch (PatternSyntaxException e) {
            Log.e("BinaryHttpResponseHandler", "Given pattern is not valid: " + anAllowedContentType, e);
        }
    }
    if (!foundAllowedContentType) {
        //Content-Type not in allowed list, ABORT!
        sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null,
                new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"));
        return;
    }
    super.sendResponseMessage(response);
}