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:com.alphabetbloc.accessmrs.utilities.NetworkUtils.java

public static DataInputStream getOdkStream(HttpClient client, String url) throws Exception {

    // get prefs/*from   w w  w  .  j  a v  a 2s.c om*/
    HttpPost request = new HttpPost(url);
    request.setEntity(new OdkAuthEntity());
    HttpResponse response = client.execute(request);
    response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();

    DataInputStream zdis = new DataInputStream(new GZIPInputStream(responseEntity.getContent()));

    int status = zdis.readInt();
    if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
        zdis.close();
        throw new IOException("Access denied. Check your username and password.");
    } else if (status <= 0 || status >= HttpURLConnection.HTTP_BAD_REQUEST) {
        zdis.close();
        throw new IOException(App.getApp().getString(R.string.error_connection));
    } else {
        assert (status == HttpURLConnection.HTTP_OK); // success
        return zdis;
    }
}

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

@Test
/**/*from w  ww. j a  va2 s. c  om*/
 * Test for a git repository URI with an empty scheme and host.
 * @throws Exception
 */
public void testCloneEmptySchemeAndHost() throws Exception {
    testUriCheck(":path/to/repo.git/", HttpURLConnection.HTTP_BAD_REQUEST);
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

/**
 * Updates a tenant./*from w  ww.  j a  v a2s  .co  m*/
 *
 * @param tenantId The identifier of the tenant.
 * @param tenantSpec The information to update the tenant with.
 * @return The outcome of the operation indicating success or failure.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public TenantResult<JsonObject> update(final String tenantId, final JsonObject tenantSpec) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(tenantSpec);

    if (getConfig().isModificationEnabled()) {
        if (tenants.containsKey(tenantId)) {
            try {
                final TenantObject tenant = tenantSpec.mapTo(TenantObject.class);
                tenant.setTenantId(tenantId);
                final TenantObject conflictingTenant = getByCa(tenant.getTrustedCaSubjectDn());
                if (conflictingTenant != null && !tenantId.equals(conflictingTenant.getTenantId())) {
                    // we are trying to use the same CA as another tenant
                    return TenantResult.from(HttpURLConnection.HTTP_CONFLICT);
                } else {
                    tenants.put(tenantId, tenant);
                    dirty = true;
                    return TenantResult.from(HttpURLConnection.HTTP_NO_CONTENT);
                }
            } catch (IllegalArgumentException e) {
                return TenantResult.from(HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } else {
            return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
        }
    } else {
        return TenantResult.from(HttpURLConnection.HTTP_FORBIDDEN);
    }
}

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

@Test
/**/*from w  ww.jav  a2s.  com*/
 * Test for a git repository URI with an empty scheme and path.
 * @throws Exception
 */
public void testCloneEmptySchemeAndPath() throws Exception {
    testUriCheck("host.xz:", HttpURLConnection.HTTP_BAD_REQUEST);
}

From source file:net.dahanne.gallery3.client.business.G3Client.java

private HttpEntity requestToResponseEntity(String appendToGalleryUrl, List<NameValuePair> nameValuePairs,
        String requestMethod, File file)
        throws UnsupportedEncodingException, IOException, ClientProtocolException, G3GalleryException {
    HttpClient defaultHttpClient = new DefaultHttpClient();
    HttpRequestBase httpMethod;//from w w w .j  a  v a  2 s  .  c om
    //are we using rewritten urls ?
    if (this.isUsingRewrittenUrls && appendToGalleryUrl.contains(INDEX_PHP_REST)) {
        appendToGalleryUrl = StringUtils.remove(appendToGalleryUrl, "index.php");
    }

    logger.debug("requestToResponseEntity , url requested : {}", galleryItemUrl + appendToGalleryUrl);
    if (POST.equals(requestMethod)) {
        httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        if (file != null) {
            MultipartEntity multipartEntity = new MultipartEntity();

            String string = nameValuePairs.toString();
            // dirty fix to remove the enclosing entity{}
            String substring = string.substring(string.indexOf("{"), string.lastIndexOf("}") + 1);

            StringBody contentBody = new StringBody(substring, Charset.forName("UTF-8"));
            multipartEntity.addPart("entity", contentBody);
            FileBody fileBody = new FileBody(file);
            multipartEntity.addPart("file", fileBody);
            ((HttpPost) httpMethod).setEntity(multipartEntity);
        } else {
            ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }
    } else if (PUT.equals(requestMethod)) {
        httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } else if (DELETE.equals(requestMethod)) {
        httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        //this is to avoid the HTTP 414 (length too long) error
        //it should only happen when getting items, index.php/rest/items?urls=
        //      } else if(appendToGalleryUrl.length()>2000) {
        //         String resource = appendToGalleryUrl.substring(0,appendToGalleryUrl.indexOf("?"));
        //         String variable = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("?")+1,appendToGalleryUrl.indexOf("="));
        //         String value = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("=")+1);
        //         httpMethod = new HttpPost(galleryItemUrl + resource);
        //         httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        //         nameValuePairs.add(new BasicNameValuePair(variable, value));
        //         ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(
        //               nameValuePairs));
    } else {
        httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl);
    }
    if (existingApiKey != null) {
        httpMethod.setHeader(X_GALLERY_REQUEST_KEY, existingApiKey);
    }
    //adding the userAgent to the request
    httpMethod.setHeader(USER_AGENT, userAgent);
    HttpResponse response = null;

    String[] patternsArray = new String[3];
    patternsArray[0] = "EEE, dd MMM-yyyy-HH:mm:ss z";
    patternsArray[1] = "EEE, dd MMM yyyy HH:mm:ss z";
    patternsArray[2] = "EEE, dd-MMM-yyyy HH:mm:ss z";
    try {
        // be extremely careful here, android httpclient needs it to be
        // an
        // array of string, not an arraylist
        defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsArray);
        response = defaultHttpClient.execute(httpMethod);
    } catch (ClassCastException e) {
        List<String> patternsList = Arrays.asList(patternsArray);
        defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsList);
        response = defaultHttpClient.execute(httpMethod);
    }

    int responseStatusCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = null;
    if (response.getEntity() != null) {
        responseEntity = response.getEntity();
    }

    switch (responseStatusCode) {
    case HttpURLConnection.HTTP_CREATED:
        break;
    case HttpURLConnection.HTTP_OK:
        break;
    case HttpURLConnection.HTTP_MOVED_TEMP:
        //the gallery is using rewritten urls, let's remember it and re hit the server
        this.isUsingRewrittenUrls = true;
        responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file);
        break;
    case HttpURLConnection.HTTP_BAD_REQUEST:
        throw new G3BadRequestException();
    case HttpURLConnection.HTTP_FORBIDDEN:
        //for some reasons, the gallery may respond with 403 when trying to log in with the wrong url
        if (appendToGalleryUrl.contains(INDEX_PHP_REST)) {
            this.isUsingRewrittenUrls = true;
            responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file);
            break;
        }
        throw new G3ForbiddenException();
    case HttpURLConnection.HTTP_NOT_FOUND:
        throw new G3ItemNotFoundException();
    default:
        throw new G3GalleryException("HTTP code " + responseStatusCode);
    }

    return responseEntity;
}

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

/**
 * Write the image plane to the given uri
 * //w  w  w.j  av  a  2s .  co m
 * @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);
}

From source file:rapture.repo.google.GoogleDatastoreKeyStore.java

@Override
public RaptureQueryResult runNativeQuery(String repoType, List<String> queryParams) {
    if (repoType.toUpperCase().equals("GCP_DATASTORE")) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "Not yet implemented");
    } else {//  ww w  .  j a v  a 2s. c o m
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                "RepoType mismatch. Repo is of type GCP_DATASTORE, asked for " + repoType);
    }
}

From source file:com.netflix.genie.server.resources.JobResource.java

/**
 * Get all the tags for a given job.//ww w.  j  a  va2s  .  co m
 *
 * @param id The id of the job to get the tags for. Not
 *           NULL/empty/blank.
 * @return The active set of tags.
 * @throws GenieException For any error
 */
@GET
@Path("/{id}/tags")
@ApiOperation(value = "Get the tags for a job", notes = "Get the tags for the job with the supplied id.", response = String.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Job for id does not exist."),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid id supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Set<String> getTagsForJob(
        @ApiParam(value = "Id of the job to get tags for.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called with id " + id);
    return this.jobService.getTagsForJob(id);
}

From source file:org.betaconceptframework.astroboa.resourceapi.utility.ContentApiUtils.java

public static Response createResponseForPutOrPostOfACmsEntity(CmsRepositoryEntity cmsRepositoryEntity,
        String httpMethod, String requestContent, boolean entityIsNew) {

    if (cmsRepositoryEntity != null && cmsRepositoryEntity.getId() != null) {

        ResourceRepresentationType<?> resourceRepresentationType = contentIsXML(requestContent)
                ? ResourceRepresentationType.XML
                : ResourceRepresentationType.JSON;

        return createSuccessfulResponseForPUTOrPOST(cmsRepositoryEntity, httpMethod, resourceRepresentationType,
                entityIsNew);/*from www . ja  va 2s  .  com*/
    } else {
        logger.error(
                "{} request was not successfull. The entity created when importing the following content {}. \n {} ",
                new Object[] { httpMethod, (cmsRepositoryEntity == null ? " was null" : " had no identifier"),
                        requestContent });

        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }
}

From source file:fr.mael.jiwigo.dao.impl.ImageDaoImpl.java

public void addSimple(File file, Integer category, String title, Integer level) throws JiwigoException {
    HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl());

    //   nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple"));
    //   for (int i = 0; i < parametres.length; i += 2) {
    //       nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1]));
    //   }//from w  w w  .j ava  2 s .  c o  m
    //   method.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    if (file != null) {
        MultipartEntity multipartEntity = new MultipartEntity();

        //      String string = nameValuePairs.toString();
        // dirty fix to remove the enclosing entity{}
        //      String substring = string.substring(string.indexOf("{"),
        //            string.lastIndexOf("}") + 1);
        try {
            multipartEntity.addPart("method", new StringBody(MethodsEnum.ADD_SIMPLE.getLabel()));
            multipartEntity.addPart("category", new StringBody(category.toString()));
            multipartEntity.addPart("name", new StringBody(title));
            if (level != null) {
                multipartEntity.addPart("level", new StringBody(level.toString()));
            }
        } catch (UnsupportedEncodingException e) {
            throw new JiwigoException(e);
        }

        //      StringBody contentBody = new StringBody(substring,
        //            Charset.forName("UTF-8"));
        //      multipartEntity.addPart("entity", contentBody);
        FileBody fileBody = new FileBody(file);
        multipartEntity.addPart("image", fileBody);
        ((HttpPost) httpMethod).setEntity(multipartEntity);
    }

    HttpResponse response;
    StringBuilder sb = new StringBuilder();
    try {
        response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod);

        int responseStatusCode = response.getStatusLine().getStatusCode();

        switch (responseStatusCode) {
        case HttpURLConnection.HTTP_CREATED:
            break;
        case HttpURLConnection.HTTP_OK:
            break;
        case HttpURLConnection.HTTP_BAD_REQUEST:
            throw new JiwigoException("status code was : " + responseStatusCode);
        case HttpURLConnection.HTTP_FORBIDDEN:
            throw new JiwigoException("status code was : " + responseStatusCode);
        case HttpURLConnection.HTTP_NOT_FOUND:
            throw new JiwigoException("status code was : " + responseStatusCode);
        default:
            throw new JiwigoException("status code was : " + responseStatusCode);
        }

        HttpEntity resultEntity = response.getEntity();
        BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity);

        BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
        String line;

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } finally {
            reader.close();
        }
    } catch (ClientProtocolException e) {
        throw new JiwigoException(e);
    } catch (IOException e) {
        throw new JiwigoException(e);
    }
    String stringResult = sb.toString();

}