Example usage for java.net HttpURLConnection HTTP_BAD_REQUEST

List of usage examples for java.net HttpURLConnection HTTP_BAD_REQUEST

Introduction

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

Prototype

int HTTP_BAD_REQUEST

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

Click Source Link

Document

HTTP Status-Code 400: Bad Request.

Usage

From source file:rapture.server.ArgumentParser.java

public static <T> T parsePayload(String json, Class<T> tClass) {
    final int errorCode = HttpURLConnection.HTTP_BAD_REQUEST;

    try {//from   w w  w .  j  a v a  2s .c  o m
        return JacksonUtilChecked.objectFromJson(json, tClass);
    } catch (UnrecognizedPropertyException e) {
        List<String> references = getReferences(e);
        if (references.size() > 1) {
            String referencesString = StringUtils.join(references.subList(0, references.size()), "->");
            throw RaptureExceptionFactory.create(errorCode,
                    String.format("Bad value for argument \"%s\". Child field \"%s\" not recognized.",
                            references.get(0), referencesString),
                    e);
        } else {
            throw RaptureExceptionFactory.create(errorCode, String.format(
                    "Unrecognized parameter \"%s\" passed to API call", e.getUnrecognizedPropertyName()), e);
        }
    } catch (JsonMappingException e) {
        List<String> references = getReferences(e);
        if (references.size() > 1) {
            String referencesString = StringUtils.join(references.subList(0, references.size()), "->");
            throw RaptureExceptionFactory.create(errorCode,
                    String.format("Bad value for argument \"%s\". The problem is in the child field \"%s\": %s",
                            references.get(0), referencesString, getReadableMessage(e)),
                    e);
        } else if (references.size() > 0) {
            throw RaptureExceptionFactory.create(errorCode, String.format("Bad value for argument \"%s\": %s",
                    references.get(0), getReadableMessage(e)), e);
        } else {
            RaptureException raptureException = RaptureExceptionFactory.create(errorCode,
                    "Error reading arguments: " + e.getMessage(), e);
            log.error(String.format("exception id [%s]; json [%s]", raptureException.getId(), json));
            throw raptureException;
        }
    } catch (JsonParseException e) {
        RaptureException raptureException = RaptureExceptionFactory.create(errorCode,
                "Bad/incomplete arguments passed in: " + e.getMessage(), e);
        log.error(String.format("exception id [%s]; json [%s]", raptureException.getId(), json));
        throw raptureException;
    } catch (IOException e) {
        RaptureException raptureException = RaptureExceptionFactory.create(errorCode,
                "Error reading arguments: " + e.getMessage(), e);
        log.error(String.format("exception id [%s]; json [%s]", raptureException.getId(), json));
        throw raptureException;
    }
}

From source file:io.jare.tk.TkAppFallback.java

/**
 * Authenticated.//from w ww  .  ja  v a2s .com
 * @param take Takes
 * @return Authenticated takes
 */
private static Take make(final Take take) {
    return new TkFallback(take,
            new FbChain(
                    new FbStatus(HttpURLConnection.HTTP_NOT_FOUND,
                            new RsWithStatus(new RsText("page not found"), HttpURLConnection.HTTP_NOT_FOUND)),
                    new FbStatus(HttpURLConnection.HTTP_BAD_REQUEST,
                            new RsWithStatus(new RsText("bad request"), HttpURLConnection.HTTP_BAD_REQUEST)),
                    req -> new Opt.Single<>(TkAppFallback.fatal(req))));
}

From source file:ru.parallel.octotron.http.requests.HttpExchangeWrapper.java

/**
 * finish the current request, fill content_type and<br>
 * return code with data from result<br>
 * *///from  w w w .j  a v  a 2  s  .  com
public void Finish(TypedString result) throws IOException {
    int return_code;

    if (result instanceof ErrorString)
        return_code = HttpURLConnection.HTTP_BAD_REQUEST;
    else
        return_code = HttpURLConnection.HTTP_OK;

    Finish(result.string, result.GetContentType(), return_code);
}

From source file:rapture.blob.mongodb.MongoDBBlobStore.java

@Override
public Boolean storeBlob(CallingContext context, RaptureURI blobUri, Boolean append, InputStream content) {
    try {/*from   w  w  w .java 2s.c  om*/
        return blobHandler.storeBlob(context, blobUri.getDocPath(), content, append);
    } catch (MongoException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, mongoMsgCatalog
                .getMessage("WriteError", new String[] { blobUri.getDocPath(), e.getMessage() }));
    }
}

From source file:com.cognifide.aet.rest.ArtifactServlet.java

@Override
protected void process(DBKey dbKey, HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String id = req.getParameter(Helper.ID_PARAM);
    resp.setCharacterEncoding("UTF-8");
    Artifact artifact = artifactsDAO.getArtifact(dbKey, id);
    if (artifact != null) {
        resp.setContentType(artifact.getContentType());
        resp.setHeader("Cache-Control", "public, max-age=31536000");

        OutputStream output = resp.getOutputStream();
        IOUtils.copy(artifact.getArtifactStream(), output);
        output.flush();//from   w w  w  . j ava 2  s  . c o  m
    } else {
        resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST);
        resp.setContentType("application/json");
        resp.getWriter()
                .write(responseAsJson("Unable to get artifact with id : %s form %s", id, dbKey.toString()));
    }
}

From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithoutSecurity.java

@Test
public void testConf() throws Exception {
    // test bad format
    final URL url = new URL(
            "http://" + SERVER_HOST + ":" + webServerPort + "/conf?" + ConfServlet.FORMAT_PARAM + "=badformat");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, conn.getResponseCode());

    // test json format
    final URL url1 = new URL("http://" + SERVER_HOST + ":" + webServerPort + "/conf?" + ConfServlet.FORMAT_PARAM
            + "=" + ConfServlet.FORMAT_JSON);
    conn = (HttpURLConnection) url1.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

    // test xml format
    final URL url2 = new URL("http://" + SERVER_HOST + ":" + webServerPort + "/conf?" + ConfServlet.FORMAT_PARAM
            + "=" + ConfServlet.FORMAT_XML);
    conn = (HttpURLConnection) url2.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    String xmlResponse = IOUtils.toString(conn.getInputStream());

    // test default is xml format
    final URL url3 = new URL("http://" + SERVER_HOST + ":" + webServerPort + "/conf");
    conn = (HttpURLConnection) url3.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    String defaultResponse = IOUtils.toString(conn.getInputStream());
    Assert.assertEquals(xmlResponse, defaultResponse);
}

From source file:ru.parallel.octotron.http.requests.HttpExchangeWrapper.java

/**
 * finish the current request with error and show the error description<br>
 * *//*from   w w  w. j  a v  a2 s .  c  o  m*/
public void FinishError(String description) throws IOException {
    Finish(description, "text/plain", HttpURLConnection.HTTP_BAD_REQUEST);
}

From source file:rapture.blob.mongodb.MongoDBBlobStore.java

@Override
public Boolean deleteBlob(CallingContext context, RaptureURI blobUri) {
    try {//from   w w w. j a  v a 2s  . c o  m
        return blobHandler.deleteBlob(context, blobUri.getDocPath());
    } catch (MongoException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, mongoMsgCatalog
                .getMessage("DeleteError", new String[] { blobUri.getDocPath(), e.getMessage() }));
    }
}

From source file:rapture.structured.StructuredFactory.java

private static StructuredStore makeStructuredStore(StructuredConfigParser parser, String authority) {
    int storeType = parser.getStoreType();
    if (keyStoreImplementationMap.containsKey(storeType)) {
        return getStructuredStore(keyStoreImplementationMap.get(storeType), parser.getInstance(),
                parser.getConfig().getConfig(), authority);
    } else {/*from  w  w  w.jav a  2s .com*/
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                "Unsupported structured store type");
    }
}

From source file:org.opendaylight.plugin2oc.neutron.SubnetHandler.java

/**
 * Invoked when a subnet creation is requested to check if the specified
 * subnet can be created./*from w  w w  . j a va 2  s.  c  o  m*/
 *
 * @param subnet
 *            An instance of proposed new Neutron Subnet object.
 *
 * @return A HTTP status code to the creation request.
 **/
@Override
public int canCreateSubnet(NeutronSubnet subnet) {
    VirtualNetwork virtualnetwork = new VirtualNetwork();
    apiConnector = Activator.apiConnector;
    if (subnet == null) {
        LOGGER.error("Neutron Subnet can't be null..");
        return HttpURLConnection.HTTP_BAD_REQUEST;
    }
    if (subnet.getCidr() == null || ("").equals(subnet.getCidr())) {
        LOGGER.info("Subnet Cidr can not be empty or null...");
        return HttpURLConnection.HTTP_BAD_REQUEST;
    }
    boolean isvalidGateway = validGatewayIP(subnet, subnet.getGatewayIP());
    if (!isvalidGateway) {
        LOGGER.error("Incorrect gateway IP....");
        return HttpURLConnection.HTTP_BAD_REQUEST;
    }
    try {
        virtualnetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class, subnet.getNetworkUUID());
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("Exception : " + e);
        return HttpURLConnection.HTTP_INTERNAL_ERROR;
    }
    if (virtualnetwork == null) {
        LOGGER.error("No network exists for the specified UUID...");
        return HttpURLConnection.HTTP_FORBIDDEN;
    } else {
        try {
            boolean ifSubnetExist = isSubnetPresent(subnet, virtualnetwork);
            if (ifSubnetExist) {
                LOGGER.error("The subnet already exists..");
                return HttpURLConnection.HTTP_FORBIDDEN;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("Exception:  " + e);
            return HttpURLConnection.HTTP_INTERNAL_ERROR;
        }
    }
    return HttpURLConnection.HTTP_OK;
}