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.offbytwo.jenkins.JenkinsServer.java

/**
 * Get a single Job from the server.//from  ww w .j  a v a  2 s .com
 *
 * @return A single Job, null if not present
 * @throws IOException
 */
public JobWithDetails getJob(String jobName) throws IOException {
    try {
        JobWithDetails job = client.get("/job/" + encode(jobName), JobWithDetails.class);
        job.setClient(client);

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

}

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

public QueueItem getQueueItem(QueueReference ref) throws IOException {
    try {/* www  .  java2 s .co m*/
        String url = ref.getQueueItemUrlPart();
        // "/queue/item/" + id
        QueueItem job = client.get(url, QueueItem.class);
        job.setClient(client);

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

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

public Build getBuild(QueueItem q) throws IOException {
    // http://ci.seitenbau.net/job/rainer-ansible-build/51/
    try {/*  ww  w .  ja  va  2 s .  c  om*/
        String url = q.getExecutable().getUrl();
        // "/queue/item/" + id
        Build job = client.get(url, Build.class);
        job.setClient(client);

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

From source file:org.carrot2.source.etools.EToolsDocumentSource.java

@Override
protected SearchEngineResponse fetchSearchResponse() throws Exception {
    try {//from   w w  w. j  a  va2  s .c  o  m
        return super.fetchSearchResponse();
    } catch (Exception e) {
        if (e instanceof HttpResponseException) {
            HttpResponseException httpException = (HttpResponseException) e;
            int sCode = httpException.getStatusCode();
            if (sCode == 302 || sCode == 403) {
                throw new IpBannedException(httpException);
            }
        }
        throw e;
    }
}

From source file:com.xorcode.andtweet.net.ConnectionOAuth.java

private JSONObject postRequest(HttpPost post) throws ConnectionException {
    JSONObject jso = null;//w  w w .j  a v  a  2  s  . com
    boolean ok = false;
    try {
        // Maybe we'll need this:
        // post.setParams(...);

        // sign the request to authenticate
        mConsumer.sign(post);
        String response = mClient.execute(post, new BasicResponseHandler());
        jso = new JSONObject(response);
        ok = true;
    } catch (HttpResponseException e) {
        ConnectionException e2 = new ConnectionException(e.getStatusCode(), e.getLocalizedMessage());
        Log.w(TAG, e2.getLocalizedMessage());
        throw e2;
    } catch (Exception e) {
        // We don't catch other exceptions because in fact it's vary difficult to tell
        // what was a real cause of it. So let's make code clearer.
        e.printStackTrace();
        throw new ConnectionException(e.getLocalizedMessage());
    }
    if (!ok) {
        jso = null;
    }
    return jso;
}

From source file:ch.cyberduck.core.dav.DAVPath.java

@Override
public ResponseOutputStream<Void> write(final TransferStatus status) throws IOException {
    final Map<String, String> headers = new HashMap<String, String>();
    if (status.isResume()) {
        headers.put(HttpHeaders.CONTENT_RANGE,
                "bytes " + status.getCurrent() + "-" + (status.getLength() - 1) + "/" + status.getLength());
    }/*w w w.  j  a  v  a  2 s . c o  m*/
    if (Preferences.instance().getBoolean("webdav.expect-continue")) {
        headers.put(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE);
    }
    try {
        return this.write(headers, status);
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED) {
            // Retry with the Expect header removed
            headers.remove(HTTP.EXPECT_DIRECTIVE);
            return this.write(headers, status);
        } else {
            throw e;
        }
    }
}

From source file:at.ac.tuwien.detlef.gpodder.SyncSubscriptionsAsyncTask.java

@Override
public void run() {
    boolean success = false;

    /* Retrieve settings. */
    GpodderSettings gps = Singletons.i().getGpodderSettings();

    DeviceId id = gps.getDeviceId();//from ww  w.j  a v a 2  s. c o  m
    if (id == null) {
        sendError(GENERIC_ERROR, Detlef.getAppContext().getString(R.string.no_gpodder_account_configured));
        return;
    }

    PodcastDAO pdao = Singletons.i().getPodcastDAO();

    String devId = id.toString();

    long lastUpdate = gps.getLastUpdate();

    MygPodderClient gpc = new MygPodderClient(gps.getUsername(), gps.getPassword(), gps.getApiHostname());

    try {
        EnhancedSubscriptionChanges localChanges = new EnhancedSubscriptionChanges(
                pdao.getLocallyAddedPodcasts(), pdao.getLocallyDeletedPodcasts(), lastUpdate);

        UpdateResult result = gpc.updateSubscriptions(devId, localChanges.getAddUrls(),
                localChanges.getRemoveUrls());

        /* Login and get subscription changes */
        SubscriptionChanges changes = gpc.pullSubscriptions(devId, lastUpdate);

        /* Get the Details for the individual URLs. */

        PodcastDetailsRetriever pdr = new PodcastDetailsRetriever();
        EnhancedSubscriptionChanges remoteChanges = pdr.getPodcastDetails(changes);

        /* Update the db here */

        applySubscriptionChanges(Detlef.getAppContext(), localChanges);
        applySubscriptionChanges(Detlef.getAppContext(), remoteChanges);

        /* apply the changed URLs */
        if (result.updateUrls != null && result.updateUrls.size() > 0) {
            for (String oldUrl : result.updateUrls.keySet()) {
                Podcast p = pdao.getPodcastByUrl(oldUrl);
                if (p == null) {
                    continue;
                }

                String newUrl = result.updateUrls.get(oldUrl);
                if (newUrl == null) {
                    newUrl = "";
                }

                p.setUrl(newUrl);
                pdao.update(p);
            }
        }

        /* Update last changed timestamp. */
        gps.setLastUpdate(remoteChanges.getTimestamp());

        Singletons.i().getGpodderSettingsDAO().writeSettings(gps);

        success = true;
    } catch (HttpResponseException e) {
        String eMsg = e.getLocalizedMessage();
        switch (e.getStatusCode()) {
        case HTTP_STATUS_FORBIDDEN:
            eMsg = Detlef.getAppContext().getString(R.string.connectiontest_unsuccessful);
            break;
        case HTTP_STATUS_NOT_FOUND:
            eMsg = String.format(Detlef.getAppContext().getString(R.string.device_doesnt_exist_fmt), devId);
            break;
        default:
            break;
        }
        sendError(e.getStatusCode(), eMsg);
    } catch (AuthenticationException e) {
        sendError(GENERIC_ERROR, e.getLocalizedMessage());
    } catch (ClientProtocolException e) {
        sendError(GENERIC_ERROR, e.getLocalizedMessage());
    } catch (IOException e) {
        sendError(GENERIC_ERROR, e.getLocalizedMessage());
    } catch (Exception e) {
        sendError(GENERIC_ERROR, e.getLocalizedMessage());
    }

    if (!success) {
        return;
    }

    /* Send the result. */
    callback.sendEvent(new NoDataResultHandler.NoDataSuccessEvent(callback));
}

From source file:com.jaspersoft.studio.server.publish.Publish.java

private IStatus publishResources(IProgressMonitor monitor, JasperDesign jd, AMJrxmlContainer parent)
        throws Exception {
    MReportUnit mrunit = null;/*  w  w w .j  a va  2s. co m*/
    MJrxml jrxml = null;
    if (parent instanceof MReportUnit) {
        mrunit = (MReportUnit) parent;
        jrxml = new MJrxml(mrunit, PublishUtil.getMainReport(monitor, mrunit, jd), 0);
    } else if (parent.getParent() instanceof MReportUnit) {
        jrxml = (MJrxml) parent;
        mrunit = (MReportUnit) parent.getParent();
    } else if (parent.getParent() instanceof MFolder) {
        jrxml = (MJrxml) parent;
    } else
        return Status.CANCEL_STATUS;

    File file = FileUtils.createTempFile("jrsres", FileExtension.PointJRXML); //$NON-NLS-1$ 
    String version = ServerManager.getVersion(Misc.nvl(mrunit, jrxml));
    ResourceDescriptor rdjrxml = jrxml.getValue();
    if (rdjrxml.getParentFolder() != null && !rdjrxml.getParentFolder().endsWith("_files"))
        rdjrxml.setIsReference(true);

    List<MResource> resources = ((JasperReportsConfiguration) jrConfig).get(PublishUtil.KEY_PUBLISH2JSS_DATA,
            new ArrayList<MResource>());
    updSelectedResources(monitor, resources, version);
    FileUtils.writeFile(file, JRXmlWriterHelper.writeReport(jrConfig, jd, version));
    jrxml.setFile(file);

    IFile ifile = (IFile) jrConfig.get(FileUtils.KEY_FILE);
    PublishUtil.savePreferences(ifile, resources);

    if (mrunit != null && !jrxml.getValue().getIsReference()) {
        ResourceDescriptor oldRU = mrunit.getValue();
        ResourceDescriptor r = mrunit.getValue();
        try {
            r = mrunit.getWsClient().get(monitor, mrunit.getValue(), null);
            mrunit.setValue(r);
        } catch (HttpResponseException e) {
            if (e.getStatusCode() != 404)
                throw e;
        } catch (Exception e) {
        }
        // setup datasource
        ResourceDescriptor ds = null;
        for (ResourceDescriptor rd : oldRU.getChildren()) {
            if (rd != null && SelectorDatasource.isDatasource(rd)) {
                ds = rd;
                ds.setDirty(false);
                break;
            }
        }
        ResourceDescriptor newDs = null;
        for (ResourceDescriptor rd : r.getChildren()) {
            if (rd != null && SelectorDatasource.isDatasource(rd)) {
                newDs = rd;
                break;
            }
        }
        if (newDs != null)
            r.getChildren().remove(newDs);
        if (ds != null)
            r.getChildren().add(0, ds);

        // setup main jrxml
        boolean isMain = true;
        for (ResourceDescriptor rd : r.getChildren()) {
            if (rd.getUriString() == null)
                continue;
            String wsType = rd.getWsType();
            if (rd.getUriString().equals(rdjrxml.getUriString())
                    && (wsType.equals(ResourceDescriptor.TYPE_JRXML)
                            || wsType.equals(ResourceDescriptor.TYPE_REFERENCE))) {
                isMain = rd.isMainReport();
                break;
            }
        }
        rdjrxml.setMainReport(isMain);
        PublishUtil.setChild(r, rdjrxml);
        for (MResource res : resources) {
            if (res.getPublishOptions().getOverwrite(OverwriteEnum.IGNORE).equals(OverwriteEnum.OVERWRITE)) {
                ResourceDescriptor rd = res.getValue();
                if (rd.getData() != null && !rd.getParentFolder().endsWith("_files")) {
                    mrunit.getWsClient().addOrModifyResource(monitor, rd, null);
                } else
                    PublishUtil.setChild(r, rd);
            }
        }
        mrunit.getWsClient().addOrModifyResource(monitor, r, file);
        this.resources.add(r.getUriString());
        for (MResource res : resources)
            if (res.getPublishOptions().getOverwrite(OverwriteEnum.IGNORE).equals(OverwriteEnum.OVERWRITE)) {
                PublishUtil.savePreferencesNoOverwrite(ifile, res);
                this.resources.add(res.getValue().getUriString());
            }
    } else {
        jrxml.setValue(saveResource(monitor, jrxml));
        for (MResource res : resources) {
            PublishOptions popt = res.getPublishOptions();
            if (popt.getOverwrite(OverwriteEnum.IGNORE).equals(OverwriteEnum.OVERWRITE)) {
                saveResource(monitor, res);
                PublishUtil.savePreferencesNoOverwrite(ifile, res);
            }
            if (monitor.isCanceled())
                return Status.CANCEL_STATUS;
        }
    }
    return Status.OK_STATUS;
}

From source file:com.postmark.PostmarkMailSender.java

@Override
public void send(SimpleMailMessage message) throws MailException {

    HttpClient httpClient = new DefaultHttpClient();
    PostmarkResponse theResponse = new PostmarkResponse();

    try {//from   ww w.j  a v a 2 s  . c o m

        // Create post request to Postmark API endpoint
        HttpPost method = new HttpPost("http://api.postmarkapp.com/email");

        // Add standard headers required by Postmark
        method.addHeader("Accept", "application/json");
        method.addHeader("Content-Type", "application/json; charset=utf-8");
        method.addHeader("X-Postmark-Server-Token", serverToken);
        method.addHeader("User-Agent", "Postmark-Java");

        // Convert the message into JSON content
        String messageContents = UnicodeEscapeFilterWriter.escape(gson.toJson(message));
        logger.log(Level.FINER, "Message contents: " + messageContents);

        // Add JSON as payload to post request
        StringEntity payload = new StringEntity(messageContents);
        payload.setContentEncoding(HTTP.UTF_8);
        method.setEntity(payload);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            String response = httpClient.execute(method, responseHandler);
            logger.log(Level.FINER, "Message response: " + response);
            theResponse = gson.fromJson(response, PostmarkResponse.class);
            theResponse.status = PostmarkResponseStatus.SUCCESS;
        } catch (HttpResponseException hre) {
            switch (hre.getStatusCode()) {
            case 401:
            case 422:
                logger.log(Level.SEVERE, "There was a problem with the email: " + hre.getMessage());
                theResponse.setMessage(hre.getMessage());
                theResponse.status = PostmarkResponseStatus.USERERROR;
                throw new MailSendException("Postmark returned: " + theResponse);
            case 500:
                logger.log(Level.SEVERE, "There has been an error sending your email: " + hre.getMessage());
                theResponse.setMessage(hre.getMessage());
                theResponse.status = PostmarkResponseStatus.SERVERERROR;
                throw new MailSendException("Postmark returned: " + theResponse);
            default:
                logger.log(Level.SEVERE,
                        "There has been an unknow error sending your email: " + hre.getMessage());
                theResponse.status = PostmarkResponseStatus.UNKNOWN;
                theResponse.setMessage(hre.getMessage());
                throw new MailSendException("Postmark returned: " + theResponse);
            }
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, "There has been an error sending email: " + e.getMessage());
        throw new MailSendException("There has been an error sending email", e);

    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}