Java Code Examples for com.google.api.server.spi.config.ApiMethod.HttpMethod#POST

The following examples show how to use com.google.api.server.spi.config.ApiMethod.HttpMethod#POST . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user object.
 *
 * @param user A User object injected by the cloud endpoints.
 * @param profileForm A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException when the User object is null.
 */
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)
public Profile saveProfile(final User user, final ProfileForm profileForm)
        throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    String displayName = profileForm.getDisplayName();
    TeeShirtSize teeShirtSize = profileForm.getTeeShirtSize();

    Profile profile = ofy().load().key(Key.create(Profile.class, getUserId(user))).now();
    if (profile == null) {
        // Populate displayName and teeShirtSize with the default values if null.
        if (displayName == null) {
            displayName = extractDefaultDisplayNameFromEmail(user.getEmail());
        }
        if (teeShirtSize == null) {
            teeShirtSize = TeeShirtSize.NOT_SPECIFIED;
        }
        profile = new Profile(getUserId(user), displayName, user.getEmail(), teeShirtSize);
    } else {
        profile.update(displayName, teeShirtSize);
    }
    ofy().save().entity(profile).now();
    return profile;
}
 
Example 2
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Queries against the datastore with the given filters and returns the result.
 *
 * Normally this kind of method is supposed to get invoked by a GET HTTP method,
 * but we do it with POST, in order to receive conferenceQueryForm Object via the POST body.
 *
 * @param conferenceQueryForm A form object representing the query.
 * @return A List of Conferences that match the query.
 */
@ApiMethod(
        name = "queryConferences",
        path = "queryConferences",
        httpMethod = HttpMethod.POST
)
public List<Conference> queryConferences(ConferenceQueryForm conferenceQueryForm) {
    Iterable<Conference> conferenceIterable = conferenceQueryForm.getQuery();
    List<Conference> result = new ArrayList<>(0);
    List<Key<Profile>> organizersKeyList = new ArrayList<>(0);
    for (Conference conference : conferenceIterable) {
        organizersKeyList.add(Key.create(Profile.class, conference.getOrganizerUserId()));
        result.add(conference);
    }
    // To avoid separate datastore gets for each Conference, pre-fetch the Profiles.
    ofy().load().keys(organizersKeyList);
    return result;
}
 
Example 3
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a list of Conferences that the user created.
 * In order to receive the websafeConferenceKey via the JSON params, uses a POST method.
 *
 * @param user A user who invokes this method, null when the user is not signed in.
 * @return a list of Conferences that the user created.
 * @throws UnauthorizedException when the user is not signed in.
 */
@ApiMethod(
        name = "getConferencesCreated",
        path = "getConferencesCreated",
        httpMethod = HttpMethod.POST
)
public List<Conference> getConferencesCreated(final User user) throws UnauthorizedException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }
    String userId = user.getUserId();
    Key<Profile> userKey = Key.create(Profile.class, userId);
    return ofy().load().type(Conference.class)
            .ancestor(userKey)
            .order("name").list();
}
 
Example 4
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Queries against the datastore with the given filters and returns the result.
 *
 * Normally this kind of method is supposed to get invoked by a GET HTTP method,
 * but we do it with POST, in order to receive conferenceQueryForm Object via the POST body.
 *
 * @param conferenceQueryForm A form object representing the query.
 * @return A List of Conferences that match the query.
 */
@ApiMethod(
        name = "queryConferences",
        path = "queryConferences",
        httpMethod = HttpMethod.POST
)
public List<Conference> queryConferences(ConferenceQueryForm conferenceQueryForm) {
    Iterable<Conference> conferenceIterable = conferenceQueryForm.getQuery();
    List<Conference> result = new ArrayList<>(0);
    List<Key<Profile>> organizersKeyList = new ArrayList<>(0);
    for (Conference conference : conferenceIterable) {
        organizersKeyList.add(Key.create(Profile.class, conference.getOrganizerUserId()));
        result.add(conference);
    }
    // To avoid separate datastore gets for each Conference, pre-fetch the Profiles.
    ofy().load().keys(organizersKeyList);
    return result;
}
 
Example 5
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
/** Code to add at the start of querying for conferences **/


    @ApiMethod(
            name = "queryConferences_nofilters",
            path = "queryConferences_nofilters",
            httpMethod = HttpMethod.POST
    )
    public List<Conference> queryConferences_nofilters() {
        // Find all entities of type Conference
        Query<Conference> query = ofy().load().type(Conference.class).order("name");

        return query.list();
    }
 
Example 6
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 5 votes vote down vote up
@ApiMethod(
        name = "queryConferences_nofilters",
        path = "queryConferences_nofilters",
        httpMethod = HttpMethod.POST
)
public List<Conference> queryConferences_nofilters() {
    // Find all entities of type Conference
    Query<Conference> query = ofy().load().type(Conference.class).order("name");

    return query.list();
}
 
Example 7
Source File: WaxEndpoint.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Remove an existing session.
 * <p>
 * Clients that create sessions without a duration (will last forever) will need to call this
 * method on their own to clean up the session.
 *
 * @return {@link WaxRemoveSessionResponse} with the deleted session id
 * @throws InternalServerErrorException if the session deletion failed
 */
@ApiMethod(
    name = "sessions.remove",
    path = "removesession",
    httpMethod = HttpMethod.POST)
public WaxRemoveSessionResponse removeSession(@Named("sessionId") String sessionId)
    throws InternalServerErrorException {
  try {
    store.deleteSession(sessionId);
    return new WaxRemoveSessionResponse(sessionId);
  } catch (InvalidSessionException e) {
    throw new InternalServerErrorException(e.getMessage());
  }
}
 
Example 8
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Register to attend the specified Conference.
 *
 * @param user An user who invokes this method, null when the user is not signed in.
 * @param websafeConferenceKey The String representation of the Conference Key.
 * @return Boolean true when success, otherwise false
 * @throws UnauthorizedException when the user is not signed in.
 * @throws NotFoundException when there is no Conference with the given conferenceId.
 */
@ApiMethod(
        name = "registerForConference",
        path = "conference/{websafeConferenceKey}/registration",
        httpMethod = HttpMethod.POST
)

public WrappedBoolean registerForConference(final User user,
        @Named("websafeConferenceKey") final String websafeConferenceKey)
        throws UnauthorizedException, NotFoundException,
        ForbiddenException, ConflictException {
    // If not signed in, throw a 401 error.
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // Get the userId
    final String userId = user.getUserId();

    WrappedBoolean result = ofy().transact(new Work<WrappedBoolean>() {
        @Override
        public WrappedBoolean run() {
            try {

            // Get the conference key
            // Will throw ForbiddenException if the key cannot be created
            Key<Conference> conferenceKey = Key.create(websafeConferenceKey);

            // Get the Conference entity from the datastore
            Conference conference = ofy().load().key(conferenceKey).now();

            // 404 when there is no Conference with the given conferenceId.
            if (conference == null) {
                return new WrappedBoolean (false,
                        "No Conference found with key: "
                                + websafeConferenceKey);
            }

            // Get the user's Profile entity
            Profile profile = getProfileFromUser(user);

            // Has the user already registered to attend this conference?
            if (profile.getConferenceKeysToAttend().contains(
                    websafeConferenceKey)) {
                return new WrappedBoolean (false, "Already registered");
            } else if (conference.getSeatsAvailable() <= 0) {
                return new WrappedBoolean (false, "No seats available");
            } else {
                // All looks good, go ahead and book the seat
                profile.addToConferenceKeysToAttend(websafeConferenceKey);
                conference.bookSeats(1);

                // Save the Conference and Profile entities
                ofy().save().entities(profile, conference).now();
                // We are booked!
                return new WrappedBoolean(true, "Registration successful");
            }

            }
            catch (Exception e) {
                return new WrappedBoolean(false, "Unknown exception");

            }
        }
    });
    // if result is false
    if (!result.getResult()) {
        if (result.getReason().contains("No Conference found with key")) {
            throw new NotFoundException (result.getReason());
        }
        else if (result.getReason() == "Already registered") {
            throw new ConflictException("You have already registered");
        }
        else if (result.getReason() == "No seats available") {
            throw new ConflictException("There are no seats available");
        }
        else {
            throw new ForbiddenException("Unknown exception");
        }
    }
    return result;
}
 
Example 9
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user
 * object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @param profileForm
 *            A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException
 *             when the User object is null.
 */

// Declare this method as a method available externally through Endpoints
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)
// The request that invokes this method should provide data that
// conforms to the fields defined in ProfileForm
// TODO 1 Pass the ProfileForm parameter
// TODO 2 Pass the User parameter
public Profile saveProfile(final User user, ProfileForm profileForm)
        throws UnauthorizedException {

    // TODO 2
    // If the user is not logged in, throw an UnauthorizedException
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO 2
    // Get the userId and mainEmail
    String mainEmail = user.getEmail();
    String userId = user.getUserId();

    // TODO 1
    // Get the displayName and teeShirtSize sent by the request.

    String displayName = profileForm.getDisplayName();
    TeeShirtSize teeShirtSize = profileForm.getTeeShirtSize();

    // Get the Profile from the datastore if it exists
    // otherwise create a new one
    Profile profile = ofy().load().key(Key.create(Profile.class, userId))
            .now();

    if (profile == null) {
        // Populate the displayName and teeShirtSize with default values
        // if not sent in the request
        if (displayName == null) {
            displayName = extractDefaultDisplayNameFromEmail(user
                    .getEmail());
        }
        if (teeShirtSize == null) {
            teeShirtSize = TeeShirtSize.NOT_SPECIFIED;
        }
        // Now create a new Profile entity
        profile = new Profile(userId, displayName, mainEmail, teeShirtSize);
    } else {
        // The Profile entity already exists
        // Update the Profile entity
        profile.update(displayName, teeShirtSize);
    }

    // TODO 3
    // Save the entity in the datastore
    ofy().save().entity(profile).now();

    // Return the profile
    return profile;
}
 
Example 10
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user
 * object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @param profileForm
 *            A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException
 *             when the User object is null.
 */

   // Declare this method as a method available externally through Endpoints
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)

// The request that invokes this method should provide data that
// conforms to the fields defined in ProfileForm

// TODO 1 Pass the ProfileForm parameter
// TODO 2 Pass the User parameter
public Profile saveProfile(final User user, ProfileForm profileForm)
		throws UnauthorizedException {

	String userId = "";
	String mainEmail = "";
	String displayName = "Your name will go here";
	TeeShirtSize teeShirtSize = TeeShirtSize.NOT_SPECIFIED;

	// TODO 2
	// If the user is not logged in, throw an UnauthorizedException
	if (user == null) {
           throw new UnauthorizedException("Authorization required");
       }

	// TODO 1
    // Set the teeShirtSize to the value sent by the ProfileForm, if sent
       // otherwise leave it as the default value
	 if (profileForm.getTeeShirtSize() != null) {
		 teeShirtSize = profileForm.getTeeShirtSize();
	 }

	// TODO 1
       // Set the displayName to the value sent by the ProfileForm, if sent
       // otherwise set it to null
	displayName = profileForm.getDisplayName();
	
	// TODO 2
	// Get the userId and mainEmail
	mainEmail = user.getEmail();
	userId = user.getUserId();

       // TODO 2
       // If the displayName is null, set it to the default value based on the user's email
       // by calling extractDefaultDisplayNameFromEmail(...)
	 if (displayName == null) {
	   displayName = extractDefaultDisplayNameFromEmail(user.getEmail());
	   }

	// Create a new Profile entity from the
	// userId, displayName, mainEmail and teeShirtSize
	Profile profile = new Profile(userId, displayName, mainEmail, teeShirtSize);

	// TODO 3 (In lesson 3)
	// Save the entity in the datastore

	// Return the profile
	return profile;
}
 
Example 11
Source File: EndpointsServletTest.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
@ApiMethod(httpMethod = HttpMethod.POST)
public TestResource echo(TestResource r) {
  return r;
}
 
Example 12
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates a new Conference object and stores it to the datastore.
 *
 * @param user A user who invokes this method, null when the user is not signed in.
 * @param conferenceForm A ConferenceForm object representing user's inputs.
 * @return A newly created Conference Object.
 * @throws UnauthorizedException when the user is not signed in.
 */
@ApiMethod(name = "createConference", path = "conference", httpMethod = HttpMethod.POST)
public Conference createConference(final User user, final ConferenceForm conferenceForm)
    throws UnauthorizedException {
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO (Lesson 4)
    // Get the userId of the logged in User
    String userId = user.getUserId();

    // TODO (Lesson 4)
    // Get the key for the User's Profile
    Key<Profile> profileKey = Key.create(Profile.class, userId);

    // TODO (Lesson 4)
    // Allocate a key for the conference -- let App Engine allocate the ID
    // Don't forget to include the parent Profile in the allocated ID
    final Key<Conference> conferenceKey = factory().allocateId(profileKey, Conference.class);

    // TODO (Lesson 4)
    // Get the Conference Id from the Key
    final long conferenceId = conferenceKey.getId();

    // TODO (Lesson 4)
    // Get the existing Profile entity for the current user if there is one
    // Otherwise create a new Profile entity with default values
    Profile profile = getProfileFromUser(user);

    // TODO (Lesson 4)
    // Create a new Conference Entity, specifying the user's Profile entity
    // as the parent of the conference
    Conference conference = new Conference(conferenceId, userId, conferenceForm);

    // TODO (Lesson 4)
    // Save Conference and Profile Entities
     ofy().save().entities(conference, profile).now();

     return conference;
     }
 
Example 13
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user
 * object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @param profileForm
 *            A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException
 *             when the User object is null.
 */

// Declare this method as a method available externally through Endpoints
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)
// The request that invokes this method should provide data that
// conforms to the fields defined in ProfileForm

// TODO 1 Pass the ProfileForm parameter
// TODO 2 Pass the User parameter
public Profile saveProfile() throws UnauthorizedException {

    String userId = null;
    String mainEmail = null;
    String displayName = "Your name will go here";
    TeeShirtSize teeShirtSize = TeeShirtSize.NOT_SPECIFIED;

    // TODO 2
    // If the user is not logged in, throw an UnauthorizedException

    // TODO 1
    // Set the teeShirtSize to the value sent by the ProfileForm, if sent
    // otherwise leave it as the default value

    // TODO 1
    // Set the displayName to the value sent by the ProfileForm, if sent
    // otherwise set it to null

    // TODO 2
    // Get the userId and mainEmail

    // TODO 2
    // If the displayName is null, set it to default value based on the user's email
    // by calling extractDefaultDisplayNameFromEmail(...)

    // Create a new Profile entity from the
    // userId, displayName, mainEmail and teeShirtSize
    Profile profile = new Profile(userId, displayName, mainEmail, teeShirtSize);

    // TODO 3 (In Lesson 3)
    // Save the Profile entity in the datastore

    // Return the profile
    return profile;
}
 
Example 14
Source File: NonDiscoverableEndpoint.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
@ApiMethod(name = "foo.update", description = "update desc", path = "foos/{id}",
    httpMethod = HttpMethod.POST)
public Foo updateFoo(@Named("id") @Description("id desc") String id, Foo foo) {
  return null;
}
 
Example 15
Source File: FooEndpoint.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
@ApiMethod(name = "toplevel", path = "foos", httpMethod = HttpMethod.POST)
public CollectionResponse<Foo> toplevel() {
  return null;
}
 
Example 16
Source File: FooEndpoint.java    From endpoints-java with Apache License 2.0 4 votes vote down vote up
@ApiMethod(name = "foo.update", description = "update desc", path = "foos/{id}",
    httpMethod = HttpMethod.POST)
public Foo updateFoo(@Named("id") @Description("id desc") String id, Foo foo) {
  return null;
}
 
Example 17
Source File: ConferenceApi.java    From ud859 with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates or updates a Profile object associated with the given user
 * object.
 *
 * @param user
 *            A User object injected by the cloud endpoints.
 * @param profileForm
 *            A ProfileForm object sent from the client form.
 * @return Profile object just created.
 * @throws UnauthorizedException
 *             when the User object is null.
 */

// Declare this method as a method available externally through Endpoints
@ApiMethod(name = "saveProfile", path = "profile", httpMethod = HttpMethod.POST)
// The request that invokes this method should provide data that
// conforms to the fields defined in ProfileForm
// TODO 1 Pass the ProfileForm parameter
// TODO 2 Pass the User parameter
public Profile saveProfile(final User user, ProfileForm profileForm)
        throws UnauthorizedException {

    // TODO 2
    // If the user is not logged in, throw an UnauthorizedException
    if (user == null) {
        throw new UnauthorizedException("Authorization required");
    }

    // TODO 2
    // Get the userId and mainEmail
    String mainEmail = user.getEmail();
    String userId = user.getUserId();

    // TODO 1
    // Get the displayName and teeShirtSize sent by the request.

    String displayName = profileForm.getDisplayName();
    TeeShirtSize teeShirtSize = profileForm.getTeeShirtSize();

    // Get the Profile from the datastore if it exists
    // otherwise create a new one
    Profile profile = ofy().load().key(Key.create(Profile.class, userId))
            .now();

    if (profile == null) {
        // Populate the displayName and teeShirtSize with default values
        // if not sent in the request
        if (displayName == null) {
            displayName = extractDefaultDisplayNameFromEmail(user
                    .getEmail());
        }
        if (teeShirtSize == null) {
            teeShirtSize = TeeShirtSize.NOT_SPECIFIED;
        }
        // Now create a new Profile entity
        profile = new Profile(userId, displayName, mainEmail, teeShirtSize);
    } else {
        // The Profile entity already exists
        // Update the Profile entity
        profile.update(displayName, teeShirtSize);
    }

    // TODO 3
    // Save the entity in the datastore
    ofy().save().entity(profile).now();

    // Return the profile
    return profile;
}
 
Example 18
Source File: EndpointV1.java    From solutions-mobile-backend-starter-java with Apache License 2.0 3 votes vote down vote up
/**
 * Inserts a CloudEntity on the backend. If it does not have any Id, it
 * creates a new Entity. If it has, find the existing entity and update it.
 *
 * @param cd
 *          {@link EntityDto} for inserting a CloudEntity.
 * @param user
 *          {@link User} who called this request.
 * @return {@link EntityDto} that has updated fields (like updatedAt and new
 *         Id).
 * @throws UnauthorizedException
 *           if the requesting {@link User} has no sufficient permission for
 *           the operation.
 */
@ApiMethod(path = "CloudEntities/insert/{kind}", httpMethod = HttpMethod.POST)
public EntityDto insert(@Named("kind") String kindName, EntityDto cd, User user)
    throws UnauthorizedException {

  SecurityChecker.getInstance().checkIfUserIsAvailable(user);
  EntityListDto cdl = new EntityListDto();
  cdl.add(cd);
  CrudOperations.getInstance().saveAll(cdl, user);
  return cd;
}
 
Example 19
Source File: EndpointV1.java    From io2014-codelabs with Apache License 2.0 3 votes vote down vote up
/**
 * Deletes all the CloudEntities specified by the List of Ids.
 *
 * @param cdl
 *          {@link com.google.cloud.backend.beans.EntityListDto} that contains a list of Ids to delete.
 * @return {@link com.google.cloud.backend.beans.EntityListDto} of a dummy {@link com.google.cloud.backend.beans.EntityDto}s (Endpoints
 *         requires to return any bean object).
 * @throws com.google.api.server.spi.response.UnauthorizedException
 *           if the requesting {@link com.google.appengine.api.users.User} has no sufficient permission for
 *           the operation.
 */
@ApiMethod(path = "CloudEntities/deleteAll", httpMethod = HttpMethod.POST)
// DELETE can't have content body
public EntityListDto deleteAll(EntityListDto cdl, User user) throws UnauthorizedException {

  SecurityChecker.getInstance().checkIfUserIsAvailable(user);
  return CrudOperations.getInstance().deleteAll(cdl, user);
}
 
Example 20
Source File: EndpointV1.java    From io2014-codelabs with Apache License 2.0 3 votes vote down vote up
/**
 * Inserts multiple CloudEntities on the backend. Works just the same as
 * {@link EndpointV1#insert(String, com.google.cloud.backend.beans.EntityDto, com.google.appengine.api.users.User)}
 *
 * @param cdl
 *          {@link com.google.cloud.backend.beans.EntityListDto} that holds {@link com.google.cloud.backend.beans.EntityDto}s to save.
 * @param user
 *          {@link com.google.appengine.api.users.User} who called this request.
 * @return {@link com.google.cloud.backend.beans.EntityListDto} that has updated {@link com.google.cloud.backend.beans.EntityDto}s.
 * @throws com.google.api.server.spi.response.UnauthorizedException
 *           if the requesting {@link com.google.appengine.api.users.User} has no sufficient permission for
 *           the operation.
 */
@ApiMethod(path = "CloudEntities/insertAll", httpMethod = HttpMethod.POST)
// the path need to include the op name to distinguish between saveAll and
// getAll.
public EntityListDto insertAll(EntityListDto cdl, User user) throws UnauthorizedException {

  SecurityChecker.getInstance().checkIfUserIsAvailable(user);
  return CrudOperations.getInstance().saveAll(cdl, user);
}