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:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * Get a list of badges from database//from   w  w  w  .j a  va2 s  .c  o  m
 * @param appId application id
 * @param currentPage current cursor page
 * @param windowSize size of fetched data
 * @param searchPhrase search word
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Badge not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "Find badges for specific App ID", notes = "Returns a list of badges", response = BadgeModel.class, responseContainer = "List", authorizations = @Authorization(value = "api_key"))
public HttpResponse getBadgeList(
        @ApiParam(value = "Application ID that contains badges", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Page number cursor for retrieving data") @QueryParam("current") int currentPage,
        @ApiParam(value = "Number of data size per fetch") @QueryParam("rowCount") int windowSize,
        @ApiParam(value = "Search phrase parameter") @QueryParam("searchPhrase") String searchPhrase) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "GET " + "gamification/badges/" + appId);

    List<BadgeModel> badges = 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(this, Event.AGENT_GET_STARTED, "Get Badges");

        try {
            if (!badgeAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get badges. 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();
            logger.info(
                    "Cannot check whether application ID exist or not. Database error. >> " + e1.getMessage());
            objResponse.put("message",
                    "Cannot get badges. 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);
        }
        // Check app id exist or not

        int offset = (currentPage - 1) * windowSize;

        int totalNum = badgeAccess.getNumberOfBadges(conn, appId);

        if (windowSize == -1) {
            offset = 0;
            windowSize = totalNum;
        }

        badges = badgeAccess.getBadgesWithOffsetAndSearchPhrase(conn, appId, offset, windowSize, searchPhrase);

        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        String badgeString = objectMapper.writeValueAsString(badges);
        JSONArray badgeArray = (JSONArray) JSONValue.parse(badgeString);

        objResponse.put("current", currentPage);
        objResponse.put("rowCount", windowSize);
        objResponse.put("rows", badgeArray);
        objResponse.put("total", totalNum);
        logger.info(objResponse.toJSONString());
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24,
                "Badges fetched" + " : " + appId + " : " + userAgent);
        L2pLogger.logEvent(this, Event.AGENT_GET_SUCCESS, "Badges fetched" + " : " + appId + " : " + userAgent);

        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot get badges. Internal Error. Database connection failed. " + e.getMessage());

        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get badges. Cannot connect to database. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }

}

From source file:rapture.kernel.DocApiImpl.java

@Override
public List<XferDocumentAttribute> getDocAttributes(CallingContext context, String attributeUri) {
    RaptureURI internalUri = new RaptureURI(attributeUri, Scheme.DOCUMENT);

    if (!internalUri.hasAttribute()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Invalid arguments supplied");
    }/*from   w  w  w  . j a  v  a 2s  .  c o  m*/

    // check if a valid attribute type was provided
    DocumentAttributeFactory.create(internalUri.getAttributeName());

    Repository repository = getRepoFromCache(internalUri.getAuthority());

    if (repository == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoSuchRepo", internalUri.toAuthString())); //$NON-NLS-1$
    }
    return Lists.transform(repository.getDocAttributes(internalUri), xferFunc);
}

From source file:rapture.kernel.DocApiImpl.java

@Override
public Boolean deleteDocAttribute(CallingContext context, String attributeUri) {
    RaptureURI internalUri = new RaptureURI(attributeUri, Scheme.DOCUMENT);

    if (!internalUri.hasAttribute() || internalUri.getAttributeKey() == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                "Invalid arguments supplied -- need attribute and attribute key to be set");
    }// w w w.jav a  2 s  .  c  o m

    Repository repository = getRepoFromCache(internalUri.getAuthority());

    if (repository == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoSuchRepo", internalUri.toAuthString())); //$NON-NLS-1$
    }
    return repository.deleteDocAttribute(internalUri);
}

From source file:rapture.kernel.DocApiImpl.java

@Override
public XferDocumentAttribute getDocAttribute(CallingContext context, String attributeUri) {
    RaptureURI internalUri = new RaptureURI(attributeUri, Scheme.DOCUMENT);

    if (!internalUri.hasAttribute() || internalUri.getAttributeKey() == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                "Invalid arguments supplied: attribute and attribute key must be set");
    }//from  w  w w.  j  a  va  2 s .  co m

    Repository repository = getRepoFromCache(internalUri.getAuthority());

    if (repository == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoSuchRepo", internalUri.toAuthString())); //$NON-NLS-1$
    }

    return xferFunc.apply(repository.getDocAttribute(internalUri));
}

From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * Fetch a badge image with specified ID
 * @param appId application id/*w w  w  .  j  a  va2s  . c o m*/
 * @param badgeId badge id
 * @return HttpResponse and return the image
 */
@GET
@Path("/{appId}/{badgeId}/img")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Badges Entry"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot found image") })
@ApiOperation(value = "", notes = "list of stored badges")
public HttpResponse getBadgeImage(@PathParam("appId") String appId, @PathParam("badgeId") String badgeId) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "GET " + "gamification/badges/" + appId + "/" + badgeId + "/img");

    JSONObject objResponse = new JSONObject();
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(this, Event.AGENT_GET_STARTED, "Get Badge Image");
        L2pLogger.logEvent(this, Event.ARTIFACT_FETCH_STARTED, "Get Badge Image");

        try {
            if (!badgeAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get badge image. 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 badge image. 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 (!badgeAccess.isBadgeIdExist(conn, appId, badgeId)) {
            objResponse.put("message", "Cannot get badge image. Badge not found");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
        byte[] filecontent = getBadgeImageMethod(appId, badgeId);

        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25,
                "Badge image fetched : " + badgeId + " : " + appId + " : " + userAgent);
        L2pLogger.logEvent(this, Event.ARTIFACT_RECEIVED,
                "Badge image fetched : " + badgeId + " : " + appId + " : " + userAgent);
        return new HttpResponse(filecontent, HttpURLConnection.HTTP_OK);
    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get badge image. Database 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.betaconceptframework.astroboa.resourceapi.resource.ContentObjectResource.java

private boolean objectIsNew(String contentObjectIdOrName, String httpMethod,
        ContentObject contentObjectToBeSaved) {

    if (contentObjectIdOrName == null) {
        return true;
    }//from w w w  .j a va2  s.  c om

    ContentObject existingObject = astroboaClient.getContentService().getContentObject(contentObjectIdOrName,
            ResourceRepresentationType.CONTENT_OBJECT_INSTANCE, FetchLevel.ENTITY, CacheRegion.NONE, null,
            false);

    boolean entityIsNew = existingObject == null;

    if (CmsConstants.UUIDPattern.matcher(contentObjectIdOrName).matches()) {
        //Save content object by Id

        if (contentObjectToBeSaved.getId() == null) {
            contentObjectToBeSaved.setId(contentObjectIdOrName);
        } else {
            //Payload contains id. Check if they are the same
            if (!StringUtils.equals(contentObjectIdOrName, contentObjectToBeSaved.getId())) {
                logger.warn("Try to " + httpMethod + " content object with ID " + contentObjectIdOrName
                        + " but payload contains id " + contentObjectToBeSaved.getId());
                throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
            }
        }
    } else {
        //Save content object by SystemName
        //Check that payload contains id
        if (contentObjectToBeSaved.getId() == null) {
            if (existingObject != null) {
                //A content object with system name 'contentObjectIdOrName' exists, but in payload no id was provided
                //Set this id to ContentObject representing the payload
                contentObjectToBeSaved.setId(existingObject.getId());
            }
        } else {

            //Payload contains an id. 

            if (existingObject != null) {
                //if this is not the same with the id returned from repository raise an exception
                if (!StringUtils.equals(existingObject.getId(), contentObjectToBeSaved.getId())) {
                    logger.warn(
                            "Try to " + httpMethod + " content object with system name " + contentObjectIdOrName
                                    + " which corresponds to an existed content object in repository with id "
                                    + existingObject.getId() + " but payload contains a different id "
                                    + contentObjectToBeSaved.getId());
                    throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
                }
            }
        }
    }
    return entityIsNew;
}

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

private Response saveContentObjectString(String contentSource, String httpMethod, boolean entityIsNew,
        boolean updateLastModificationTime) {

    try {/*from   w w  w  . ja  v a  2s. c om*/

        //Must determine whether a single or a collection of objects is saved
        if (contentSource == null) {
            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        if (contentSource.contains(CmsConstants.RESOURCE_RESPONSE_PREFIXED_NAME)
                || contentSource.contains(CmsConstants.RESOURCE_COLLECTION)) {

            List<ContentObject> contentObjects = astroboaClient.getContentService()
                    .saveContentObjectResourceCollection(contentSource, false, updateLastModificationTime,
                            null);

            //TODO : Improve response details.

            ResponseBuilder responseBuilder = Response.status(Status.OK);

            responseBuilder.header("Content-Disposition", "inline");
            responseBuilder.type(MediaType.TEXT_PLAIN + "; charset=utf-8");

            return responseBuilder.build();

        } else {

            ContentObject contentObject = astroboaClient.getContentService().save(contentSource, false,
                    updateLastModificationTime, null);

            return ContentApiUtils.createResponseForPutOrPostOfACmsEntity(contentObject, httpMethod,
                    contentSource, entityIsNew);
        }

    } catch (CmsUnauthorizedAccessException e) {
        throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED);
    } catch (Exception e) {
        logger.error("", e);
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }
}

From source file:org.wso2.carbon.registry.app.RegistryAdapter.java

/**
 * Posts a new media entry.//from w  w w .  jav a2 s.  c  o m
 *
 * @param mimeType    the MIME type of the content.
 * @param slug        the slug as a String.
 * @param inputStream the content stream.
 * @param request     the request context.
 *
 * @return the generated media object.
 * @throws ResponseContextException if the operation failed.
 */
public Resource postMedia(MimeType mimeType, String slug, InputStream inputStream, RequestContext request)
        throws ResponseContextException {
    final Registry registry;
    try {
        registry = getSecureRegistry(request);
    } catch (RegistryException e) {
        throw new ResponseContextException(new StackTraceResponseContext(e));
    }

    String path = ((ResourceTarget) request.getTarget()).getResource().getPath();

    final String[] splitPath = (String[]) request.getAttribute(RequestContext.Scope.REQUEST,
            APPConstants.PARAMETER_SPLIT_PATH);
    if (splitPath != null && APPConstants.PARAMETER_COMMENTS.equals(splitPath[1])) {
        if (!mimeType.toString().equals("text/plain")) {
            throw new ResponseContextException("Can only post Atom or text/plain to comments!",
                    HttpURLConnection.HTTP_BAD_REQUEST);
        }
        // Comment post
        org.wso2.carbon.registry.core.Comment comment;
        try {
            comment = new org.wso2.carbon.registry.core.Comment(readToString(inputStream));
        } catch (IOException e) {
            throw new ResponseContextException(new StackTraceResponseContext(e));
        }
        try {
            String commentPath = registry.addComment(path, comment);
            comment.setPath(commentPath);
            comment.setParentPath(path + RegistryConstants.URL_SEPARATOR + APPConstants.PARAMETER_COMMENTS);
        } catch (RegistryException e) {
            throw new ResponseContextException(new StackTraceResponseContext(e));
        }
        return comment;
    }

    if (!path.endsWith("/")) {
        path += "/";
    }
    path += getGoodSlug(path, slug, request);
    boolean isCollection = "app/collection".equals(mimeType.toString());
    Resource ret;
    try {
        ret = isCollection ? registry.newCollection() : registry.newResource();
    } catch (RegistryException e) {
        throw new ResponseContextException(new StackTraceResponseContext(e));
    }
    ret.setMediaType(mimeType.toString());

    try {

        if (!isCollection) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[RegistryConstants.DEFAULT_BUFFER_SIZE];
            try {
                while (inputStream.available() > 0) {
                    int amount = inputStream.read(buffer, 0, RegistryConstants.DEFAULT_BUFFER_SIZE);
                    bos.write(buffer, 0, amount);
                }
            } catch (IOException e) {
                // nothing here
            }
            String content = RegistryUtils.decodeBytes(bos.toByteArray());
            ret.setContent(content);
        }

        registry.put(path, ret);
    } catch (RegistryException e) {
        throw new ResponseContextException(new StackTraceResponseContext(e));
    }
    return ret;
}