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

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

Introduction

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

Prototype

public int getStatusCode() 

Source Link

Usage

From source file:com.puppetlabs.geppetto.forge.impl.ForgeServiceImpl.java

@Override
public void publish(File moduleArchive, boolean dryRun, Diagnostic result) throws IOException {
    if (releaseService == null)
        throw new UnsupportedOperationException(
                "Unable to publish since no release service is configured. Was a serviceURL provided in the preferences?");

    Metadata metadata = forgeUtil.getMetadataFromPackage(moduleArchive);
    if (metadata == null)
        throw new ForgeException("No \"metadata.json\" found in archive: " + moduleArchive.getAbsolutePath());

    if (metadata.getName() == null)
        throw new ForgeException(
                "The \"metadata.json\" found in archive: " + moduleArchive.getAbsolutePath() + " has no name");

    if (metadata.getVersion() == null)
        throw new ForgeException("The \"metadata.json\" found in archive: " + moduleArchive.getAbsolutePath()
                + " has no version");

    try {//from www  .j  a  v a2s  .  c  o m
        if (metadataRepo.resolve(metadata.getName(), metadata.getVersion()) != null)
            throw new AlreadyPublishedException("Module " + metadata.getName() + ':' + metadata.getVersion()
                    + " has already been published");
    } catch (HttpResponseException e) {
        // A SC_NOT_FOUND can be expected and is OK.
        if (e.getStatusCode() != HttpStatus.SC_NOT_FOUND)
            throw new ForgeException("Unable to check module existence on the forge: " + e.getMessage());
    }

    if (dryRun) {
        result.addChild(new Diagnostic(INFO, PUBLISHER, "Module file " + moduleArchive.getName()
                + " would have been uploaded (but wasn't since this is a dry run)"));
        return;
    }

    InputStream gzInput = new FileInputStream(moduleArchive);
    try {
        ModuleName name = metadata.getName();
        releaseService.create(name.getOwner(), name.getName(), "Published using GitHub trigger", gzInput,
                moduleArchive.length());
        result.addChild(new Diagnostic(INFO, PUBLISHER,
                "Module file " + moduleArchive.getName() + " has been uploaded"));
    } finally {
        StreamUtil.close(gzInput);
    }
}

From source file:fr.lissi.belilif.om2m.oao.ContainerManager.java

@Override
public int delete(Container obj) {
    if (obj.getApplication() == null || obj.getApplication().getAppId() == null) {
        LOGGER.error("you must specify the parent resource (parent Application) to manage containers.");
        return -1;
    }//w  w w  .  j a va 2 s .c  om

    HttpGetSimpleResp resp;
    int appResponse = -1;
    try {
        resp = WebServiceActions.doDelete(this.OM2MUrlBase + "applications/" + obj.getApplication().getAppId()
                + "/containers/" + obj.getId(), headers);
        appResponse = resp.getStatusCode();
    } catch (HttpResponseException e) {
        LOGGER.error("HttpResponseException - " + e.getStatusCode() + " / " + e.getMessage());
        appResponse = e.getStatusCode();
    } catch (ClientProtocolException e) {
        LOGGER.error(e);
    } catch (ConnectException e) {
        LOGGER.error(
                e.getMessage() + ". \nThe server '" + this.OM2MUrlBase.substring(7, 21) + "' is unreachable.");
    } catch (IOException e) {
        LOGGER.error(e);
    }
    return appResponse;
}

From source file:fr.lissi.belilif.om2m.oao.ContainerManager.java

@Override
public Container get(Container obj) {
    // TODO ContainerResponse -> Container
    if (obj.getApplication() == null || obj.getApplication().getAppId() == null) {
        LOGGER.error("you must specify the parent resource (parent Application) to manage containers.");
        return null;
    }// w w  w.  ja v a2 s .  co m

    LOGGER.debug(this.OM2MUrlBase + "applications/" + obj.getApplication().getAppId() + "/containers/"
            + obj.getId());

    Container containerResponse = null;
    HttpGetSimpleResp resp;
    try {
        resp = WebServiceActions.doGet(this.OM2MUrlBase + "applications/" + obj.getApplication().getAppId()
                + "/containers/" + obj.getId(), headers);
        if (resp.getStatusCode() == 200)
            containerResponse = (Container) JAXBMapper.XMLStringToObject(resp.getResult(), Container.class);
    } catch (HttpResponseException e) {
        LOGGER.error("HttpResponseException - " + e.getStatusCode() + " / " + e.getMessage());
    } catch (ClientProtocolException e) {
        LOGGER.error(e.getMessage());
    } catch (ConnectException e) {
        LOGGER.error(
                e.getMessage() + ". \nThe server '" + this.OM2MUrlBase.substring(7, 21) + "' is unreachable.");
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }
    return containerResponse;
}

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

private static Bundle authenticate(Context context, NetworkClient nc, String username, String password)
        throws IOException, JSONException, NetworkProtocolException {

    nc.setCredentials(username, password);

    boolean authenticated = false;
    try {/*from  w w w  .j av a 2s . c  om*/
        final HttpResponse res = nc.get(PATH_USER);

        authenticated = nc.checkStatusCode(res, false);

        final HttpEntity ent = res.getEntity();
        JSONObject jo = null;

        if (authenticated) {
            jo = new JSONObject(StreamUtils.inputStreamToString(ent.getContent()));
            ent.consumeContent();
        } else {
            jo = null;
        }

        final Bundle userData = jsonObjectToBundle(jo, true);
        userData.putString(AuthenticationService.USERDATA_LOCAST_API_URL, nc.getBaseUrl());
        return userData;

    } catch (final HttpResponseException e) {
        if (e.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            return null;
        } else {
            throw e;
        }
    }
}

From source file:net.wasdev.gameon.concierge.PlayerClient.java

/**
 * Obtain apiKey for player id.//from   w  w  w  . j  av  a2 s  .c om
 *
 * @param playerId
 *            The player id
 * @return The apiKey for the player
 */
public String getApiKey(String playerId) throws IOException {
    String jwt = getClientJwtForId(playerId);

    HttpClient client = null;
    if ("development".equals(System.getenv("CONCIERGE_PLAYER_MODE"))) {
        System.out.println("Using development mode player connection. (DefaultSSL,NoHostNameValidation)");
        try {
            HttpClientBuilder b = HttpClientBuilder.create();

            //use the default ssl context, we have a trust store configured for player cert.
            SSLContext sslContext = SSLContext.getDefault();

            //use a very trusting truststore.. (not needed..)
            //SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();

            b.setSSLContext(sslContext);

            //disable hostname validation, because we'll need to access the cert via a different hostname.
            b.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);

            client = b.build();
        } catch (Exception e) {
            throw new IOException(e);
        }
    } else {
        client = HttpClientBuilder.create().build();
    }
    HttpGet hg = new HttpGet(playerLocation + "/" + playerId + "?jwt=" + jwt);

    System.out.println("Building web target " + hg.getURI().toString());

    try {
        // Make GET request using the specified target, get result as a
        // string containing JSON
        HttpResponse r = client.execute(hg);
        String result = new BasicResponseHandler().handleResponse(r);

        // Parse the JSON response, and retrieve the apiKey field value.
        ObjectMapper om = new ObjectMapper();
        JsonNode jn = om.readValue(result, JsonNode.class);

        return jn.get("apiKey").textValue();
    } catch (HttpResponseException hre) {
        System.out.println(
                "Error communicating with player service: " + hre.getStatusCode() + " " + hre.getMessage());
        throw hre;
    } catch (ResponseProcessingException rpe) {
        System.out.println("Error processing response " + rpe.getResponse().toString());
        throw new IOException(rpe);
    } catch (ProcessingException | WebApplicationException ex) {
        //bad stuff.
        System.out.println("Hmm.. " + ex.getMessage());
        throw new IOException(ex);
    } catch (IOException io) {
        System.out.println("Utoh.. " + io.getMessage());
        throw new IOException(io);
    }

}

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

@Override
public void handleException(Exception e) {
    if (_event.isCancelled()) {
        return;/*  ww w. j  a  v  a2  s  .com*/
    }

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

    if (!ConnectionRetryUtil.retryInProgress(getSyncAccountId()) && _logger.isDebugEnabled()) {

        _logger.debug("Handling exception {}", e.toString());
    }

    if (e instanceof HttpResponseException) {
        HttpResponseException hre = (HttpResponseException) e;

        int statusCode = hre.getStatusCode();

        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            if (_logger.isDebugEnabled()) {
                _logger.debug("Authentication failed. Retrying in {} seconds.",
                        syncAccount.getAuthenticationRetryInterval());
            }

            syncAccount.setState(SyncAccount.STATE_DISCONNECTED);
            syncAccount.setUiEvent(SyncAccount.UI_EVENT_AUTHENTICATION_EXCEPTION);

            SyncAccountService.update(syncAccount);

            ServerEventUtil.retryServerConnection(getSyncAccountId(),
                    syncAccount.getAuthenticationRetryInterval(), TimeUnit.SECONDS);

            return;
        }
    }

    if (e instanceof ClientProtocolException || e instanceof ConnectTimeoutException
            || e instanceof HttpHostConnectException || e instanceof NoHttpResponseException
            || e instanceof SocketException || e instanceof SocketTimeoutException || e instanceof SSLException
            || e instanceof TruncatedChunkException || e instanceof UnknownHostException) {

        retryServerConnection(SyncAccount.UI_EVENT_CONNECTION_EXCEPTION);
    } else if (e instanceof FileNotFoundException) {
        SyncFile syncFile = (SyncFile) getParameterValue("syncFile");

        String message = e.getMessage();

        if (message.contains("The process cannot access the file")) {
            if (_logger.isTraceEnabled()) {
                _logger.trace("Retrying event {} for sync file {}", _event, syncFile);
            }

            _scheduledExecutorService.schedule(_event, 1, TimeUnit.SECONDS);
        } else if (syncFile.getVersion() == null) {
            SyncFileService.deleteSyncFile(syncFile, false);
        }
    } else {
        _logger.error(e.getMessage(), e);
    }
}

From source file:fr.lissi.belilif.om2m.oao.ContainerManager.java

/**
 * Gets the all./*from   www.  jav a2 s .  co  m*/
 *
 * @param res
 *            instance of Application.
 * @return All container of the Application 'res'.
 * @see fr.lissi.belilif.om2m.oao.Om2mManager#getAll()
 */
@Override
public List<Container> getAll(Resource res) {
    Application app;
    if (res instanceof Application) {
        app = (Application) res;
    } else {
        LOGGER.error(
                "The parameter of the method 'ContainerManager->getAll' must be an instance of Application.");
        return null;
    }

    HttpGetSimpleResp resp = null;
    try {
        resp = WebServiceActions.doGet(this.OM2MUrlBase + "applications/" + app.getAppId() + "/containers",
                headers);
    } catch (HttpResponseException e) {
        LOGGER.error("HttpResponseException - " + e.getStatusCode() + " / " + e.getMessage());
    } catch (ClientProtocolException e) {
        LOGGER.error(e);
    } catch (ConnectException e) {
        LOGGER.error(
                e.getMessage() + ". \nThe server '" + this.OM2MUrlBase.substring(7, 21) + "' is unreachable.");
    } catch (IOException e) {
        LOGGER.error(e);
    }

    // xml to object
    Containers containersResp = (Containers) JAXBMapper.XMLStringToObject(resp.getResult(), Containers.class);
    List<Container> apps = new ArrayList<Container>();

    for (ReferenceToNamedResource refToNamedRes : containersResp.getContainerCollection().getNamedReference()) {
        apps.add(new Container(refToNamedRes.getId()));
    }

    return apps;
}

From source file:com.mywork.framework.util.RemoteHttpUtil.java

/**
 * FluentAPI/*from ww  w  . j  av a 2  s  .  c o  m*/
 */
@SuppressWarnings("unused")
public void fluentAPIDemo(String contentUrl) throws IOException {
    try {
        // demo1: ? , (200 total/100 per route), returnContent()??inputstream
        String resultString = Request.Get(contentUrl).execute().returnContent().asString();

        // demo2: ?, 
        byte[] resultBytes = Request.Get(contentUrl).connectTimeout(TIMEOUT_SECONDS * 1000)
                .socketTimeout(TIMEOUT_SECONDS * 1000).execute().returnContent().asBytes();

        // demo3: ??httpClient
        Executor executor = Executor.newInstance(httpClient);
        String resultString2 = executor.execute(Request.Get(contentUrl)).returnContent().asString();
    } catch (HttpResponseException e) {
        logger.error("Status code:" + e.getStatusCode(), e);
    }
}

From source file:org.zenoss.metrics.reporter.ZenossMetricsReporter.java

@Override
public void run() {
    final long timestamp = clock.time() / 1000;
    final MetricBatch batchContext = new MetricBatch(timestamp);
    if (reportJvmMetrics) {
        collectVmMetrics(batchContext);//from   w  ww .  j  a v a  2 s  .  c  om
    }
    collectMetrics(batchContext);
    try {

        LOG.debug("Posting {} metrics", batchContext.getMetrics().size());
        if (LOG.isTraceEnabled()) {
            for (org.zenoss.app.consumer.metric.data.Metric m : batchContext.getMetrics()) {
                LOG.trace("Sending metric {}", m.toString());
            }
        }
        post(batchContext);
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            // the cookies were cleared so try again
            try {
                LOG.debug("Error posting metrics. Posting with batchContext.", e);
                post(batchContext);
                return;
            } catch (IOException j) {
                // redefine the exception e
                LOG.error("Error posting metrics", j);
            }
        } else {
            LOG.error("Error posting metrics", e);
        }
    } catch (IOException e) {
        LOG.error("Error posting metrics", e);
    }
}

From source file:com.offbytwo.jenkins.JenkinsServer.java

public MavenJobWithDetails getMavenJob(String jobName) throws IOException {
    try {/*ww w.j a  v  a2 s. c o  m*/
        MavenJobWithDetails job = client.get("/job/" + encode(jobName), MavenJobWithDetails.class);
        job.setClient(client);

        return job;
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == 404) {
            return null;
        }
        throw e;
    }
}