Search in sources :

Example 6 with BadRequestException

use of com.google.api.server.spi.response.BadRequestException in project endpoints-java by cloudendpoints.

the class RestServletRequestParamReader method read.

@Override
public Object[] read() throws ServiceException {
    // TODO: Take charset from content-type as encoding
    try {
        EndpointMethod method = getMethod();
        if (method.getParameterClasses().length == 0) {
            return new Object[0];
        }
        HttpServletRequest servletRequest = endpointsContext.getRequest();
        JsonNode node;
        // this case, each part represents a named parameter instead.
        if (ServletFileUpload.isMultipartContent(servletRequest)) {
            try {
                ServletFileUpload upload = new ServletFileUpload();
                FileItemIterator iter = upload.getItemIterator(servletRequest);
                ObjectNode obj = (ObjectNode) objectReader.createObjectNode();
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    if (item.isFormField()) {
                        obj.put(item.getFieldName(), IoUtil.readStream(item.openStream()));
                    } else {
                        throw new BadRequestException("unable to parse multipart form field");
                    }
                }
                node = obj;
            } catch (FileUploadException e) {
                throw new BadRequestException("unable to parse multipart request", e);
            }
        } else {
            String requestBody = IoUtil.readRequestBody(servletRequest);
            logger.atFine().log("requestBody=%s", requestBody);
            // Unlike the Lily protocol, which essentially always requires a JSON body to exist (due to
            // path and query parameters being injected into the body), bodies are optional here, so we
            // create an empty body and inject named parameters to make deserialize work.
            node = Strings.isEmptyOrWhitespace(requestBody) ? objectReader.createObjectNode() : objectReader.readTree(requestBody);
        }
        if (!node.isObject()) {
            throw new BadRequestException("expected a JSON object body");
        }
        ObjectNode body = (ObjectNode) node;
        Map<String, Class<?>> parameterMap = getParameterMap(method);
        // the order of precedence is resource field > query parameter > path parameter.
        for (Enumeration<?> e = servletRequest.getParameterNames(); e.hasMoreElements(); ) {
            String parameterName = (String) e.nextElement();
            if (!body.has(parameterName)) {
                Class<?> parameterClass = parameterMap.get(parameterName);
                ApiParameterConfig parameterConfig = parameterConfigMap.get(parameterName);
                if (parameterClass != null && parameterConfig.isRepeated()) {
                    ArrayNode values = body.putArray(parameterName);
                    for (String value : servletRequest.getParameterValues(parameterName)) {
                        values.add(value);
                    }
                } else {
                    body.put(parameterName, servletRequest.getParameterValues(parameterName)[0]);
                }
            }
        }
        for (Entry<String, String> entry : rawPathParameters.entrySet()) {
            String parameterName = entry.getKey();
            Class<?> parameterClass = parameterMap.get(parameterName);
            if (parameterClass != null && !body.has(parameterName)) {
                if (parameterConfigMap.get(parameterName).isRepeated()) {
                    ArrayNode values = body.putArray(parameterName);
                    for (String value : COMPOSITE_PATH_SPLITTER.split(entry.getValue())) {
                        values.add(value);
                    }
                } else {
                    body.put(parameterName, entry.getValue());
                }
            }
        }
        for (Entry<String, ApiParameterConfig> entry : parameterConfigMap.entrySet()) {
            if (!body.has(entry.getKey()) && entry.getValue().getDefaultValue() != null) {
                body.put(entry.getKey(), entry.getValue().getDefaultValue());
            }
        }
        return deserializeParams(body);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException e) {
        logger.atInfo().withCause(e).log("Unable to read request parameter(s)");
        throw new BadRequestException(e);
    }
}
Also used : ApiParameterConfig(com.google.api.server.spi.config.model.ApiParameterConfig) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) EndpointMethod(com.google.api.server.spi.EndpointMethod) BadRequestException(com.google.api.server.spi.response.BadRequestException) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 7 with BadRequestException

use of com.google.api.server.spi.response.BadRequestException in project endpoints-java by cloudendpoints.

the class ServletRequestParamReader method deserializeParams.

protected Object[] deserializeParams(JsonNode node) throws IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ServiceException {
    EndpointMethod method = getMethod();
    Class<?>[] paramClasses = method.getParameterClasses();
    TypeToken<?>[] paramTypes = method.getParameterTypes();
    Object[] params = new Object[paramClasses.length];
    List<String> parameterNames = getParameterNames(method);
    for (int i = 0; i < paramClasses.length; i++) {
        TypeToken<?> type = paramTypes[i];
        Class<?> clazz = paramClasses[i];
        if (User.class.isAssignableFrom(clazz)) {
            // User type parameter requires no Named annotation (ignored if present)
            User user = getUser();
            if (user == null && methodConfig != null && methodConfig.getAuthLevel() == AuthLevel.REQUIRED) {
                throw new UnauthorizedException("Valid user credentials are required.");
            }
            if (user == null || clazz.isAssignableFrom(user.getClass())) {
                params[i] = user;
                logger.atFine().log("deserialize: User injected into param[%d]", i);
            } else {
                logger.atWarning().log("deserialize: User object of type %s is not assignable to %s. User will be null.", user.getClass().getName(), clazz.getName());
            }
        } else if (APPENGINE_USER_CLASS_NAME.equals(clazz.getName())) {
            // User type parameter requires no Named annotation (ignored if present)
            com.google.appengine.api.users.User appEngineUser = getAppEngineUser();
            if (appEngineUser == null && methodConfig != null && methodConfig.getAuthLevel() == AuthLevel.REQUIRED) {
                throw new UnauthorizedException("Valid user credentials are required.");
            }
            params[i] = appEngineUser;
            logger.atFine().log("deserialize: App Engine User injected into param[%d]", i);
        } else if (clazz == HttpServletRequest.class) {
            // HttpServletRequest type parameter requires no Named annotation (ignored if present)
            params[i] = endpointsContext.getRequest();
            logger.atFine().log("deserialize: HttpServletRequest injected into param[%d]", i);
        } else if (clazz == ServletContext.class) {
            // ServletContext type parameter requires no Named annotation (ignored if present)
            params[i] = servletContext;
            logger.atFine().log("deserialize: ServletContext %s injected into param[%d]", params[i], i);
        } else {
            String name = parameterNames.get(i);
            if (Strings.isNullOrEmpty(name)) {
                params[i] = (node == null) ? null : objectReader.forType(clazz).readValue(node);
                logger.atFine().log("deserialize: %s %s injected into unnamed param[%d]", clazz, params[i], i);
            } else if (StandardParameters.isStandardParamName(name)) {
                params[i] = getStandardParamValue(node, name);
            } else {
                JsonNode nodeValue = node.get(name);
                if (nodeValue == null) {
                    params[i] = null;
                } else {
                    // Check for collection type
                    if (Collection.class.isAssignableFrom(clazz) && type.getType() instanceof ParameterizedType) {
                        params[i] = deserializeCollection(clazz, (ParameterizedType) type.getType(), nodeValue);
                    } else {
                        params[i] = objectReader.forType(clazz).readValue(nodeValue);
                    }
                }
                if (params[i] == null && isRequiredParameter(method, i)) {
                    throw new BadRequestException("null value for parameter '" + name + "' not allowed");
                }
                logger.atFine().log("deserialize: %s %s injected into param[%d] named {%s}", clazz, params[i], i, name);
            }
        }
    }
    return params;
}
Also used : User(com.google.api.server.spi.auth.common.User) JsonNode(com.fasterxml.jackson.databind.JsonNode) ParameterizedType(java.lang.reflect.ParameterizedType) TypeToken(com.google.common.reflect.TypeToken) UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) EndpointMethod(com.google.api.server.spi.EndpointMethod) ServletContext(javax.servlet.ServletContext) Collection(java.util.Collection) BadRequestException(com.google.api.server.spi.response.BadRequestException)

Example 8 with BadRequestException

use of com.google.api.server.spi.response.BadRequestException in project cryptonomica by Cryptonomica.

the class OnlineVerificationAPI method approve.

// end of acceptTerms();
// /* --- Approve online verification (for Cryptonomica Complience Officer)  */
@ApiMethod(name = "approve", path = "approve", httpMethod = ApiMethod.HttpMethod.POST)
@SuppressWarnings("unused")
public BooleanWrapperObject approve(// final HttpServletRequest httpServletRequest,
final User googleUser, @Named("onlineVerificationApproved") final Boolean onlineVerificationApproved, @Named("verificationNotes") final String verificationNotes, @Named("fingerprint") final String fingerprint) throws // see: https://cloud.google.com/appengine/docs/java/endpoints/exceptions
UnauthorizedException, BadRequestException, NotFoundException, NumberParseException, IllegalArgumentException {
    /* --- Check authorization : CRYPTONOMICA OFFICER ONLY !!! */
    CryptonomicaUser cryptonomicaUser = UserTools.ensureCryptonomicaOfficer(googleUser);
    /* --- Check input: */
    if (fingerprint == null || fingerprint.equals("") || fingerprint.length() != 40) {
        throw new BadRequestException("fingerprint is missing or invalid");
    }
    if (onlineVerificationApproved == null) {
        throw new IllegalArgumentException("onlineVerificationApproved is null");
    } else if (onlineVerificationApproved == false) {
        throw new BadRequestException("onlineVerificationApproved (checkbox): false");
    }
    // Check if OnlineVerification entity exists:
    OnlineVerification onlineVerification = ofy().load().key(Key.create(OnlineVerification.class, fingerprint)).now();
    if (onlineVerification == null) {
        throw new NotFoundException("OnlineVeriication entity for fingerprint " + fingerprint + " does not exist in data base");
    } else if (onlineVerification.getOnlineVerificationDataVerified() != null && onlineVerification.getOnlineVerificationDataVerified()) {
        throw new BadRequestException("OnlineVerification already approved");
    }
    // mark Online Verification as approved:
    // <<<<<< !!!
    onlineVerification.setOnlineVerificationDataVerified(onlineVerificationApproved);
    onlineVerification.setVerifiedById(googleUser.getUserId());
    onlineVerification.setVerifiedByFirstNameLastName(cryptonomicaUser.getFirstName() + " " + cryptonomicaUser.getLastName());
    onlineVerification.setVerifiedOn(new Date());
    onlineVerification.setVerificationNotes(verificationNotes);
    // mark key as verified:
    PGPPublicKeyData pgpPublicKeyData = ofy().load().type(PGPPublicKeyData.class).filter("fingerprintStr", fingerprint).first().now();
    if (pgpPublicKeyData == null) {
        throw new NotFoundException("Key with fingerprint " + fingerprint + " not found");
    }
    // 
    pgpPublicKeyData.setOnlineVerificationFinished(Boolean.TRUE);
    pgpPublicKeyData.setNationality(onlineVerification.getNationality().toUpperCase());
    // save data to data store:
    ofy().save().entity(onlineVerification).now();
    ofy().save().entity(pgpPublicKeyData).now();
    // Send email to user:
    final Queue queue = QueueFactory.getDefaultQueue();
    queue.add(TaskOptions.Builder.withUrl("/_ah/SendGridServlet").param("email", onlineVerification.getUserEmail().getEmail()).param("emailCC", "verification@cryptonomica.net").param("messageSubject", "[cryptonomica] Online verification for key: " + onlineVerification.getKeyID() + " approved").param("messageText", "Congratulation! \n\n" + onlineVerification.getFirstName().toUpperCase() + " " + onlineVerification.getLastName().toUpperCase() + ",\n\n" + "your request for online verification for key with fingerprint : " + fingerprint + " approved! \n\n" + "See verification information on:\n" + "https://cryptonomica.net/#/onlineVerificationView/" + fingerprint + "\n" + "(information is not public, you have to login with your google account " + onlineVerification.getUserEmail().getEmail() + ")\n\n" + "Best regards, \n\n" + "Cryptonomica team\n\n" + new Date().toString() + "\n\n" + "if you think it's wrong or it is an error, " + "please write to support@cryptonomica.net\n\n"));
    // create result object:
    BooleanWrapperObject result = new BooleanWrapperObject(onlineVerificationApproved, "Online Verification for key " + fingerprint + " approved");
    return result;
}
Also used : BadRequestException(com.google.api.server.spi.response.BadRequestException) NotFoundException(com.google.api.server.spi.response.NotFoundException) BooleanWrapperObject(net.cryptonomica.returns.BooleanWrapperObject) Queue(com.google.appengine.api.taskqueue.Queue) Date(java.util.Date) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 9 with BadRequestException

use of com.google.api.server.spi.response.BadRequestException in project cryptonomica by Cryptonomica.

the class VerificationAPI method getVerificationByWebSafeString.

// end: getVerificationByID
/* --- Get verification info by web-safe key string: */
@ApiMethod(name = "getVerificationByWebSafeString", path = "getVerificationByWebSafeString", httpMethod = ApiMethod.HttpMethod.GET)
@SuppressWarnings("unused")
public VerificationGeneralView getVerificationByWebSafeString(final HttpServletRequest httpServletRequest, final User googleUser, @Named("verificationWebSafeString") final String verificationWebSafeString) throws // see: https://cloud.google.com/appengine/docs/java/endpoints/exceptions
UnauthorizedException, BadRequestException, NotFoundException {
    /* --- Check authorization: */
    CryptonomicaUser cryptonomicaUser = UserTools.ensureCryptonomicaRegisteredUser(googleUser);
    /* --- Check input: */
    if (verificationWebSafeString == null || verificationWebSafeString.equals("")) {
        throw new BadRequestException("Verification ID missing");
    }
    /* --- Load verification entity from DS: */
    Key<Verification> verificationKey = Key.create(verificationWebSafeString);
    Verification verification = ofy().load().key(verificationKey).now();
    if (verification == null) {
        throw new NotFoundException("Verification info not found");
    }
    /* --- Create new verification info representation: */
    VerificationGeneralView verificationGeneralView = new VerificationGeneralView(verification);
    LOG.warning(new Gson().toJson(verificationGeneralView));
    return verificationGeneralView;
}
Also used : BadRequestException(com.google.api.server.spi.response.BadRequestException) NotFoundException(com.google.api.server.spi.response.NotFoundException) Gson(com.google.gson.Gson) Verification(net.cryptonomica.entities.Verification) VerificationGeneralView(net.cryptonomica.returns.VerificationGeneralView) CryptonomicaUser(net.cryptonomica.entities.CryptonomicaUser) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 10 with BadRequestException

use of com.google.api.server.spi.response.BadRequestException in project endpoints-java by cloudendpoints.

the class ServletRequestParamReader method read.

@Override
public Object[] read() throws ServiceException {
    // TODO: Take charset from content-type as encoding
    try {
        String requestBody = IoUtil.readStream(endpointsContext.getRequest().getInputStream());
        logger.atFine().log("requestBody=%s", requestBody);
        if (requestBody == null || requestBody.trim().isEmpty()) {
            return new Object[0];
        }
        JsonNode node = objectReader.readTree(requestBody);
        return deserializeParams(node);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException e) {
        throw new BadRequestException(e);
    }
}
Also used : BadRequestException(com.google.api.server.spi.response.BadRequestException) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

BadRequestException (com.google.api.server.spi.response.BadRequestException)11 ApiMethod (com.google.api.server.spi.config.ApiMethod)7 NotFoundException (com.google.api.server.spi.response.NotFoundException)5 UnauthorizedException (com.google.api.server.spi.response.UnauthorizedException)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 EndpointMethod (com.google.api.server.spi.EndpointMethod)2 Gson (com.google.gson.Gson)2 IOException (java.io.IOException)2 Date (java.util.Date)2 CryptonomicaUser (net.cryptonomica.entities.CryptonomicaUser)2 Verification (net.cryptonomica.entities.Verification)2 StringWrapperObject (net.cryptonomica.returns.StringWrapperObject)2 VerificationGeneralView (net.cryptonomica.returns.VerificationGeneralView)2 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 User (com.google.api.server.spi.auth.common.User)1 ApiParameterConfig (com.google.api.server.spi.config.model.ApiParameterConfig)1 ForbiddenException (com.google.api.server.spi.response.ForbiddenException)1 InternalServerErrorException (com.google.api.server.spi.response.InternalServerErrorException)1