me.emily.config.PlusConfig.java Source code

Java tutorial

Introduction

Here is the source code for me.emily.config.PlusConfig.java

Source

/*
 * Copyright (C) 2012 Emily Soldal
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.emily.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import me.emily.context.Context;
import me.emily.oauth2.OAuth2Native;
import me.emily.oauth2.SerializableCredentials;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.CredentialStore;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.urlshortener.Urlshortener;
import com.google.api.services.urlshortener.model.Url;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.inject.AbstractModule;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;

/**
 * @author Emily Soldal
 * @created 9 Feb 2012
 */

public class PlusConfig extends AbstractModule {
    private static final Logger log = LoggerFactory.getLogger(PlusConfig.class);

    @Override
    protected void configure() {

        TypeLiteral<Function<String, String>> literal = new TypeLiteral<Function<String, String>>() {
        };

        final Gson gson = new GsonBuilder().setPrettyPrinting().create();
        final GsonFactory jsonFactory = new GsonFactory();
        final NetHttpTransport transport = new NetHttpTransport();
        bind(Gson.class).toInstance(gson);
        bind(JsonFactory.class).toInstance(jsonFactory);
        bind(HttpTransport.class).toInstance(transport);

        final Urlshortener shortener = new Urlshortener.Builder(transport, jsonFactory, null).build();

        bind(literal).annotatedWith(Names.named("shortner")).toInstance(new Function<String, String>() {

            @Override
            public String apply(String input) {
                try {
                    return shortener.url().insert(new Url().setLongUrl(input)).execute().getId();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                    return input;
                }
            }

        });

        bind(GoogleClientSecrets.class).toProvider(new Provider<GoogleClientSecrets>() {

            @Override
            public GoogleClientSecrets get() {
                try {
                    File secrets = new File(Context.get(Context.contextDirectory), "client-secrets.json");
                    log.warn("Loading secrets from {}", secrets.getAbsolutePath());

                    return GoogleClientSecrets.load(jsonFactory, new FileInputStream(secrets));

                } catch (Exception e) {
                    Throwables.propagate(e);
                    return null;
                }
            }

        });

        bind(CredentialStore.class).toInstance(new CredentialStore() {

            Cache<String, SerializableCredentials> cache = CacheBuilder.newBuilder()
                    .expireAfterAccess(300, TimeUnit.SECONDS).build();

            File directory = new File(Context.get(Context.contextDirectory), "/creds");

            {
                directory.mkdir();
            }

            @Override
            public void store(String userId, Credential credential) throws IOException {
                SerializableCredentials permCreds = new SerializableCredentials(credential);
                cache.put(userId, permCreds);
                Files.write(gson.toJson(permCreds), credFile(userId), Charsets.UTF_8);
            }

            @Override
            public boolean load(String userId, Credential credential) throws IOException {
                SerializableCredentials cred = cache.getIfPresent(userId);
                if (cred != null) {
                    cred.push(credential);
                    return true;
                }

                cred = loadFromDisc(userId);
                if (cred != null) {
                    cred.push(credential);
                    cache.put(userId, cred);
                    return true;
                }
                return false;
            }

            private SerializableCredentials loadFromDisc(String userId)
                    throws JsonSyntaxException, JsonIOException, FileNotFoundException {

                File credfile = credFile(userId);
                if (credfile.exists()) {
                    return gson.fromJson(new FileReader(credfile), SerializableCredentials.class);
                }

                return null;
            }

            @Override
            public void delete(String userId, Credential credential) throws IOException {
                cache.invalidate(userId);

                File credFile = credFile(userId);
                if (credFile.exists()) {
                    credFile.delete();
                }

            }

            private File credFile(String userId) {
                return new File(directory, userId.replaceAll("(\\|/)", ".") + ".cred.json");
            }

        });

        bind(OAuth2Native.class).asEagerSingleton();

    }
}