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:org.betaconceptframework.astroboa.resourceapi.resource.DefinitionResource.java

private Response getModelInternal(String callback, boolean prettyPrintEnabled, Output outputEnum) {
    try {/*w  w w . j a  v  a  2  s  . c  o  m*/

        if (outputEnum != Output.XML && outputEnum != Output.JSON) {
            throw new Exception("All definitions are exported only in XML and JSON format. " + outputEnum
                    + " is not supported");
        }

        String allDefinitions = new ModelSerializer(prettyPrintEnabled, outputEnum == Output.JSON,
                astroboaClient.getDefinitionService(), astroboaClient.getConnectedRepositoryId()).serialize();

        if (StringUtils.isBlank(allDefinitions)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        StringBuilder definitionAsXMLOrJSONorXSD = new StringBuilder();
        if (StringUtils.isBlank(callback)) {
            definitionAsXMLOrJSONorXSD.append(allDefinitions);
        } else {
            switch (outputEnum) {
            case XML: {
                ContentApiUtils.generateXMLP(definitionAsXMLOrJSONorXSD, allDefinitions, callback);
                break;
            }
            case JSON:
                ContentApiUtils.generateJSONP(definitionAsXMLOrJSONorXSD, allDefinitions, callback);
                break;
            }
        }

        return ContentApiUtils.createResponse(definitionAsXMLOrJSONorXSD, outputEnum, callback, null);

    } catch (Exception e) {
        logger.error("When exporting all Definitions", e);
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }
}

From source file:rapture.kernel.DocApiImpl.java

public Map<String, String> getDocsInternal(CallingContext context, List<String> docUris) {
    Map<String, String> ret = new LinkedHashMap<>();
    ListMultimap<String, RaptureURI> repoToUriMap = ArrayListMultimap.create();

    // Group all the documents by the correct repo
    for (String docUri : docUris) {
        if (StringUtils.isBlank(docUri)) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                    apiMessageCatalog.getMessage("NullOrEmpty"));
        }/*from   w w  w . ja v a  2  s  .  c o  m*/
        RaptureURI internalUri = new RaptureURI(docUri, Scheme.DOCUMENT);
        repoToUriMap.put(internalUri.getAuthority(), internalUri);
    }

    // Request each set of the documents from the repo at once
    for (final String authority : repoToUriMap.keySet()) {
        Repository repository = getRepoFromCache(authority);
        if (repository != null) {
            List<RaptureURI> uris = repoToUriMap.get(authority);
            List<String> docs = repository
                    .getDocuments(Lists.transform(uris, new Function<RaptureURI, String>() {
                        @Override
                        public String apply(RaptureURI uri) {
                            return uri.getDocPath();
                        }
                    }));
            for (int i = 0; i < docs.size(); i++) {
                ret.put(uris.get(i).toString(), docs.get(i));
            }
        }
    }
    return ret;
}

From source file:fi.cosky.sdk.API.java

private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass,
        Object object, HashMap<String, String> headers) throws IOException {
    URL serverAddress;/*from  w w  w  . j av  a  2 s . co m*/
    HttpURLConnection connection;
    BufferedReader br;
    String result = "";
    try {
        serverAddress = new URL(url);
        connection = (HttpURLConnection) serverAddress.openConnection();
        connection.setInstanceFollowRedirects(false);
        boolean doOutput = doOutput(verb);
        connection.setDoOutput(doOutput);
        connection.setRequestMethod(method(verb));
        connection.setRequestProperty("Authorization", headers.get("authorization"));
        connection.addRequestProperty("Accept", "application/json");

        if (doOutput) {
            connection.addRequestProperty("Content-Length", "0");
            OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream());
            os.write("");
            os.flush();
            os.close();
        }
        connection.connect();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER
                || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            Link location = parseLocationLinkFromString(connection.getHeaderField("Location"));
            Link l = new Link("self", "/tokens", "GET", "", true);
            ArrayList<Link> links = new ArrayList<Link>();
            links.add(l);
            links.add(location);
            ResponseData data = new ResponseData();
            data.setLocation(location);
            data.setLinks(links);
            return (T) data;
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            System.out.println("Authentication expired: " + connection.getResponseMessage());
            if (retry && this.tokenData != null) {
                retry = false;
                this.tokenData = null;
                if (authenticate()) {
                    System.out.println(
                            "Reauthentication success, will continue with " + verb + " request on " + url);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                }
            } else
                throw new IOException(
                        "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API");
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST
                && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) {
            System.out.println("ErrorCode: " + connection.getResponseCode() + " "
                    + connection.getResponseMessage() + " " + url + ", verb: " + verb);

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class);
        } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
            if (retry) {
                System.out.println("Server responded with internal server error, trying again in "
                        + RETRY_WAIT_TIME + " msec.");
                try {
                    retry = false;
                    Thread.sleep(RETRY_WAIT_TIME);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                } catch (InterruptedException e) {

                }
            } else {
                System.out.println("Server responded with internal server error, please contact dev@nfleet.fi");
            }

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw new IOException(errorString);
        }

        result = readDataFromConnection(connection);
    } catch (MalformedURLException e) {
        throw e;
    } catch (ProtocolException e) {
        throw e;
    } catch (UnsupportedEncodingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
    return (T) gson.fromJson(result, tClass);
}

From source file:rapture.kernel.AdminApiImpl.java

@Override
public Boolean verifyUser(CallingContext context, String userName, String token) {
    checkParameter("User", userName);
    checkParameter("Token", token);
    RaptureUser user = getUser(context, userName);
    boolean match = user.getVerified();

    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 .  co m*/
    if (!match) {
        match = token.equals(user.getRegistrationToken());
        if (match) {
            user.setRegistrationToken("");
            user.setVerified(true);
            RaptureUserStorage.add(user, context.getUser(),
                    adminMessageCatalog.getMessage("CreatedApi").toString()); //$NON-NLS-1$
        }
    }
    return match;
}

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

/**
 * make transport item from local cache if present or local file if not
 * /*from  w w  w. j  a  v  a 2 s . c om*/
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public PluginTransportItem makeTransportItem() throws NoSuchAlgorithmException, IOException {
    if (getContent() == null) {
        cacheFileContent();
        if (getContent() == null) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Content not present");
        }
    }
    PluginTransportItem result = new PluginTransportItem();
    result.setContent(getContent());
    result.setUri(uri.toString());
    result.setHash(getHash());
    return result;
}

From source file:i5.las2peer.services.gamificationLevelService.GamificationLevelService.java

/**
 * Get a level data with specific ID from database
 * @param appId applicationId//from ww  w.  ja v a  2 s.c  o  m
 * @param levelNum level number
 * @return HttpResponse Returned as JSON object
 */
@GET
@Path("/{appId}/{levelNum}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found a level"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "getlevelWithNum", notes = "Get level details with specific level number", response = LevelModel.class)
public HttpResponse getlevelWithNum(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Level number") @PathParam("levelNum") int levelNum) {

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

    LevelModel level = 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();
        try {
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_16, "" + randomLong);

            try {
                if (!levelAccess.isAppIdExist(conn, appId)) {
                    objResponse.put("message", "Cannot fetched level. 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 fetched level. 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 (!levelAccess.isLevelNumExist(conn, appId, levelNum)) {
                objResponse.put("message", "Cannot fetched level. level not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            level = levelAccess.getLevelWithNumber(conn, appId, levelNum);
            if (level != null) {
                ObjectMapper objectMapper = new ObjectMapper();
                //Set pretty printing of json
                objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

                String levelString = objectMapper.writeValueAsString(level);
                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(levelString, HttpURLConnection.HTTP_OK);
            } else {
                objResponse.put("message", "Cannot fetched level. Cannot find level with " + levelNum);
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

            }
        } catch (SQLException e) {
            e.printStackTrace();
            objResponse.put("message", "Cannot fetched level. 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 fetched level. 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 fetched level. DB Error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

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

/**
 * Delete the all tags from a given job.
 *
 * @param id The id of the job to delete the tags from.
 *           Not null/empty/blank.//  www . j  a  v  a  2  s  . c  om
 * @return Empty set if successful
 * @throws GenieException For any error
 */
@DELETE
@Path("/{id}/tags")
@ApiOperation(value = "Remove all tags from a job", notes = "Remove all the tags 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> removeAllTagsForJob(
        @ApiParam(value = "Id of the job to delete from.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called with id " + id);
    return this.jobService.removeAllTagsForJob(id);
}

From source file:rapture.kernel.SeriesApiImpl.java

@Override
public void addLongsToSeries(CallingContext context, String seriesURI, List<String> pointKeys,
        List<Long> 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.ja  v a  2 s  .c  o  m*/
    for (Long 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).addLongsToSeries(internalURI.getDocPath(), pointKeys, pointValues);
    processSearchUpdate(context, internalURI, pointKeys, pointValues);
}

From source file:i5.las2peer.services.gamificationActionService.GamificationActionService.java

/**
 * Get an action data with specific ID from database
 * @param appId applicationId/* ww  w.ja  v a 2s .  com*/
 * @param actionId action id
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}/{actionId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found an action"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "Find action for specific App ID and action ID", notes = "Returns a action", response = ActionModel.class, authorizations = @Authorization(value = "api_key"))
public HttpResponse getActionWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Action ID") @PathParam("actionId") String actionId) {

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

    ActionModel action = 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 (!actionAccess.isAppIdExist(conn, appId)) {
                    objResponse.put("message", "Cannot get action. 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 action. 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 (!actionAccess.isActionIdExist(conn, appId, actionId)) {
                objResponse.put("message", "Cannot get action. Action not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
            action = actionAccess.getActionWithId(conn, appId, actionId);
            if (action != null) {
                ObjectMapper objectMapper = new ObjectMapper();
                //Set pretty printing of json
                objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

                String actionString = objectMapper.writeValueAsString(action);
                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(actionString, HttpURLConnection.HTTP_OK);
            } else {
                objResponse.put("message", "Cannot get action. Cannot find badge with " + actionId);
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

            }
        } catch (SQLException e) {
            e.printStackTrace();
            objResponse.put("message", "Cannot get action. 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 action. 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 action. DB Error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

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

@Test
public void testResetPathsAndRef() 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, new String[] { "test.txt" }, "origin/master",
            null);/*from w  ww  . j  a  va 2  s .  c o m*/
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode());
}