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:au.org.ala.biocache.web.ValidationRuleController.java

/**
 * Example expected payload/*  ww w  .  jav  a  2  s .c  om*/
 *
 * {
 *    "status": "new",
 *    "ignored": false,
 *    "apiKey": "XXXXXXXXXX",
 *    "user": {
 *    "isAdmin": true,
 *    "email": "xxxxxxxx@gmail.com",
 *    "authority": 1000
 *    },
 *    "classification": "invalid",
 *    "area": "MULTIPOLYGON(((137.5 -26,137.5 -25.5,138 -25.5,138 -26,137.5 -26)),((134.5 -29.5,134.5 -29,135 -29,135 -29.5,134.5 -29.5)))",
 *    "lastModified": "2013-01-01T09:05:19",
 *    "id": 5090,
 *    "comment": "",
 *    "species": "Trichoglossus haematodus"
 * }
 *
 * @param request
 * @param response
 * @throws Exception
 */
@RequestMapping(value = { "/assertions/query/add", "/validation/rule/add" }, method = RequestMethod.POST)
public void addValidationRule(HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {
        String rawValue = org.apache.commons.io.IOUtils.toString(request.getInputStream(), "UTF-8");
        logger.debug("The raw value :" + rawValue);

        try {
            ObjectMapper om = new ObjectMapper();
            ValidationRuleDTO validationRuleDTO = om.readValue(rawValue, ValidationRuleDTO.class);

            //we know that it is a JCU assertion
            if (shouldPerformOperation(validationRuleDTO.getApiKey(), response)) {
                //delete
                if (validationRuleDTO.getStatus().equals("deleted")) {
                    Store.deleteValidationRule(validationRuleDTO.getApiKey() + "|" + validationRuleDTO.getId(),
                            validationRuleDTO.getLastModified());
                } else {
                    //new or update
                    //does the species exist
                    String guid = speciesLookupService.getGuidForName(validationRuleDTO.getSpecies());
                    if ((guid != null || validationRuleDTO.getQuery() != null)
                            && validationRuleDTO.getId() != null) {
                        //check to see if the area is well formed.
                        SpatialSearchRequestParams ssr = new SpatialSearchRequestParams();
                        String query = guid != null ? "lsid:" + guid : validationRuleDTO.getQuery();
                        ssr.setQ(query);
                        ssr.setWkt(validationRuleDTO.getArea());
                        ssr.setFacet(false);
                        try {
                            SolrDocumentList list = searchDAO.findByFulltext(ssr);
                            Long recordCount = list.getNumFound();
                            logger.debug("Validation rule should apply to records: " + recordCount);
                            //now create the query assertion
                            ValidationRule validationRule = new ValidationRule();
                            //NQ: need the id to be populated to construct the correct validation rowkey to allow for updates
                            validationRule.setId(validationRuleDTO.getId().toString());
                            //copy form DTO -> model object for storage
                            validationRule.setApiKey(validationRuleDTO.apiKey);
                            validationRule.setRawAssertion(rawValue);
                            validationRule.setWkt(validationRuleDTO.area);
                            validationRule.setComment(validationRuleDTO.getComment());

                            //auth details
                            String userId = authService.getMapOfEmailToId()
                                    .get(validationRuleDTO.user.getEmail());
                            validationRule.setUserId(userId);
                            validationRule.setUserEmail(validationRuleDTO.user.getEmail());
                            validationRule.setAuthority(validationRuleDTO.user.getAuthority().toString());

                            validationRule.setRawQuery(getRawQuery(validationRuleDTO.getQuery(), guid,
                                    validationRuleDTO.getArea()));
                            if (validationRuleDTO.getStatus().equals("new")) {
                                validationRule.setCreatedDate(validationRuleDTO.getLastModified());
                            }

                            Store.addValidationRule(validationRule);
                        } catch (Exception e) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                                    "Unable to construct a valid validation rule from the provided information. "
                                            + validationRuleDTO.getId());
                            logger.error("Error constructing query or adding to datastore", e);
                        }
                    } else {
                        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                                "Unable to locate species " + validationRuleDTO.getSpecies()
                                        + " for validation rule " + validationRuleDTO.getId());
                    }
                }
            }
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            logger.error("Unable to resolve message to known type", e);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        response.sendError(HttpURLConnection.HTTP_BAD_REQUEST);
    }
}

From source file:noThreads.ParseLevel2.java

/**
 * @param theUrl/*from   w ww.j  a va2s.  c o  m*/
 * @param conAttempts
 * @return
 * @throws IOException
 */
public boolean validUrl(String theUrl, int conAttempts) throws IOException {
    long total_time = 0, endTime = 0;
    long startTime = System.currentTimeMillis();
    URL link = new URL(theUrl);
    int CONNECT_TIMEOUT = 5000, READ_TIMEOUT = 2000;

    HttpURLConnection huc = (HttpURLConnection) link.openConnection();
    huc.setRequestProperty("User-Agent", userAgent);
    huc.setConnectTimeout(CONNECT_TIMEOUT);
    huc.setReadTimeout(READ_TIMEOUT);
    try {
        huc.connect();

    } catch (java.net.ConnectException e) {
        print(e.getMessage() + "\n");
        if (e.getMessage().equalsIgnoreCase("Connection timed out")) {
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        } else {
            return false;
        }

    } catch (java.net.SocketTimeoutException e) {
        print(e.getMessage() + "\n");
        if (e.getMessage().equalsIgnoreCase("connect timed out")) {
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        } else {
            return false;
        }

    } catch (IOException e) {
        print(e.getMessage() + "\n");
        return false;
    }
    UrlValidator urlValidator = new UrlValidator();
    if (urlValidator.isValid(theUrl) == true) {
        print("valid url form");
        if (huc.getContentType() != null) {
            print("Content: " + huc.getContentType());
            if (huc.getContentType().equals("text/html") || huc.getContentType().equals("unknown/unknown")) {
                if (getResposeCode(theUrl, 0) >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
                    print("Server Response Code: " + getResposeCode(theUrl, 0));
                    return false;
                }
            }
            print(huc.getContentType());
            endTime = System.currentTimeMillis();
            total_time = total_time + (endTime - startTime);
            print("Total elapsed time is :" + total_time + "\n");
            return true;
        } else {//edw erxetai an den prolavei na diavasei h an einai null to content
            endTime = System.currentTimeMillis();
            total_time = total_time + (endTime - startTime);
            print("Total elapsed time is :" + total_time + "\n");
            if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
                print("Recurrencing validUrl method...");
                return validUrl(theUrl, conAttempts + 1);
            } else {
                return false;
            }
        }
    } else {
        endTime = System.currentTimeMillis();
        total_time = total_time + (endTime - startTime);
        print("Total elapsed time is :" + total_time + "\n");
        return false;
    }
}

From source file:rapture.plugin.install.PluginSandbox.java

public void extract(ScriptingApi client, RaptureURI uri, boolean force) {
    PluginSandboxItem item = uri2item.get(uri);
    if (item == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "URI not in manifest");
    }//  w  w  w  .j  a v a2s .  co  m
    item.download(client, force);
}

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

@Test
public void testCloneEmptyPathBadUrl() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath workspacePath = new Path("workspace").append(getWorkspaceId(workspaceLocation)).makeAbsolute();

    AuthorizationService.removeUserRight(testUserId, "/");
    AuthorizationService.removeUserRight(testUserId, "/*");

    // /workspace/{id} + {methodName}
    WebRequest request = new PostGitCloneRequest().setURIish("I'm//bad!").setWorkspacePath(workspacePath)
            .setName(getMethodName()).getWebRequest();
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode());

    // no project should be created
    request = new GetMethodWebRequest(workspaceLocation.toString());
    setAuthentication(request);/*from w w w  .j  a  va 2 s .  c om*/
    response = webConversation.getResponse(request);
    JSONObject workspace = new JSONObject(response.getText());
    assertEquals(0, workspace.getJSONArray(ProtocolConstants.KEY_CHILDREN).length());
}

From source file:org.eclipse.orion.server.tests.servlets.xfer.TransferTest.java

/**
 * Tests importing from a URL, where the source URL is not absolute. This should fail.
 *//*from  w  ww. j ava  2  s .com*/
@Test
public void testImportFromURLMalformed() throws CoreException, IOException, SAXException {
    //create a directory to upload to
    String directoryPath = "sample/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);

    //start the import
    String requestPath = getImportRequestPath(directoryPath) + "?source=pumpkins";
    PostMethodWebRequest request = new PostMethodWebRequest(requestPath);
    setAuthentication(request);
    WebResponse postResponse = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, postResponse.getResponseCode());
}

From source file:com.netflix.genie.server.services.impl.GenieExecutionServiceImpl.java

/** {@inheritDoc} */
@Override//from w w  w  . j a v  a2 s .  co m
public JobInfoResponse getJobs(String jobID, String jobName, String userName, String jobType, String status,
        String clusterName, String clusterId, Integer limit, Integer page) {
    logger.info("called");

    JobInfoResponse response;
    String table = JobInfoElement.class.getSimpleName();

    ClauseBuilder criteria = null;
    try {
        criteria = new ClauseBuilder(ClauseBuilder.AND);
        if ((jobID != null) && (!jobID.isEmpty())) {
            String query = "jobID like '" + jobID + "'";
            criteria.append(query);
        }
        if ((jobName != null) && (!jobName.isEmpty())) {
            String query = "jobName like '" + jobName + "'";
            criteria.append(query);
        }
        if ((userName != null) && (!userName.isEmpty())) {
            String query = "userName='" + userName + "'";
            criteria.append(query);
        }
        if ((jobType != null) && (!jobType.isEmpty())) {
            if (Types.JobType.parse(jobType) == null) {
                throw new CloudServiceException(HttpURLConnection.HTTP_BAD_REQUEST,
                        "Job type: " + jobType + " can only be HADOOP, HIVE or PIG");
            }
            String query = "jobType='" + jobType.toUpperCase() + "'";
            criteria.append(query);
        }
        if ((status != null) && (!status.isEmpty())) {
            if (Types.JobStatus.parse(status) == null) {
                throw new CloudServiceException(HttpURLConnection.HTTP_BAD_REQUEST,
                        "Unknown job status: " + status);
            }
            String query = "status='" + status.toUpperCase() + "'";
            criteria.append(query);
        }
        if ((clusterName != null) && (!clusterName.isEmpty())) {
            String query = "clusterName='" + clusterName + "'";
            criteria.append(query);
        }
        if ((clusterId != null) && (!clusterId.isEmpty())) {
            String query = "clusterId='" + clusterId + "'";
            criteria.append(query);
        }
    } catch (CloudServiceException e) {
        logger.error(e.getMessage(), e);
        response = new JobInfoResponse(e);
        return response;
    }

    Object[] results;
    try {
        QueryBuilder builder = new QueryBuilder().table(table).clause(criteria.toString()).limit(limit)
                .page(page);
        results = pm.query(builder);

    } catch (Exception e) {
        logger.error("Failed to get job results from database: ", e);
        response = new JobInfoResponse(
                new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage()));
        return response;
    }

    if (results.length != 0) {
        JobInfoElement[] jobInfos = new JobInfoElement[results.length];
        for (int i = 0; i < results.length; i++) {
            jobInfos[i] = (JobInfoElement) results[i];
        }

        response = new JobInfoResponse();
        response.setJobs(jobInfos);
        response.setMessage("Returning job information for specified criteria");
        return response;
    } else {
        response = new JobInfoResponse(new CloudServiceException(HttpURLConnection.HTTP_NOT_FOUND,
                "No jobs found for specified criteria"));
        return response;
    }
}

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

@Test
public void testCloneBadUrl() throws Exception {
    testUriCheck("I'm//bad!", HttpURLConnection.HTTP_BAD_REQUEST);
}

From source file:rapture.repo.mongodb.MongoDbDataStore.java

@Override
public RaptureQueryResult runNativeQuery(final String repoType, final List<String> queryParams) {
    if (repoType.toUpperCase().equals(MONGODB)) {

        MongoRetryWrapper<RaptureQueryResult> wrapper = new MongoRetryWrapper<RaptureQueryResult>() {

            @Override//from   ww  w  . j a  va 2  s. c  o  m
            public FindIterable<Document> makeCursor() {
                // Here we go, the queryParams are basically
                // (1) the searchCriteria
                Document queryObj = getQueryObjFromQueryParams(queryParams);
                // Document fieldObj =
                // getFieldObjFromQueryParams(queryParams);
                MongoCollection<Document> collection = MongoDBFactory.getCollection(instanceName, tableName);
                FindIterable<Document> find = collection.find(queryObj).batchSize(100);
                if (queryParams.size() > 2) {
                    Map<String, Object> options = JacksonUtil.getMapFromJson(queryParams.get(2));
                    if (options.containsKey(SKIP)) {
                        find.skip((Integer) options.get(SKIP));
                    }
                    if (options.containsKey(LIMIT)) {
                        find.limit((Integer) options.get(LIMIT));
                    }
                    if (options.containsKey(SORT)) {
                        Map<String, Object> sortInfo = JacksonUtil.getMapFromJson(options.get(SORT).toString());
                        Document sortInfoObject = new Document();
                        sortInfoObject.putAll(sortInfo);
                        find.sort(sortInfoObject);
                    }
                }
                return find;
            }

            @Override
            public RaptureQueryResult action(FindIterable<Document> iterable) {
                RaptureQueryResult res = new RaptureQueryResult();
                for (Document d : iterable) {
                    res.addRowContent(new JsonContent(d.toString()));
                }
                return res;
            }

        };
        return wrapper.doAction();
    } else {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                mongoMsgCatalog.getMessage("Mismatch", repoType));
    }
}

From source file:org.eclipse.orion.server.tests.servlets.users.BasicUsersTest.java

/**
 * Tests creating users with username that can't be represented in a URI.
 * @throws IOException/*from   w ww.  j  av a 2  s  . c  o m*/
 * @throws SAXException
 * @throws JSONException
 */
@Test
public void testCreateUserInvalidName() throws IOException, SAXException, JSONException {
    WebConversation webConversation = new WebConversation();
    webConversation.setExceptionsThrownOnErrorStatus(false);

    //restrict to alphanumeric characters
    String invalidChars = " !@#$%^&*()-=_+[]{}\";':\\/><.,`~";
    for (int i = 0; i < invalidChars.length(); i++) {
        String name = "bad" + invalidChars.charAt(i) + "name";

        // create user
        Map<String, String> params = new HashMap<String, String>();
        params.put("login", name);
        params.put("Name", "Tom");

        params.put("password", "pass_" + System.currentTimeMillis());
        WebRequest request = getPostUsersRequest("", params, true);
        WebResponse response = webConversation.getResponse(request);
        assertEquals("Should fail with name: " + name, HttpURLConnection.HTTP_BAD_REQUEST,
                response.getResponseCode());

    }
}

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

@Test
public void testCloneBadUrlScheme() throws Exception {
    testUriCheck("file:///path/to/other/users.git", HttpURLConnection.HTTP_BAD_REQUEST);
}