Example usage for java.net HttpURLConnection HTTP_NOT_IMPLEMENTED

List of usage examples for java.net HttpURLConnection HTTP_NOT_IMPLEMENTED

Introduction

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

Prototype

int HTTP_NOT_IMPLEMENTED

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

Click Source Link

Document

HTTP Status-Code 501: Not Implemented.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection con = (HttpURLConnection) new URL("http://www.google.coom").openConnection();
    con.setRequestMethod("HEAD");
    System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_NOT_IMPLEMENTED);
}

From source file:org.wso2.carbon.registry.app.ResourceServlet.java

/**
 * Logic that will be executed for a get request.
 *
 * @param request  the HTTP Servlet request.
 * @param response the HTTP Servlet response.
 *
 * @throws IOException if an error occurred.
 *//* w  ww  .  ja v a  2 s. c om*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        String uri = request.getRequestURI();
        int idx = uri.indexOf("resource");
        String path = uri.substring(idx + 8);
        if (path == null) {
            String msg = "Could not get the resource content. Path is not specified.";
            log.error(msg);
            response.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
            return;
        }

        Resource resource;
        try {
            UserRegistry registry = Utils.getRegistry(request);
            try {
                path = new URI(path).normalize().toString();
            } catch (URISyntaxException e) {
                log.error("Unable to normalize requested resource path: " + path, e);
            }
            String decodedPath = URLDecoder.decode(path, RegistryConstants.DEFAULT_CHARSET_ENCODING);

            CurrentSession.setUserRealm(registry.getUserRealm());
            CurrentSession.setUser(registry.getUserName());
            try {
                if (!AuthorizationUtils.authorize(
                        RegistryUtils.getAbsolutePath(registry.getRegistryContext(), decodedPath),
                        ActionConstants.GET)) {
                    response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
                    response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
                    return;
                }
                resource = registry.get(decodedPath);
            } finally {
                CurrentSession.removeUserRealm();
                CurrentSession.removeUser();
            }
        } catch (AuthorizationFailedException e) {
            log.error(e.getMessage());
            response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED);
            response.setHeader("WWW-Authenticate", "Basic realm=\"WSO2-Registry\"");
            return;
        } catch (RegistryException e) {
            String msg = "Error retrieving the resource " + path + ". " + e.getMessage();
            log.error(msg, e);
            throw e;
        }

        if (resource instanceof Collection) {
            String msg = "Could not get the resource content. Path " + path + " refers to a collection.";
            log.error(msg);
            response.setStatus(HttpURLConnection.HTTP_NOT_IMPLEMENTED);
            return;
        }

        // date based conditional get
        long ifModifiedSinceValue = request.getDateHeader("If-Modified-Since");
        long lastModifiedValue = resource.getLastModified().getTime();
        if (ifModifiedSinceValue > 0) {
            // convert the time values from milliseconds to seconds
            ifModifiedSinceValue /= 1000;
            lastModifiedValue /= 1000;

            /* condition to check we have latest updates in terms of dates */
            if (ifModifiedSinceValue >= lastModifiedValue) {
                /* no need to response with data */
                response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED);
                return;
            }
        }
        response.setDateHeader("Last-Modified", lastModifiedValue);

        // eTag based conditional get
        String ifNonMatchValue = request.getHeader("if-none-match");
        String currentETag = Utils.calculateEntityTag(resource);
        if (ifNonMatchValue != null) {
            if (ifNonMatchValue.equals(currentETag)) {
                /* the version is not modified */
                response.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED);
                return;
            }
        }
        response.setHeader("ETag", currentETag);

        if (resource.getMediaType() != null && resource.getMediaType().length() > 0) {
            response.setContentType(resource.getMediaType());
        } else {
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + RegistryUtils.getResourceName(path));
            response.setContentType("application/download");
        }

        InputStream contentStream = null;
        if (resource.getContent() != null) {
            contentStream = resource.getContentStream();
        }
        if (contentStream != null) {

            try {
                ServletOutputStream servletOutputStream = response.getOutputStream();
                byte[] contentChunk = new byte[RegistryConstants.DEFAULT_BUFFER_SIZE];
                int byteCount;
                while ((byteCount = contentStream.read(contentChunk)) != -1) {
                    servletOutputStream.write(contentChunk, 0, byteCount);
                }

                response.flushBuffer();
                servletOutputStream.flush();

            } finally {
                contentStream.close();
            }

        } else {
            Object content = resource.getContent();
            if (content != null) {

                if (content instanceof byte[]) {
                    ServletOutputStream servletOutputStream = response.getOutputStream();
                    servletOutputStream.write((byte[]) content);
                    response.flushBuffer();
                    servletOutputStream.flush();
                } else {
                    PrintWriter writer = response.getWriter();
                    writer.write(content.toString());
                    writer.flush();
                }
            }
        }

        resource.discard();

    } catch (RegistryException e) {
        String msg = "Failed to get resource content. " + e.getMessage();
        log.error(msg, e);
        response.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:org.opendaylight.lispflowmapping.neutron.LispNeutronPortHandler.java

@Override
public int canUpdatePort(NeutronPort delta, NeutronPort original) {
    // TODO Change of Fixed IPs are not allowed as we are storing ports by
    // fixed IPs for now

    if (original.getFixedIPs().equals(original.getFixedIPs())) {
        LOG.info("Neutron canUpdatePort : Port name: " + original.getName() + " Port Fixed IP: "
                + (original.getFixedIPs() != null ? original.getFixedIPs().get(0) : "No Fixed IP assigned")
                + "New Port Fixed IP: "
                + (delta.getFixedIPs() != null ? delta.getFixedIPs().get(0) : "No Fixed IP assigned"));
        LOG.debug("Neutron canUpdatePort : original" + original.toString() + " delta : " + delta.toString());

        return HttpURLConnection.HTTP_OK;
    }//from   w  ww.  j  av a 2  s  .  co  m
    return HttpURLConnection.HTTP_NOT_IMPLEMENTED;
}

From source file:eionet.cr.util.URLUtil.java

/**
 * Connect to the URL and check if it exists at the remote end. Local identifiers are removed (the part after the '#') before
 * connecting. The method returns true (i.e. URL is considered as "not existing") if the given URL is malformed, or its
 * connection throws a {@link UnknownHostException} or sends a HTTP code that is 501 or 505 or anything in the range of 400
 * to 499. The latter range, however, is ignored if the given boolean input is is true (meaning a client error is OK).
 *
 * @param urlStr the URL to check./*from w ww. ja va2s  .c  o  m*/
 * @param clientErrorOk If true, then a response code in the range of 400 to 499 is considered OK.
 * @return As described above.
 */
public static boolean isNotExisting(String urlStr, boolean clientErrorOk) {

    int responseCode = -1;
    IOException ioe = null;
    URLConnection urlConnection = null;
    try {
        URL url = new URL(StringUtils.substringBefore(urlStr, "#"));
        urlConnection = escapeIRI(url).openConnection();
        urlConnection.setRequestProperty("Connection", "close");
        responseCode = ((HttpURLConnection) urlConnection).getResponseCode();
    } catch (IOException e) {
        ioe = e;
    } finally {
        URLUtil.disconnect(urlConnection);
    }

    return ioe instanceof MalformedURLException || ioe instanceof UnknownHostException
            || (!clientErrorOk && isClientError(responseCode))
            || responseCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED
            || responseCode == HttpURLConnection.HTTP_VERSION;
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitResetTest.java

@Test
public void testResetNotImplemented() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    String projectName = getMethodName();
    JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());

    JSONObject testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "hello");

    JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);

    WebRequest request = getPostGitIndexRequest(gitIndexUri, ResetType.KEEP);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_IMPLEMENTED, response.getResponseCode());

    request = getPostGitIndexRequest(gitIndexUri, ResetType.MERGE);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_IMPLEMENTED, response.getResponseCode());

    request = getPostGitIndexRequest(gitIndexUri, ResetType.SOFT);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_IMPLEMENTED, response.getResponseCode());
}

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./*from   w w  w  .  j  av  a 2s  . c om*/
    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:com.scvngr.levelup.core.net.LevelUpResponseTest.java

/**
 * Tests {@link com.scvngr.levelup.core.net.LevelUpResponse#mapStatus(int, String)}.
 *//*from  w w  w.jav  a 2 s  . c  o  m*/
@SmallTest
public void testMapStatusHttp_errorCodeUpgrade() {
    assertEquals(LevelUpStatus.UPGRADE,
            LevelUpResponse.mapStatus(HttpURLConnection.HTTP_NOT_IMPLEMENTED, SERVER_LEVELUP_PLATFORM));
}

From source file:com.scvngr.levelup.core.net.LevelUpResponseTest.java

/**
 * Tests {@link LevelUpResponse#mapStatus(int, String)}. Responses not coming from LevelUp
 * Platform should be treated as generic errors rather than upgrade-required messages.
 *///from www. j a v a2 s.  c  om
@SmallTest
public void testMapStatusHttp_errorCodeUpgrade_notFromLevelUp() {
    assertEquals(LevelUpStatus.ERROR_SERVER,
            LevelUpResponse.mapStatus(HttpURLConnection.HTTP_NOT_IMPLEMENTED, SERVER_NOT_LEVELUP_PLATFORM));
}

From source file:org.intermine.webservice.client.util.HttpConnection.java

/**
 * Handles an error response received while executing a service request.
 * Throws a {@link ServiceException} or one of its subclasses, depending on
 * the failure conditions.//from  w w w.  j ava  2  s . c om
 *
 * @throws ServiceException exception describing the failure.
 * @throws IOException error reading the error response from the
 *         service.
 */
protected void handleErrorResponse() throws IOException {

    String message = executedMethod.getResponseBodyAsString();
    try {
        JSONObject jo = new JSONObject(message);
        message = jo.getString("error");
    } catch (JSONException e) {
        // Pass
    }

    switch (executedMethod.getStatusCode()) {

    case HttpURLConnection.HTTP_NOT_FOUND:
        throw new ResourceNotFoundException(this);

    case HttpURLConnection.HTTP_BAD_REQUEST:
        if (message != null) {
            throw new BadRequestException(message);
        } else {
            throw new BadRequestException(this);
        }
    case HttpURLConnection.HTTP_FORBIDDEN:
        if (message != null) {
            throw new ServiceForbiddenException(message);
        } else {
            throw new ServiceForbiddenException(this);
        }
    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
        throw new NotImplementedException(this);

    case HttpURLConnection.HTTP_INTERNAL_ERROR:
        if (message != null) {
            throw new InternalErrorException(message);
        } else {
            throw new InternalErrorException(this);
        }
    case HttpURLConnection.HTTP_UNAVAILABLE:
        throw new ServiceUnavailableException(this);

    default:
        if (message != null) {
            throw new ServiceException(message);
        } else {
            throw new ServiceException(this);
        }
    }
}

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

/**
 * Write the image plane to the given uri
 * //from  w  w  w .j a  va  2 s  . c om
 * @param exchange the HttpExchange for the connection
 * @param ndimage the image to write
 * @param uri the file URI to write to (must be a file URI currently)
 * @param omeXML the OME-XML metadata for the plane
 * @param index the planar index of the plane being written to the file. Note that the indices must be written in order and that an index of 0 will truncate the file.
 * @param compression the compression method to be used
 * @throws IOException
 */
private void writeImage(HttpExchange exchange, NDImage ndimage, URI uri, String omeXML, int index,
        String compression) throws IOException {
    if (!uri.getScheme().equals("file")) {
        reportError(exchange, HttpURLConnection.HTTP_NOT_IMPLEMENTED,
                "<html><body>This server currently only supports the file: protocol, url=" + uri.toString()
                        + "</body></html>");
        return;
    }
    File outputFile = new File(uri);
    if ((index == 0) && outputFile.exists()) {
        outputFile.delete();
    }
    IMetadata metadata = null;
    try {
        ServiceFactory factory;
        factory = new ServiceFactory();
        OMEXMLService service = factory.getInstance(OMEXMLService.class);
        metadata = service.createOMEXMLMetadata(omeXML);
    } catch (DependencyException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>Configuration error: could not create OMEXML service - check for missing omexml libraries</body></html>");
        return;
    } catch (ServiceException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>Possible OME-XML parsing error: " + e.getMessage() + "</body></html>");
        return;
    }
    ImageWriter writer = new ImageWriter();
    writer.setMetadataRetrieve(metadata);
    try {
        writer.setId(outputFile.getAbsolutePath());
    } catch (IOException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>Failed to open output file " + outputFile.getAbsolutePath() + "</body></html>");
        return;
    } catch (FormatException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>Format exception when opening output file: " + e.getMessage() + "</body></html>");
        return;
    }
    PixelType pixelType = metadata.getPixelsType(0);
    if (SUPPORTED_PIXEL_TYPES.indexOf(pixelType) == -1) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>Unsupported pixel type: " + pixelType.getValue() + "</body></html>");
        return;
    }
    boolean toBigEndian = metadata.getPixelsBinDataBigEndian(0, 0);
    writer.setInterleaved(true);
    List<String> compressionTypes = Arrays.asList(writer.getCompressionTypes());
    try {
        if (compression == DEFAULT_COMPRESSION) {
            for (String possibleCompression : PREFERRED_COMPRESSION) {
                if (compressionTypes.indexOf(possibleCompression) != -1) {
                    //writer.setCompression(possibleCompression);
                    break;
                }
            }
        } else {
            if (compressionTypes.indexOf(compression) == -1) {
                reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                        "<html><body>Unsupported compression type: " + compression + "</body></html>");
                return;
            }
            writer.setCompression(compression);
        }
    } catch (FormatException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>Error when setting compression type: " + e.getMessage() + "</body></html>");
        return;
    }
    byte[] buffer = convertImage(ndimage, pixelType, toBigEndian);
    try {
        writer.saveBytes(index, buffer);
        writer.close();
    } catch (IOException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>An I/O error prevented the server from writing the image: " + e.getMessage()
                        + "</body></html>");
        return;
    } catch (FormatException e) {
        reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                "<html><body>The imaging library failed to write the image because of a format error: "
                        + e.getMessage() + "</body></html>");
        return;
    }
    String html = String.format("<html><body>%s successfully written</body></html>",
            StringEscapeUtils.escapeHtml(outputFile.getAbsolutePath()));
    reportError(exchange, HttpURLConnection.HTTP_OK, html);
}