Search in sources :

Example 21 with ApiMethod

use of com.google.api.server.spi.config.ApiMethod in project iosched by google.

the class CmsUpdateEndpoint method getDataFromCms.

/**
 * Retrieve session data from CMS and make it ready for processing.
 *
 * @param user User making the request (injected by Endpoints)
 * @throws UnauthorizedException
 * @throws IOException
 */
@ApiMethod(name = "getDataFromCms", path = "topics")
public void getDataFromCms(User user) throws UnauthorizedException, IOException {
    if (user == null || !isAllowed(user)) {
        throw new UnauthorizedException("Invalid credentials");
    }
    // everything ok, let's update
    StringBuilder summary = new StringBuilder();
    JsonObject contents = new JsonObject();
    JsonDataSources sources = new VendorDynamicInput().fetchAllDataSources();
    for (String entity : sources) {
        JsonArray array = new JsonArray();
        JsonDataSource source = sources.getSource(entity);
        for (JsonObject obj : source) {
            array.add(obj);
        }
        summary.append(entity).append(": ").append(source.size()).append("\n");
        contents.add(entity, array);
    }
    // Fetch new images and set up serving URLs.
    new ImageUpdater().run(sources);
    // Write file to cloud storage
    CloudFileManager fileManager = new CloudFileManager();
    fileManager.createOrUpdate("__raw_session_data.json", contents, true);
}
Also used : JsonArray(com.google.gson.JsonArray) JsonDataSource(com.google.samples.apps.iosched.server.schedule.model.JsonDataSource) CloudFileManager(com.google.samples.apps.iosched.server.schedule.server.cloudstorage.CloudFileManager) ImageUpdater(com.google.samples.apps.iosched.server.schedule.server.image.ImageUpdater) JsonDataSources(com.google.samples.apps.iosched.server.schedule.model.JsonDataSources) UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) JsonObject(com.google.gson.JsonObject) VendorDynamicInput(com.google.samples.apps.iosched.server.schedule.server.input.VendorDynamicInput) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 22 with ApiMethod

use of com.google.api.server.spi.config.ApiMethod in project iosched by google.

the class FcmRegistrationEndpoint method unregister.

/**
 * Remove a registration of a user's device. When a user signs out of a client they should
 * unregister. This will prevent messages from being sent to the wrong user if multiple users
 * are using the same device.
 *
 * @param deviceId FCM token representing the device.
 * @return Result containing a message about the un-registration.
 * @throws BadRequestException Thrown when there is no device ID in the request.
 */
@ApiMethod(path = "unregister", httpMethod = HttpMethod.POST)
public void unregister(User user, @Named(PARAMETER_DEVICE_ID) String deviceId) throws BadRequestException, UnauthorizedException, com.google.api.server.spi.response.NotFoundException, ForbiddenException {
    // Check to see if deviceId.
    if (Strings.isNullOrEmpty(deviceId)) {
        // Drop request.
        throw new BadRequestException("Invalid request: Request must contain " + PARAMETER_DEVICE_ID);
    }
    // Check that user making requests is non null.
    if (user == null) {
        throw new UnauthorizedException("Invalid credentials");
    }
    try {
        Device device = ofy().load().type(Device.class).id(deviceId).safe();
        // Check that the user trying to unregister the token is the same one that registered it.
        if (!device.getUserId().equals(user.getId())) {
            throw new ForbiddenException("Not authorized to unregister token");
        }
        DeviceStore.unregister(deviceId);
    } catch (NotFoundException e) {
        throw new com.google.api.server.spi.response.NotFoundException("Device ID: " + deviceId + " not found");
    }
}
Also used : ForbiddenException(com.google.api.server.spi.response.ForbiddenException) Device(com.google.samples.apps.iosched.server.gcm.db.models.Device) UnauthorizedException(com.google.api.server.spi.response.UnauthorizedException) BadRequestException(com.google.api.server.spi.response.BadRequestException) NotFoundException(com.googlecode.objectify.NotFoundException) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 23 with ApiMethod

use of com.google.api.server.spi.config.ApiMethod in project iosched by google.

the class FcmSendEndpoint method sendFeedPing.

/**
 * Ping all users' devices to update UI indicating that the feed has been updated.
 *
 * @param context Servlet context (injected by Endpoints)
 * @param user User making the request (injected by Endpoints)
 */
@ApiMethod(name = "sendFeedPing", path = "feed", clientIds = { Ids.SERVICE_ACCOUNT_CLIENT_ID })
public void sendFeedPing(ServletContext context, User user) throws UnauthorizedException {
    validateServiceAccount(user);
    MessageSender sender = new MessageSender(context);
    List<Device> devices = DeviceStore.getAllDevices();
    sender.multicastSend(devices, "feed_update", null);
}
Also used : MessageSender(com.google.samples.apps.iosched.server.gcm.device.MessageSender) Device(com.google.samples.apps.iosched.server.gcm.db.models.Device) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 24 with ApiMethod

use of com.google.api.server.spi.config.ApiMethod in project iosched by google.

the class RegistrationEndpoint method registrationStatus.

@ApiMethod(path = "status", httpMethod = ApiMethod.HttpMethod.GET)
public RegistrationResult registrationStatus(ServletContext context, @Named("firebaseUserToken") String firebaseUserToken) throws IOException, ForbiddenException, ExecutionException, InterruptedException, InternalServerErrorException {
    String databaseUrl = context.getInitParameter("databaseUrl");
    LOG.info("databaseUrl: " + databaseUrl);
    String serviceAccountKey = context.getInitParameter("accountKey");
    LOG.info("accountKey: " + serviceAccountKey);
    InputStream serviceAccount = context.getResourceAsStream(serviceAccountKey);
    LOG.info("serviceAccount: " + serviceAccount);
    firebaseWrapper.initFirebase(databaseUrl, serviceAccount);
    firebaseWrapper.authenticateFirebaseUser(firebaseUserToken);
    if (!firebaseWrapper.isUserAuthenticated()) {
        throw new ForbiddenException("Not authenticated");
    }
    boolean isRegistered = isUserRegistered(context);
    final TaskCompletionSource<Boolean> isRegisteredTCS = new TaskCompletionSource<>();
    final Task<Boolean> isRegisteredTCSTask = isRegisteredTCS.getTask();
    // Update the user registration state in the Real-time Database.
    DatabaseReference dbRef = firebaseWrapper.getDatabaseReference();
    int rtdbRetries = 0;
    while (rtdbRetries < RTDB_RETRY_LIMIT) {
        dbRef.child("users").child(firebaseWrapper.getUserId()).setValue(isRegistered).addOnCompleteListener(new OnCompleteListener<Void>() {

            @Override
            public void onComplete(Task<Void> task) {
                if (task.isSuccessful()) {
                    isRegisteredTCS.setResult(true);
                } else {
                    isRegisteredTCS.setResult(false);
                }
            }
        });
        // If writing to RTDB was successful break out.
        if (Tasks.await(isRegisteredTCSTask)) {
            break;
        }
        LOG.info("Writing to RTDB has failed.");
        rtdbRetries++;
    }
    // indeed registered.
    if (rtdbRetries >= RTDB_RETRY_LIMIT) {
        throw new InternalServerErrorException("Unable to write registration status to RTDB.");
    } else {
        // Return the user registration state.
        return new RegistrationResult(isRegistered);
    }
}
Also used : ForbiddenException(com.google.api.server.spi.response.ForbiddenException) DatabaseReference(com.google.firebase.database.DatabaseReference) InputStream(java.io.InputStream) TaskCompletionSource(com.google.firebase.tasks.TaskCompletionSource) InternalServerErrorException(com.google.api.server.spi.response.InternalServerErrorException) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Example 25 with ApiMethod

use of com.google.api.server.spi.config.ApiMethod in project iosched by google.

the class ServingUrlEndpoint method getServingUrl.

/**
 * Get the serving URL for the image at the given filepath.
 *
 * @param filepath Filepath of image in GCS.
 * @return Serving URL that can be used to request different sizes of an image.
 */
@ApiMethod(name = "getServingUrl", path = "imageurl")
public ServingUrlResult getServingUrl(@Named("filepath") String filepath) {
    GcsFilename gcsFilename = new GcsFilename(Config.CLOUD_STORAGE_BUCKET, filepath);
    // Use ImageService to get serving URL for image.
    String url = ServingUrlManager.INSTANCE.createServingUrl(gcsFilename, Optional.<String>absent());
    // Use https for url.
    url = url.replace("http://", "https://");
    return new ServingUrlResult(url);
}
Also used : GcsFilename(com.google.appengine.tools.cloudstorage.GcsFilename) ApiMethod(com.google.api.server.spi.config.ApiMethod)

Aggregations

ApiMethod (com.google.api.server.spi.config.ApiMethod)54 CryptonomicaUser (net.cryptonomica.entities.CryptonomicaUser)19 Gson (com.google.gson.Gson)16 UserData (com.google.samples.apps.iosched.server.userdata.db.UserData)10 PGPPublicKeyData (net.cryptonomica.entities.PGPPublicKeyData)10 ArrayList (java.util.ArrayList)9 StringWrapperObject (net.cryptonomica.returns.StringWrapperObject)9 NotFoundException (com.google.api.server.spi.response.NotFoundException)8 BadRequestException (com.google.api.server.spi.response.BadRequestException)7 UnauthorizedException (com.google.api.server.spi.response.UnauthorizedException)7 Queue (com.google.appengine.api.taskqueue.Queue)7 HTTPResponse (com.google.appengine.api.urlfetch.HTTPResponse)6 Device (com.google.samples.apps.iosched.server.gcm.db.models.Device)6 MessageSender (com.google.samples.apps.iosched.server.gcm.device.MessageSender)5 AppSettings (net.cryptonomica.entities.AppSettings)5 PGPPublicKeyGeneralView (net.cryptonomica.returns.PGPPublicKeyGeneralView)5 UserProfileGeneralView (net.cryptonomica.returns.UserProfileGeneralView)5 BookmarkedSession (com.google.samples.apps.iosched.server.userdata.db.BookmarkedSession)4 BooleanWrapperObject (net.cryptonomica.returns.BooleanWrapperObject)4 PGPPublicKey (org.bouncycastle.openpgp.PGPPublicKey)4