Example usage for java.net HttpURLConnection HTTP_BAD_METHOD

List of usage examples for java.net HttpURLConnection HTTP_BAD_METHOD

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_BAD_METHOD.

Prototype

int HTTP_BAD_METHOD

To view the source code for java.net HttpURLConnection HTTP_BAD_METHOD.

Click Source Link

Document

HTTP Status-Code 405: Method Not Allowed.

Usage

From source file:com.adaptris.http.legacy.GenericConsumer.java

/**
 * @see HttpConsumerImp#handleRequest(HttpSession)
 *///from w ww  .jav  a 2s.co m
@Override
@SuppressWarnings("deprecation")
protected AdaptrisMessage handleRequest(HttpSession httpSession)
        throws IOException, IllegalStateException, HttpException {

    HttpRequest request = httpSession.getRequestLine();
    HttpMessage message = httpSession.getRequestMessage();
    HttpHeaders header = message.getHeaders();

    HttpResponse response = httpSession.getResponseLine();

    AdaptrisMessage result = null;
    OutputStream out = null;
    try {
        // By default we only accept post methods
        if (request.getMethod().equalsIgnoreCase(getMethod())) {
            response.setResponseCode(HttpURLConnection.HTTP_OK);
            response.setResponseMessage("OK");
            if (getEncoder() != null) {
                result = getEncoder().readMessage(message);
            } else {
                result = defaultIfNull(getMessageFactory()).newMessage();
                out = result.getOutputStream();
                StreamUtil.copyStream(message.getInputStream(), out, header.getContentLength());
            }
            result.addObjectHeader(CoreConstants.HTTP_SESSION_KEY, httpSession);
            addParamsAsMetadata(httpSession, result);
        } else {
            response.setResponseCode(HttpURLConnection.HTTP_BAD_METHOD);
            response.setResponseMessage("Method Not Allowed");
        }
    } catch (CoreException e) {
        throw new HttpException(e);
    } finally {
        IOUtils.closeQuietly(out);
    }

    return result;
}

From source file:org.cellprofiler.subimager.ImageWriterHandler.java

public void handle(HttpExchange exchange) throws IOException {
    if (!exchange.getRequestMethod().equals("POST")) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_METHOD,
                "<html><body>writeimage only accepts HTTP post</body></html>");
        return;//  www  . ja v a2  s  . c om
    }
    final String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
    if (contentType == null) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>No Content-type request header</body></html>");
        return;
    }
    if (!contentType.startsWith(MULTIPART_FORM_DATA)) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>Content type must be " + MULTIPART_FORM_DATA + ".</body></html>");
        return;
    }
    int idx = contentType.indexOf(BOUNDARY_EQUALS, MULTIPART_FORM_DATA.length());
    if (idx == -1) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>Did not find boundary identifier in multipart/form-data content type.</body></html>");
        return;
    }
    final String contentEncoding = exchange.getRequestHeaders().getFirst("Content-Encoding");
    String contentLengthString = exchange.getRequestHeaders().getFirst("Content-Length");
    if (contentLengthString == null) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>No Content-Length request header</body></html>");
        return;
    }
    try {
        Integer.parseInt(contentLengthString);
    } catch (NumberFormatException e) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, String
                .format("<html><body>Content length was not a number: %s</body></html>", contentLengthString));
        return;
    }
    final int contentLength = Integer.parseInt(contentLengthString);
    final InputStream requestBodyStream = exchange.getRequestBody();
    FileUpload upload = new FileUpload();
    FileItemIterator fileItemIterator;
    String omeXML = null;
    URI uri = null;
    int index = 0;
    NDImage ndimage = null;
    String compression = DEFAULT_COMPRESSION;
    try {
        fileItemIterator = upload.getItemIterator(new RequestContext() {

            public String getCharacterEncoding() {
                return contentEncoding;
            }

            public String getContentType() {
                return contentType;
            }

            public int getContentLength() {
                return contentLength;
            }

            public InputStream getInputStream() throws IOException {
                return requestBodyStream;
            }
        });
        while (fileItemIterator.hasNext()) {
            FileItemStream fis = fileItemIterator.next();
            String name = fis.getFieldName();

            if (name.equals(NAME_IMAGE)) {
                String imageContentType = fis.getContentType();
                if (imageContentType == null) {
                    reportError(exchange, HttpURLConnection.HTTP_UNSUPPORTED_TYPE,
                            "<html><body>Image form-data field must have a content type.</body></html>");
                    return;
                }
                try {
                    InputStream is = SubimagerUtils.getInputStream(exchange, fis);
                    if (is == null)
                        return;
                    ndimage = NDImage.decode(is);
                } catch (MalformedStreamException e) {
                    reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                            "<html><body>Failed to read body for part, " + name + ".</body></html>");
                } catch (IOException e) {
                    reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                            "<html><body>Failed to read multipart body data</body></html>");
                    return;
                } catch (org.cellprofiler.subimager.NDImage.FormatException e) {
                    reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                            "<html><body>Image data was not in correct format: " + e.getMessage()
                                    + "</body></html>");
                    return;
                }
            } else {
                String partDataString = SubimagerUtils.readFully(exchange, fis);
                if (partDataString == null)
                    return;
                if (name.equals(NAME_INDEX)) {
                    try {
                        index = Integer.parseInt(partDataString);
                    } catch (NumberFormatException e) {
                        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                                "<html><body>Index form-data field must be a number: " + partDataString
                                        + ".</body></html>");
                        return;
                    }
                } else if (name.equals(NAME_OMEXML)) {
                    omeXML = partDataString;
                } else if (name.equals(NAME_URL)) {
                    try {
                        uri = new URI(partDataString);
                    } catch (URISyntaxException e) {
                        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                                "<html><body>Improperly formatted URL: " + partDataString + ".</body></html>");
                        return;
                    }
                } else if (name.equals(NAME_COMPRESSION)) {
                    compression = partDataString;
                }
            }
        }
        if (ndimage == null) {
            reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                    "<html><body>Request did not have an image part</body></html>");
            return;
        }
        if (uri == null) {
            reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                    "<html><body>Request did not have a URL part</body></html>");
            return;
        }
        if (omeXML == null) {
            reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                    "<html><body>Request did not have an omexml part</body></html>");
            return;
        }
        writeImage(exchange, ndimage, uri, omeXML, index, compression);
    } catch (FileUploadException e) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, String
                .format("<html><body>Parsing error in multipart message: %s</body></html>", e.getMessage()));
        return;
    }
}

From source file:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java

/**
 * @param uri// ww  w  . j av a  2s.co  m
 * @param parameters
 * @return
 */
public boolean fetchPageContent(String uri, List<NameValuePair> parameters) {
    // Set login, ssl, port, host etc;
    applyConfig();

    mErrorText = "";
    mErrorTextId = -1;
    mError = false;
    mBytes = new byte[0];
    if (!uri.startsWith("/")) {
        uri = "/".concat(uri);
    }

    HttpURLConnection conn = null;
    try {
        if (mProfile.getSessionId() != null)
            parameters.add(new BasicNameValuePair("sessionid", mProfile.getSessionId()));
        URL url = new URL(buildUrl(uri, parameters));
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(mConnectionTimeoutMillis);
        if (DreamDroid.featurePostRequest())
            conn.setRequestMethod("POST");
        setAuth(conn);
        if (conn.getResponseCode() != 200) {
            if (conn.getResponseCode() == HttpURLConnection.HTTP_BAD_METHOD
                    && mRememberedReturnCode != HttpURLConnection.HTTP_BAD_METHOD) {
                // Method not allowed, the target device either can't handle
                // POST or GET requests (old device or Anti-Hijack enabled)
                DreamDroid.setFeaturePostRequest(!DreamDroid.featurePostRequest());
                conn.disconnect();
                mRememberedReturnCode = HttpURLConnection.HTTP_BAD_METHOD;
                return fetchPageContent(uri, parameters);
            }
            if (conn.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED
                    && mRememberedReturnCode != HttpURLConnection.HTTP_PRECON_FAILED) {
                createSession();
                conn.disconnect();
                mRememberedReturnCode = HttpURLConnection.HTTP_PRECON_FAILED;
                return fetchPageContent(uri, parameters);
            }
            mRememberedReturnCode = 0;
            Log.e(LOG_TAG, Integer.toString(conn.getResponseCode()));
            switch (conn.getResponseCode()) {
            case HttpURLConnection.HTTP_UNAUTHORIZED:
                mErrorTextId = R.string.auth_error;
                break;
            default:
                mErrorTextId = -1;
            }
            mErrorText = conn.getResponseMessage();
            mError = true;
            return false;
        }

        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int read = 0;
        int bufSize = 512;
        byte[] buffer = new byte[bufSize];
        while ((read = bis.read(buffer)) != -1) {
            baf.append(buffer, 0, read);
        }

        mBytes = baf.toByteArray();
        if (DreamDroid.dumpXml())
            dumpToFile(url);
        return true;

    } catch (MalformedURLException e) {
        mError = true;
        mErrorTextId = R.string.illegal_host;
    } catch (UnknownHostException e) {
        mError = true;
        mErrorText = null;
        mErrorTextId = R.string.host_not_found;
    } catch (ProtocolException e) {
        mError = true;
        mErrorText = e.getLocalizedMessage();
    } catch (ConnectException e) {
        mError = true;
        mErrorTextId = R.string.host_unreach;
    } catch (IOException e) {
        e.printStackTrace();
        mError = true;
        mErrorText = e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
        if (mError)
            if (mErrorText == null)
                mErrorText = "Error text is null";
        Log.e(LOG_TAG, mErrorText);
    }

    return false;
}

From source file:com.datos.vfs.provider.http.HttpFileObject.java

/**
 * Determines the type of this file.  Must not return null.  The return
 * value of this method is cached, so the implementation can be expensive.
 *///  ww  w .ja va 2 s  .  c  o  m
@Override
protected FileType doGetType() throws Exception {
    // Use the HEAD method to probe the file.
    final int status = this.getHeadMethod().getStatusCode();
    if (status == HttpURLConnection.HTTP_OK
            || status == HttpURLConnection.HTTP_BAD_METHOD /* method is bad, but resource exist */) {
        return FileType.FILE;
    } else if (status == HttpURLConnection.HTTP_NOT_FOUND || status == HttpURLConnection.HTTP_GONE) {
        return FileType.IMAGINARY;
    } else {
        throw new FileSystemException("vfs.provider.http/head.error", getName(), Integer.valueOf(status));
    }
}

From source file:org.ScripterRon.JavaBitcoin.RpcHandler.java

/**
 * Handle an HTTP request//  www  .j  av  a 2  s  .c om
 *
 * @param       exchange            HTTP exchange
 * @throws      IOException         Error detected while handling the request
 */
@Override
public void handle(HttpExchange exchange) throws IOException {
    try {
        int responseCode;
        String responseBody;
        //
        // Get the HTTP request
        //
        InetSocketAddress requestAddress = exchange.getRemoteAddress();
        String requestMethod = exchange.getRequestMethod();
        Headers requestHeaders = exchange.getRequestHeaders();
        String contentType = requestHeaders.getFirst("Content-Type");
        Headers responseHeaders = exchange.getResponseHeaders();
        log.debug(String.format("%s request received from %s", requestMethod, requestAddress.getAddress()));
        if (!rpcAllowIp.contains(requestAddress.getAddress())) {
            responseCode = HttpURLConnection.HTTP_UNAUTHORIZED;
            responseBody = "Your IP address is not authorized to access this server";
            responseHeaders.set("Content-Type", "text/plain");
        } else if (!exchange.getRequestMethod().equals("POST")) {
            responseCode = HttpURLConnection.HTTP_BAD_METHOD;
            responseBody = String.format("%s requests are not supported", exchange.getRequestMethod());
            responseHeaders.set("Content-Type", "text/plain");
        } else if (contentType == null || !contentType.equals("application/json-rpc")) {
            responseCode = HttpURLConnection.HTTP_BAD_REQUEST;
            responseBody = "Content type must be application/json-rpc";
            responseHeaders.set("Content-Type", "text/plain");
        } else {
            responseBody = processRequest(exchange);
            responseCode = HttpURLConnection.HTTP_OK;
            responseHeaders.set("Content-Type", "application/json-rpc");
        }
        //
        // Return the HTTP response
        //
        responseHeaders.set("Cache-Control", "no-cache, no-store, must-revalidate, private");
        responseHeaders.set("Server", "JavaBitcoin");
        byte[] responseBytes = responseBody.getBytes("UTF-8");
        exchange.sendResponseHeaders(responseCode, responseBytes.length);
        try (OutputStream out = exchange.getResponseBody()) {
            out.write(responseBytes);
        }
        log.debug(String.format("RPC request from %s completed", requestAddress.getAddress()));
    } catch (IOException exc) {
        log.error("Unable to process RPC request", exc);
        throw exc;
    }
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private double getAvail(int code) {
    // There are too many options to list everything that is
    // successful. So, instead we are going to call out the
    // things that should be considered failure, everything else
    // is OK./*  w w  w.  j  a  v a2 s  .  c  o m*/
    switch (code) {
    case HttpURLConnection.HTTP_BAD_REQUEST:
    case HttpURLConnection.HTTP_FORBIDDEN:
    case HttpURLConnection.HTTP_NOT_FOUND:
    case HttpURLConnection.HTTP_BAD_METHOD:
    case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
    case HttpURLConnection.HTTP_CONFLICT:
    case HttpURLConnection.HTTP_PRECON_FAILED:
    case HttpURLConnection.HTTP_ENTITY_TOO_LARGE:
    case HttpURLConnection.HTTP_REQ_TOO_LONG:
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
    case HttpURLConnection.HTTP_UNAVAILABLE:
    case HttpURLConnection.HTTP_VERSION:
    case HttpURLConnection.HTTP_BAD_GATEWAY:
    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
        return Metric.AVAIL_DOWN;
    default:
    }

    if (hasCredentials()) {
        if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            return Metric.AVAIL_DOWN;
        }
    }

    return Metric.AVAIL_UP;
}

From source file:org.rhq.modules.plugins.jbossas7.ASConnection.java

/**
 * Execute an operation against the domain api. This method is doing the
 * real work by talking to the remote server and sending JSON data, that
 * is obtained by serializing the operation.
 *
 * Please do not use this API , but execute()
 * @return JsonNode that describes the result
 * @param operation an Operation that should be run on the domain controller
 * @see #execute(org.rhq.modules.plugins.jbossas7.json.Operation)
 * @see #execute(org.rhq.modules.plugins.jbossas7.json.Operation, boolean)
 * @see #executeComplex(org.rhq.modules.plugins.jbossas7.json.Operation)
 *//*from   w  w w  .j a  va  2 s. co m*/
public JsonNode executeRaw(Operation operation) {

    InputStream inputStream = null;
    BufferedReader br = null;
    InputStream es = null;
    HttpURLConnection conn = null;
    long t1 = System.currentTimeMillis();
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "application/json");
        conn.addRequestProperty("Accept", "application/json");
        conn.setConnectTimeout(10 * 1000); // 10s
        conn.setReadTimeout(10 * 1000); // 10s

        if (conn.getReadTimeout() != 10 * 1000)
            log.warn("JRE uses a broken timeout mechanism - nothing we can do");

        OutputStream out = conn.getOutputStream();

        String json_to_send = mapper.writeValueAsString(operation);

        //check for spaces in the path which the AS7 server will reject. Log verbose error and
        // generate failure indicator.
        if ((operation != null) && (operation.getAddress() != null)
                && operation.getAddress().getPath() != null) {
            if (containsSpaces(operation.getAddress().getPath())) {
                Result noResult = new Result();
                String outcome = "- Path '" + operation.getAddress().getPath()
                        + "' in invalid as it cannot contain spaces -";
                if (verbose) {
                    log.error(outcome);
                }
                noResult.setFailureDescription(outcome);
                noResult.setOutcome("failure");
                JsonNode invalidPathResult = mapper.valueToTree(noResult);
                return invalidPathResult;
            }
        }

        if (verbose) {
            log.info("Json to send: " + json_to_send);
        }

        mapper.writeValue(out, operation);

        out.flush();
        out.close();

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = conn.getInputStream();
        } else {
            inputStream = conn.getErrorStream();
        }

        if (inputStream != null) {

            br = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }

            String outcome;
            JsonNode operationResult;
            if (builder.length() > 0) {
                outcome = builder.toString();
                operationResult = mapper.readTree(outcome);
                if (verbose) {
                    ObjectMapper om2 = new ObjectMapper();
                    om2.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
                    String tmp = om2.writeValueAsString(operationResult);
                    log.info(tmp);
                }
            } else {
                outcome = "- no response from server -";
                Result noResult = new Result();
                noResult.setFailureDescription(outcome);
                noResult.setOutcome("failure");
                operationResult = mapper.valueToTree(noResult);
            }
            return operationResult;
        } else {
            //if not properly authorized sends plugin exception for visual indicator in the ui.
            if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED
                    || responseCode == HttpURLConnection.HTTP_BAD_METHOD) {
                if (log.isDebugEnabled()) {
                    log.debug("[" + url + "] Response was empty and response code was " + responseCode + " "
                            + conn.getResponseMessage() + ".");
                }
                throw new InvalidPluginConfigurationException(
                        "Credentials for plugin to connect to AS7 management interface are invalid. Update Connection Settings with valid credentials.");
            } else {
                log.error("[" + url + "] Response was empty and response code was " + responseCode + " "
                        + conn.getResponseMessage() + ".");
            }
        }
    } catch (IllegalArgumentException iae) {
        log.error("Illegal argument " + iae);
        log.error("  for input " + operation);
    } catch (SocketTimeoutException ste) {
        log.error("Request to AS timed out " + ste.getMessage());
        conn.disconnect();
        Result failure = new Result();
        failure.setFailureDescription(ste.getMessage());
        failure.setOutcome("failure");
        failure.setRhqThrowable(ste);

        JsonNode ret = mapper.valueToTree(failure);
        return ret;

    } catch (IOException e) {
        log.error("Failed to get data: " + e.getMessage());

        //the following code is in place to help keep-alive http connection re-use to occur.
        if (conn != null) {//on error conditions it's still necessary to read the response so JDK knows can reuse
            //the http connections behind the scenes.
            es = conn.getErrorStream();
            if (es != null) {
                BufferedReader dr = new BufferedReader(new InputStreamReader(es));
                String ignore = null;
                try {
                    while ((ignore = dr.readLine()) != null) {
                        //already reported error. just empty stream.
                    }
                    es.close();
                } catch (IOException e1) {
                    // ignore
                }
            }
        }

        Result failure = new Result();
        failure.setFailureDescription(e.getMessage());
        failure.setOutcome("failure");
        failure.setRhqThrowable(e);

        JsonNode ret = mapper.valueToTree(failure);
        return ret;

    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        if (es != null) {
            try {
                es.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        long t2 = System.currentTimeMillis();
        PluginStats stats = PluginStats.getInstance();
        stats.incrementRequestCount();
        stats.addRequestTime(t2 - t1);
    }

    return null;
}

From source file:org.codehaus.mojo.mrm.servlet.FileSystemServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String httpMethodOverride = req.getHeader("X-HTTP-Method-Override");

    if ("PUT".equals(httpMethodOverride))
        _doPut(req, resp);/*from  www.  j ava  2s.com*/
    else if ("DELETE".equals(httpMethodOverride))
        _doDelete(req, resp);
    else
        resp.sendError(HttpURLConnection.HTTP_BAD_METHOD);

}

From source file:org.codehaus.mojo.mrm.servlet.FileSystemServlet.java

/**
 * {@inheritDoc}/*ww w  .ja  v  a  2  s  .c  o m*/
 */
protected void _doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String path = req.getPathInfo();
    boolean outcome = false;

    if (path.endsWith("/")) {
        outcome = createFile(req, resp, path, true);
    } else {
        outcome = createFile(req, resp, path, false);
    }

    if (!outcome)
        resp.sendError(HttpURLConnection.HTTP_BAD_METHOD);
}

From source file:org.codehaus.mojo.mrm.servlet.FileSystemServlet.java

private boolean createFile(HttpServletRequest req, HttpServletResponse resp, String path, boolean isDirectory)
        throws IOException {
    if (path.startsWith("/")) {
        path = path.substring(1);/*from   w  w  w  .ja va2 s .c  o m*/
    }

    String[] parts = path.split("/");
    if (parts.length == 0) {
        resp.sendError(HttpURLConnection.HTTP_BAD_METHOD);
        return true;
    }

    String name = parts[parts.length - 1];
    if (StringUtils.isEmpty(name)) {
        resp.sendError(HttpURLConnection.HTTP_BAD_METHOD);
        return true;
    }

    // find parent
    DirectoryEntry parent = fileSystem.getRoot();
    for (int i = 0; i < parts.length - 1; i++) {
        parent = new DefaultDirectoryEntry(fileSystem, parent, parts[i]);
    }

    // create file or directory
    ServletInputStream inputStream = null;
    try {
        if (isDirectory) {
            DirectoryEntry dir = fileSystem.mkdir(parent, name);
            if (dir != null) {
                resp.setStatus(HttpURLConnection.HTTP_OK);
                return true;
            }
        } else {
            inputStream = req.getInputStream();
            FileEntry put = fileSystem.put(parent, name, inputStream);
            if (put != null) {
                resp.setStatus(HttpURLConnection.HTTP_OK);
                return true;
            }
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return false;
}