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:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testBadRequestCreate() throws IOException {
    try {/*from   ww w.j  a  v a  2s.c o  m*/
        streamClient.create(TestUtils.BAD_REQUEST_STREAM_NAME);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, e.getStatusCode());
    }
}

From source file:rapture.kernel.AdminApiImpl.java

private String generateSecureToken() {
    try {//from w  ww . j  av a2s  .  c o m
        // get secure random
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte bytes[] = new byte[128];
        random.nextBytes(bytes);
        // get its digest
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] result = sha.digest(bytes);
        // encode to hex
        return (new Hex()).encodeHexString(result);
    } catch (NoSuchAlgorithmException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, e.getMessage());
    }
}

From source file:rapture.kernel.SeriesApiImpl.java

@Override
public void addStringsToSeries(CallingContext context, String seriesURI, List<String> pointKeys,
        List<String> pointValues) {
    checkParameter("URI", seriesURI);
    checkParameter("pointKeys", pointKeys);
    checkParameter("pointValues", pointValues);
    if (pointKeys.size() != pointValues.size()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("ArgSizeNotEqual")); //$NON-NLS-1$
    }/*from  w w  w  . j av  a2  s .co  m*/
    RaptureURI internalURI = new RaptureURI(seriesURI, Scheme.SERIES);
    getRepoOrFail(internalURI).addStringsToSeries(internalURI.getDocPath(), pointKeys, pointValues);
    processSearchUpdate(context, internalURI, pointKeys, pointValues);
}

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

/**
 * Remove an tag from a given job.//from  ww  w  . j  a v a  2s  . com
 *
 * @param id  The id of the job to delete the tag from. Not
 *            null/empty/blank.
 * @param tag The tag to remove. Not null/empty/blank.
 * @return The active set of tags for the job.
 * @throws GenieException For any error
 */
@DELETE
@Path("/{id}/tags/{tag}")
@ApiOperation(value = "Remove a tag from a job", notes = "Remove the given tag from the job with given 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> removeTagForJob(
        @ApiParam(value = "Id of the job to delete from.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The tag to remove.", required = true) @PathParam("tag") final String tag)
        throws GenieException {
    LOG.info("Called with id " + id + " and tag " + tag);
    return this.jobService.removeTagForJob(id, tag);
}

From source file:rapture.kernel.AdminApiImpl.java

@Override
public void cancelPasswordResetToken(CallingContext context, String userName) {
    checkParameter("User", userName);
    RaptureUser user = getUser(context, userName);
    if (user == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                adminMessageCatalog.getMessage("NoExistUser", userName)); //$NON-NLS-1$
    }/*from   w  w  w . ja  v  a 2  s. c om*/
    // expire token now
    user.setTokenExpirationTime(System.currentTimeMillis());
    RaptureUserStorage.add(user, context.getUser(), "Cancel password reset token for user " + userName); //$NON-NLS-1$
}

From source file:eu.codeplumbers.cosi.services.CosiContactService.java

/**
 * Make remote request to get all calls stored in Cozy
 */// w w  w  . jav  a2  s .  c o  m
public void getRemoteContacts() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new ContactSyncEvent(SYNC_MESSAGE, "Your Cozy has no contacts stored."));
                Contact.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    Log.d("Contact", i + "");
                    EventBus.getDefault().post(new ContactSyncEvent(SYNC_MESSAGE,
                            "Reading contacts on Cozy " + (i + 1) + "/" + jsonArray.length() + "..."));
                    try {

                        JSONObject contactJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        Contact contact = Contact.getByRemoteId(contactJson.get("_id").toString());
                        if (contact == null) {
                            contact = Contact.getByName(contactJson.getString("n"));
                            if (contact == null) {
                                contact = new Contact(contactJson);
                            } else {
                                if (contactJson.has("n"))
                                    contact.setN(contactJson.getString("n"));
                                else
                                    contact.setN("");

                                if (contactJson.has("fn"))
                                    contact.setFn(contactJson.getString("fn"));
                                else
                                    contact.setFn("");

                                if (contactJson.has("revision")) {
                                    contact.setRevision(contactJson.getString("revision"));
                                } else {
                                    contact.setRevision(DateUtils.formatDate(new Date().getTime()));
                                }

                                if (contactJson.has("tags")
                                        && !contactJson.getString("tags").equalsIgnoreCase("")) {
                                    contact.setTags(contactJson.getJSONArray("tags").toString());
                                } else {
                                    contact.setTags(new JSONArray().toString());
                                }
                                contact.setPhotoBase64("");
                                contact.setAnniversary("");

                                if (contactJson.has("deviceId")) {
                                    contact.setDeviceId(contactJson.getString("deviceId"));
                                }

                                if (contactJson.has("systemId")) {
                                    contact.setSystemId(contactJson.getString("systemId"));
                                }

                                contact.setRemoteId(contactJson.getString("_id"));

                                if (contactJson.has("_attachments")) {
                                    JSONObject attachment = contactJson.getJSONObject("_attachments");

                                    contact.setAttachments(attachment.toString());

                                    if (attachment.has("picture")) {
                                        JSONObject picture = attachment.getJSONObject("picture");
                                        String attachmentName = new String(
                                                Base64.decode(picture.getString("digest").replace("md5-", ""),
                                                        Base64.DEFAULT));
                                        Log.d("Contact", attachmentName);
                                    }
                                }

                                contact.save();

                                if (contactJson.has("datapoints")) {
                                    JSONArray datapoints = contactJson.getJSONArray("datapoints");

                                    for (int j = 0; j < datapoints.length(); j++) {
                                        JSONObject datapoint = datapoints.getJSONObject(j);
                                        String value = datapoint.getString("value");
                                        ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact,
                                                value);

                                        if (contactDataPoint == null && !value.isEmpty()) {
                                            contactDataPoint = new ContactDataPoint();
                                            contactDataPoint.setPref(false);
                                            contactDataPoint.setType(datapoint.getString("type"));
                                            contactDataPoint.setValue(value);
                                            contactDataPoint.setName(datapoint.getString("name"));
                                            contactDataPoint.setContact(contact);
                                            contactDataPoint.save();
                                        }
                                    }
                                }
                            }
                        } else {
                            if (contactJson.has("n"))
                                contact.setN(contactJson.getString("n"));
                            else
                                contact.setN("");

                            if (contactJson.has("fn"))
                                contact.setFn(contactJson.getString("fn"));
                            else
                                contact.setFn("");

                            if (contactJson.has("revision")) {
                                contact.setRevision(contactJson.getString("revision"));
                            } else {
                                contact.setRevision(DateUtils.formatDate(new Date().getTime()));
                            }

                            if (contactJson.has("tags")
                                    && !contactJson.getString("tags").equalsIgnoreCase("")) {
                                contact.setTags(contactJson.getJSONArray("tags").toString());
                            } else {
                                contact.setTags(new JSONArray().toString());
                            }
                            contact.setPhotoBase64("");
                            contact.setAnniversary("");

                            if (contactJson.has("deviceId")) {
                                contact.setDeviceId(contactJson.getString("deviceId"));
                            }

                            if (contactJson.has("systemId")) {
                                contact.setSystemId(contactJson.getString("systemId"));
                            }

                            contact.setRemoteId(contactJson.getString("_id"));

                            if (contactJson.has("_attachments")) {
                                JSONObject attachment = contactJson.getJSONObject("_attachments");

                                contact.setAttachments(attachment.toString());

                                if (attachment.has("picture")) {
                                    JSONObject picture = attachment.getJSONObject("picture");
                                    String attachmentName = new String(Base64.decode(
                                            picture.getString("digest").replace("md5-", ""), Base64.DEFAULT));
                                    Log.d("Contact", attachmentName);
                                }
                            }

                            contact.save();

                            if (contactJson.has("datapoints")) {
                                JSONArray datapoints = contactJson.getJSONArray("datapoints");

                                for (int j = 0; j < datapoints.length(); j++) {
                                    JSONObject datapoint = datapoints.getJSONObject(j);
                                    String value = datapoint.getString("value");
                                    ContactDataPoint contactDataPoint = ContactDataPoint.getByValue(contact,
                                            value);

                                    if (contactDataPoint == null && !value.isEmpty()) {
                                        contactDataPoint = new ContactDataPoint();
                                        contactDataPoint.setPref(false);
                                        contactDataPoint.setType(datapoint.getString("type"));
                                        contactDataPoint.setValue(value);
                                        contactDataPoint.setName(datapoint.getString("name"));
                                        contactDataPoint.setContact(contact);
                                        contactDataPoint.save();
                                    }
                                }
                            }
                        }

                        contact.save();

                        allContacts.add(contact);
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new ContactSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java

/**
 * Get an achievement data with specific ID from database
 * @param appId applicationId//  ww w  .j a va 2  s.com
 * @param achievementId achievement id
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}/{achievementId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found an achievement"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getAchievementWithId", notes = "Get achievement data with specified ID", response = AchievementModel.class)
public HttpResponse getAchievementWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Achievement ID") @PathParam("achievementId") String achievementId) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "GET " + "gamification/achievements/" + appId + "/" + achievementId);
    long randomLong = new Random().nextLong(); //To be able to match 

    AchievementModel achievement = null;
    Connection conn = null;

    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_16, "" + randomLong);

        try {

            try {
                if (!achievementAccess.isAppIdExist(conn, appId)) {
                    objResponse.put("message", "Cannot get achievement detail. App not found");
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
                objResponse.put("message",
                        "Cannot get achievement detail. Cannot check whether application ID exist or not. Database error. "
                                + e1.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
            if (!achievementAccess.isAchievementIdExist(conn, appId, achievementId)) {
                objResponse.put("message", "Cannot get achievement detail. Achievement not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            achievement = achievementAccess.getAchievementWithId(conn, appId, achievementId);
            if (achievement == null) {
                objResponse.put("message", "Achievement Null, Cannot find achievement with " + achievementId);
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            //Set pretty printing of json
            objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

            String achievementString = objectMapper.writeValueAsString(achievement);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_17, "" + randomLong);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_26, "" + name);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_27, "" + appId);

            return new HttpResponse(achievementString, HttpURLConnection.HTTP_OK);
        } catch (SQLException e) {
            e.printStackTrace();
            objResponse.put("message", "Cannot get achievement detail. DB Error. " + e.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

        }

    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get achievement detail. JSON processing error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot get achievement. Failed to fetch " + achievementId + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    }
}

From source file:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java

@Test
public void testCreateProjectBadName() throws IOException, SAXException, JSONException {
    //create workspace
    String workspaceName = WorkspaceServiceTest.class.getName() + "#testCreateProjectBadName";
    URI workspaceLocation = createWorkspace(workspaceName);

    //check a variety of bad project names
    for (String badName : Arrays.asList("", " ", "/")) {
        //create a project
        WebRequest request = getCreateProjectRequest(workspaceLocation, badName, null);
        WebResponse response = webConversation.getResponse(request);
        assertEquals("Shouldn't allow name: " + badName, HttpURLConnection.HTTP_BAD_REQUEST,
                response.getResponseCode());
    }// ww  w .j a v  a  2  s. com
}

From source file:org.betaconceptframework.astroboa.resourceapi.resource.TaxonomyResource.java

private Response saveTaxonomyByIdOrName(@PathParam("taxonomyIdOrName") String taxonomyIdOrName,
        String requestContent, String httpMethod) {

    //Import from xml or json. Taxonomy will not be saved
    ImportConfiguration configuration = ImportConfiguration.taxonomy().persist(PersistMode.DO_NOT_PERSIST)
            .build();//from  w w  w. j  a  v  a  2 s . com

    Taxonomy taxonomyToBeSaved = astroboaClient.getImportService().importTaxonomy(requestContent,
            configuration);

    //Bring taxonomy from repository
    Taxonomy existedTaxonomy = astroboaClient.getTaxonomyService().getTaxonomy(taxonomyIdOrName,
            ResourceRepresentationType.TAXONOMY_INSTANCE, FetchLevel.ENTITY, false);

    boolean taxonomyIdHasBeenProvided = CmsConstants.UUIDPattern.matcher(taxonomyIdOrName).matches();

    boolean entityIsNew = existedTaxonomy == null;

    if (taxonomyIdHasBeenProvided) {
        if (taxonomyToBeSaved.getId() == null) {
            taxonomyToBeSaved.setId(taxonomyIdOrName);
        }
    } else {
        if (taxonomyToBeSaved.getName() == null) {
            taxonomyToBeSaved.setName(taxonomyIdOrName);
        }
    }

    if (existedTaxonomy != null) {

        //Taxonomy exists in repository.
        //Check to see if an id is provided in the payload
        if (taxonomyToBeSaved.getId() == null) {
            taxonomyToBeSaved.setId(existedTaxonomy.getId());
        } else {
            if (!StringUtils.equals(existedTaxonomy.getId(), taxonomyToBeSaved.getId())) {
                logger.warn(
                        "Try to {} taxonomy {} which corresponds to an existed taxonomy in repository with id {} but payload contains a different id {}",
                        new Object[] { httpMethod, taxonomyIdOrName, existedTaxonomy.getId(),
                                taxonomyToBeSaved.getId() });
                throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
            }
        }

    } else {
        //A new taxonomy will be created.
        //Check to see if system name is provided in the payload
        if (taxonomyToBeSaved.getName() != null && !taxonomyIdHasBeenProvided
                && !StringUtils.equals(taxonomyIdOrName, taxonomyToBeSaved.getName())) {
            logger.warn("Try to {} taxonomy with name {} but payload contains a different name {}",
                    new Object[] { httpMethod, taxonomyIdOrName, taxonomyToBeSaved.getName() });
            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }
    }

    //Produce xml representation of imported taxonomy and continue with save
    return saveTaxonomySource(taxonomyToBeSaved.xml(false), httpMethod, entityIsNew);
}

From source file:rapture.kernel.SeriesApiImpl.java

@Override
public void addStructuresToSeries(CallingContext context, String seriesURI, List<String> pointKeys,
        List<String> pointValues) {
    checkParameter("URI", seriesURI);
    checkParameter("pointKeys", pointKeys);
    checkParameter("pointValues", pointValues);

    if (pointKeys.size() != pointValues.size()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("ArgSizeNotEqual")); //$NON-NLS-1$
    }//from w  w w. j  a  va 2 s  . co m
    for (String v : pointValues) {
        if (v == null)
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                    apiMessageCatalog.getMessage("NullEmpty", "pointValue")); //$NON-NLS-1$
    }
    RaptureURI internalURI = new RaptureURI(seriesURI, Scheme.SERIES);
    getRepoOrFail(internalURI).addStructuresToSeries(internalURI.getDocPath(), pointKeys, pointValues);
    processSearchUpdate(context, internalURI, pointKeys, pointValues);
}