Example usage for org.apache.commons.httpclient HttpStatus getStatusText

List of usage examples for org.apache.commons.httpclient HttpStatus getStatusText

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus getStatusText.

Prototype

public static String getStatusText(int statusCode) 

Source Link

Document

Get the reason phrase for a particular status code.

Usage

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private PostMethod postInternal(String formUrl, Map<String, String> changed, final ITaskAttachment attach)
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {

    WebClientUtil.setupHttpClient(httpClient, proxy, formUrl, null, null);
    if (!authenticated && hasAuthenticationCredentials()) {
        authenticate();/*from w  ww.ja v a  2 s . c om*/
    }

    String requestUrl = WebClientUtil.getRequestPath(formUrl + "&token=" + token);

    ArrayList<Part> parts = new ArrayList<Part>();
    if (attach != null) {
        requestUrl += "&nFileCount=1";
        FilePart part = new FilePart("File1", new PartSource() {

            public InputStream createInputStream() throws IOException {
                return attach.createInputStream();
            }

            public String getFileName() {
                return attach.getFilename();
            }

            public long getLength() {
                return attach.getLength();
            }

        });
        part.setTransferEncoding(null);
        parts.add(part);
        parts.add(new StringPart("Content-Type", attach.getContentType()));
    }
    PostMethod postMethod = new PostMethod(requestUrl);
    // postMethod.setRequestHeader("Content-Type",
    // "application/x-www-form-urlencoded; charset="
    // + characterEncoding);

    // postMethod.setRequestBody(formData);
    postMethod.setDoAuthentication(true);

    for (String key : changed.keySet()) {
        StringPart p = new StringPart(key, changed.get(key));
        p.setTransferEncoding(null);
        p.setContentType(null);
        parts.add(p);
    }
    postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));

    int status = httpClient.executeMethod(postMethod);
    if (status == HttpStatus.SC_OK) {
        return postMethod;
    } else {
        postMethod.getResponseBody();
        postMethod.releaseConnection();
        throw new IOException(
                "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status));
    }
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(File file, boolean retry) {
    String result = null;// ww  w . jav  a  2 s.  c om
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading file with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        int status = httpClient.executeMethod(post);

        StringWriter sw = new StringWriter();
        try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) {
            int b;
            while ((b = in.read()) != -1) {
                pw.write(b);
            }
        }

        switch (status) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_CREATED:
        case HttpStatus.SC_ACCEPTED:
            result = sw.toString().trim();
            log.info("Upload complete, response=" + result);
            break;
        case HttpStatus.SC_FORBIDDEN:
            log.warn("Authorization to Fedora failed, attempting to reestablish connection.");
            try {
                this.initializeConnections();
                return upload(file, false);
            } catch (Exception e) {
                log.error("Failed to reestablish connection to Fedora", e);
            }
            break;
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            throw new FedoraTimeoutException("Fedora service unavailable, upload failed");
        default:
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
            break;
        }
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private PostMethod postInternal(String formUrl, Map<String, String> changed, final ITaskAttachment attach,
        IProgressMonitor monitor)/* www . ja  v a  2 s . co  m*/
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {

    WebClientUtil.setupHttpClient(httpClient, proxy, formUrl, null, null);
    if (!authenticated && hasAuthenticationCredentials()) {
        monitor.subTask("Authenticating request");
        authenticate();
        if (checkMonitor(monitor))
            return null;
    }

    String requestUrl = WebClientUtil.getRequestPath(formUrl + "&token=" + token);

    ArrayList<Part> parts = new ArrayList<Part>();
    if (attach != null) {
        requestUrl += "&nFileCount=1";
        FilePart part = new FilePart("File1", new PartSource() {

            public InputStream createInputStream() throws IOException {
                return attach.createInputStream();
            }

            public String getFileName() {
                return attach.getFilename();
            }

            public long getLength() {
                return attach.getLength();
            }

        });
        part.setTransferEncoding(null);
        parts.add(part);
        parts.add(new StringPart("Content-Type", attach.getContentType()));
    }
    PostMethod postMethod = new PostMethod(requestUrl);
    // postMethod.setRequestHeader("Content-Type",
    // "application/x-www-form-urlencoded; charset="
    // + characterEncoding);

    // postMethod.setRequestBody(formData);
    postMethod.setDoAuthentication(true);

    for (String key : changed.keySet()) {
        StringPart p = new StringPart(key, changed.get(key));
        p.setTransferEncoding(null);
        p.setContentType(null);
        parts.add(p);
    }
    postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));

    monitor.subTask("Sending request");
    int status = httpClient.executeMethod(postMethod);
    if (status == HttpStatus.SC_OK) {
        return postMethod;
    } else {
        postMethod.getResponseBody();
        postMethod.releaseConnection();
        throw new IOException(
                "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status));
    }
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(byte[] bytes, String fileName) {
    String result = null;//from  w ww.j av  a  2 s .  co m
    // construct a post request to Fedora upload service
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading XML with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", new ByteArrayPartSource(fileName, bytes)) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        int status = httpClient.executeMethod(post);

        StringWriter sw = new StringWriter();
        try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) {
            int b;
            while ((b = in.read()) != -1) {
                pw.write(b);
            }
        }
        if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_ACCEPTED) {
            result = sw.toString().trim();
            log.debug("Upload complete, response=" + result);
        } else {
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
        }
    } catch (Exception ex) {
        log.error("Upload failed due to error", ex);
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}

From source file:com.apatar.rss.RssNode.java

private void publishing() throws HttpException, IOException, ApatarException {
    Object obj = ApplicationData.getProject().getProjectData(getConnectionDataID()).getData();
    if (!(obj instanceof CreateNewParams)) {
        return;//from  ww w.  j  a va  2  s .  c o m
    }

    CreateNewParams params = (CreateNewParams) obj;

    PostMethod method = new PostMethod(PUBLISH_URL);

    String tempFolderName = "publish/";
    File tempFolder = new File(tempFolderName);
    if (!tempFolder.exists()) {
        tempFolder.mkdir();
    }
    String fileName = rssTitle == null ? "temp" : rssTitle.replaceAll("[|/\\:*?\"<> ]", "_") + ".aptr";
    ReadWriteXMLDataUi rwXMLdata = new ReadWriteXMLDataUi();
    File tempFile = rwXMLdata.writeXMLData(fileName.toString(), ApplicationData.getProject(), true);

    int partCount = 15;
    if (publishId != null) {
        partCount++;
    }
    Part[] parts = new Part[partCount];
    parts[0] = new StringPart("option", "com_remository");
    parts[1] = new StringPart("task", "");
    parts[2] = new StringPart("element", "component");
    parts[3] = new StringPart("client", "");
    parts[4] = new StringPart("oldid", "0");
    parts[5] = new FilePart("userfile", tempFile);
    parts[6] = new StringPart("containerid", "15");
    parts[7] = new StringPart("filetitle", rssTitle == null ? "" : rssTitle);
    parts[8] = new StringPart("description", description == null ? "" : description);
    parts[9] = new StringPart("smalldesc", description == null ? "" : description);
    parts[10] = new StringPart("filetags", "RSS");
    parts[11] = new StringPart("pubExternal", "true");
    parts[12] = new StringPart("username", username);
    parts[13] = new StringPart("password", CoreUtils.getMD5(password));
    parts[14] = new FilePart("rssfile", params.getFile());
    if (publishId != null) {
        parts[15] = new StringPart("dmid", publishId);
    }

    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                "Upload failed, response=" + HttpStatus.getStatusText(status));
    } else {
        if (publishId == null) {
            StringBuffer buff = new StringBuffer(method.getResponseBodyAsString());

            Matcher matcher = ApatarRegExp.getMatcher("<meta name=\"dmid\" content=\"[a-zA-Z_0-9]+\"",
                    buff.toString());

            while (matcher.find()) {
                String result = matcher.group();
                if (result == null || result.equals("")) {
                    JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Publishing error");
                    return;
                }
                result = result.replaceFirst("<meta name=\"dmid\" content=\"", "");
                result = result.replace("\"", "");
                publishId = result;
                return;
            }
        }
        JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Publishing error");
    }
}

From source file:davmail.caldav.CaldavConnection.java

/**
 * Send Http response with given status, headers, content type and content.
 * Close connection if keepAlive is false
 *
 * @param status      Http status/*from w w w  .j  a va2  s . com*/
 * @param headers     Http headers
 * @param contentType MIME content type
 * @param content     response body as byte array
 * @param keepAlive   keep connection open
 * @throws IOException on error
 */
public void sendHttpResponse(int status, Map<String, String> headers, String contentType, byte[] content,
        boolean keepAlive) throws IOException {
    sendClient("HTTP/1.1 " + status + ' ' + HttpStatus.getStatusText(status));
    if (status != HttpStatus.SC_UNAUTHORIZED) {
        sendClient("Server: DavMail Gateway " + DavGateway.getCurrentVersion());
        sendClient("DAV: 1, calendar-access, calendar-schedule, calendarserver-private-events, addressbook");
        SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
        // force GMT timezone
        formatter.setTimeZone(ExchangeSession.GMT_TIMEZONE);
        String now = formatter.format(new Date());
        sendClient("Date: " + now);
        sendClient("Expires: " + now);
        sendClient("Cache-Control: private, max-age=0");
    }
    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            sendClient(header.getKey() + ": " + header.getValue());
        }
    }
    if (contentType != null) {
        sendClient("Content-Type: " + contentType);
    }
    closed = closed || !keepAlive;
    sendClient("Connection: " + (closed ? "close" : "keep-alive"));
    if (content != null && content.length > 0) {
        sendClient("Content-Length: " + content.length);
    } else if (headers == null || !"chunked".equals(headers.get("Transfer-Encoding"))) {
        sendClient("Content-Length: 0");
    }
    sendClient("");
    if (content != null && content.length > 0) {
        // full debug trace
        if (wireLogger.isDebugEnabled()) {
            wireLogger.debug("> " + new String(content, "UTF-8"));
        }
        sendClient(content);
    }
}

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Creates the status message for the error, alerts the user with a popup. If
 * the issue is a recognized syntax error and the line and column numbers can
 * be found int he exception message, the cursor will be moved to that
 * position./*from w  ww  . jav a  2 s.c  o  m*/
 * 
 * @param throwable
 *          The error that occurred
 * @param operationDetailMessage
 *          A message specific to the operation that was running. This may be
 *          null
 * 
 * @return The message to be presented on the status line
 */
private String errorAlert(Throwable throwable, String operationDetailMessage) {
    String statusMessage;
    String alertMessage;
    String httpStatusMessage = null;
    String causeClass;
    String causeMessage;
    QueryExceptionHTTP httpExc = null;
    int[] lineAndColumn = new int[2];
    int whichSelectedTab = -1;
    JTextArea whichFocusJTextArea = null;

    if (throwable.getCause() != null) {
        causeClass = throwable.getCause().getClass().getName();
        causeMessage = throwable.getCause().getMessage();
    } else {
        causeClass = throwable.getClass().getName();
        causeMessage = throwable.getMessage();
    }

    if (operationDetailMessage != null) {
        alertMessage = operationDetailMessage + "\n\n";
    } else {
        alertMessage = "Error:";
    }

    alertMessage += causeClass + "\n" + causeMessage;

    statusMessage = causeMessage.trim().length() > 0 ? causeMessage : causeClass;

    if (throwable instanceof QueryExceptionHTTP) {
        httpExc = (QueryExceptionHTTP) throwable;

        httpStatusMessage = httpExc.getResponseMessage();
        if (httpStatusMessage == null || httpStatusMessage.trim().length() == 0) {
            try {
                httpStatusMessage = HttpStatus.getStatusText(httpExc.getResponseCode());
            } catch (Throwable lookupExc) {
                LOGGER.info("Cannot find message for returned HTTP code of " + httpExc.getResponseCode());
            }
        }
    }

    if (httpExc != null) {
        statusMessage += ": " + "Response Code: " + httpExc.getResponseCode()
                + (httpStatusMessage != null && httpStatusMessage.trim().length() > 0
                        ? " (" + httpStatusMessage + ")"
                        : "");

        JOptionPane.showMessageDialog(this,
                alertMessage + "\n\n" + "Response Code: " + httpExc.getResponseCode() + "\n"
                        + (httpStatusMessage != null ? httpStatusMessage : ""),
                "Error", JOptionPane.ERROR_MESSAGE);
    } else {
        JOptionPane.showMessageDialog(this, alertMessage, "Error", JOptionPane.ERROR_MESSAGE);
    }

    // Attempt to deal with a syntax error and positioning the cursor
    if (runningOperation == Operation.CREATE_MODEL) {
        // Assertions processing issue
        RiotException riotExc = null;
        Throwable nextThrowable = throwable;
        while (riotExc == null && nextThrowable != null) {
            if (nextThrowable instanceof RiotException) {
                riotExc = (RiotException) nextThrowable;
            } else {
                LOGGER.trace("Not a riot exception, another? " + throwable.getClass().toString() + "->"
                        + throwable.getCause());
                nextThrowable = nextThrowable.getCause();
            }
        }
        if (riotExc != null) {
            lineAndColumn = getSyntaxErrorLineColLocation(riotExc.getMessage().toLowerCase(), "line: ", ",",
                    "col: ", "]");
            whichSelectedTab = TAB_NUMBER_ASSERTIONS;
            whichFocusJTextArea = assertionsInput;
        } else {
            LOGGER.debug("No riot exception found so the caret cannot be positioned");
        }
    }
    if (runningOperation == Operation.EXECUTE_SPARQL) {
        // SPARQL processing issue
        QueryParseException queryParseExc = null;
        Throwable nextThrowable = throwable;
        while (queryParseExc == null && nextThrowable != null) {
            if (nextThrowable instanceof QueryParseException) {
                queryParseExc = (QueryParseException) nextThrowable;
            } else {
                LOGGER.trace("Not a query parse exception, another? " + throwable.getClass().toString() + "->"
                        + throwable.getCause());
                nextThrowable = nextThrowable.getCause();
            }
        }
        if (queryParseExc != null) {
            lineAndColumn = getSyntaxErrorLineColLocation(queryParseExc.getMessage().toLowerCase(), "at line ",
                    ",", ", column ", ".");
            whichSelectedTab = TAB_NUMBER_SPARQL;
            whichFocusJTextArea = sparqlInput;
        } else {
            LOGGER.debug("No query parse exception found so the caret cannot be positioned");
        }
    }

    if (lineAndColumn[0] > 0 && lineAndColumn[1] > 0) {
        LOGGER.debug("Attempt to set assertions caret to position (" + lineAndColumn[0] + "," + lineAndColumn[1]
                + ")");
        final int finalLineNumber = lineAndColumn[0] - 1;
        final int finalColumnNumber = lineAndColumn[1] - 1;
        final int finalWhichSelectedTab = whichSelectedTab;
        final JTextArea finalWhichFocusJTextArea = whichFocusJTextArea;
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                tabbedPane.setSelectedIndex(finalWhichSelectedTab);
                try {
                    finalWhichFocusJTextArea.setCaretPosition(
                            finalWhichFocusJTextArea.getLineStartOffset(finalLineNumber) + finalColumnNumber);
                    finalWhichFocusJTextArea.requestFocusInWindow();
                } catch (Throwable throwable) {
                    LOGGER.warn("Cannot set " + finalWhichFocusJTextArea.getName() + " carat position to ("
                            + finalLineNumber + "," + finalColumnNumber + ") on tab " + finalWhichSelectedTab,
                            throwable);
                }
            }
        });
    }

    return statusMessage;
}

From source file:no.norrs.launchpad.tasks.LaunchpadRepository.java

private Task[] processEndpoint(String url, HttpClient client) throws IOException {
    GetMethod method = new GetMethod(url);
    configureHttpMethod(method);/* www  .j  a v a2  s .c o  m*/
    client.executeMethod(method);

    int code = method.getStatusCode();
    if (code != HttpStatus.SC_OK) {
        throw new IOException(code == HttpStatus.SC_BAD_REQUEST ? method.getResponseBodyAsString()
                : ("HTTP " + code + " (" + HttpStatus.getStatusText(code) + ") " + method.getStatusText()));
    }

    BugTask bugTask = mapper.readValue(method.getResponseBodyAsStream(), BugTask.class);
    List<Bug> bugs = bugTask.getEntries();
    List<Task> tasks = new ArrayList<Task>();
    for (Bug bug : bugs) {
        tasks.add(new LaunchpadTask(bug));
    }
    LOG.debug(String.format("Tasks size: %s", tasks.size()));

    return tasks.toArray(new Task[] {});
}

From source file:no.norrs.launchpad.tasks.LaunchpadRepository.java

@Override
public CancellableConnection createCancellableConnection() {
    StringBuilder url = new StringBuilder((getUrl()));
    url.append("?ws.op=searchTasks");
    GetMethod method = new GetMethod(url.toString());

    return new HttpTestConnection<GetMethod>(method) {

        @Override//from  www  . ja  v a  2s . c  om
        public void doTest(GetMethod method) throws Exception {
            HttpClient client = getHttpClient();
            client.executeMethod(myMethod);

            int statusCode = myMethod.getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new IOException("Can't reach resource: " + statusCode + " ("
                        + HttpStatus.getStatusText(statusCode) + ")");
            }
            Task[] results = getIssues(null, 1, 0);
            if (results.length < 1)
                throw new IOException("No results fetched, sure this is correct endpoint?");
        }
    };
}

From source file:org.alfresco.repo.publishing.slideshare.SlideShareConnectorImpl.java

public InputStream sendMessage(String url, Map<String, String> parameters)
        throws IOException, SlideShareErrorException {
    PostMethod method = new PostMethod(url);
    method.addParameter("api_key", this.apiKey);
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        method.addParameter(entry.getKey(), entry.getValue());
    }//from  w  w w .  j a va 2  s .  c  o m
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    method.addParameter("ts", ts);
    method.addParameter("hash", hash);
    logger.debug("Sending POST message to " + method.getURI().getURI() + " with parameters "
            + Arrays.toString(method.getParameters()));
    int statusCode = httpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.debug("Server replied with a " + statusCode + " HTTP status code ("
                + HttpStatus.getStatusText(statusCode) + ")");
        throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(method.getResponseBodyAsString());
    }
    InputStream result = new ByteArrayInputStream(method.getResponseBody());
    method.releaseConnection();
    return result;
}