use of com.google.api.client.util.store.FileDataStoreFactory in project community by GoogleCloudPlatform.
the class SimpleExample method main.
public static void main(String[] args) throws Throwable {
File directory = new File(System.getProperty("user.home"), ".store/ttam");
if (args.length != 2) {
throw new AssertionError("client_id and client_secret are required");
}
SimpleExample simpleExample = new SimpleExample(new FileDataStoreFactory(directory), args[0], args[1]);
Genotype genotype = simpleExample.retrieveGenotype();
System.out.println("Genotype @ i3003137, a SNP associated with Sickle Cell Anemia: " + genotype.i3003137);
}
use of com.google.api.client.util.store.FileDataStoreFactory in project Ardent by adamint.
the class Ardent method main.
public static void main(String[] args) throws Exception {
new DefaultAudioPlayerManager();
Logger root1 = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root1.setLevel(Level.OFF);
for (String s : args) {
if (s.contains("premium"))
premiumBot = true;
}
if (!testingBot) {
spotifyApi = Api.builder().clientId("471f277107704e3b89d489284b65c6c6").clientSecret(IOUtils.toString(new FileInputStream(new File("/root/Ardent/spotifysecret.key")))).redirectURI("https://ardentbot.tk").build();
SpotifyTokenRefresh spotifyTokenRefresh = new SpotifyTokenRefresh();
spotifyTokenRefresh.run();
globalExecutorService.scheduleAtFixedRate(spotifyTokenRefresh, 10, 10, TimeUnit.MINUTES);
} else
spotifyApi = Api.DEFAULT_API;
if (!testingBot) {
dbPassword = IOUtils.toString(new FileReader(new File("/root/Ardent/v2password.key")));
botsDiscordPwToken = IOUtils.toString(new FileReader(new File("/root/Ardent/botsdiscordpw.key")));
discordBotsOrgToken = IOUtils.toString(new FileReader(new File("/root/Ardent/discordbotsorg.key")));
} else {
try {
dbPassword = IOUtils.toString(new FileReader(new File("C:\\Users\\AMR\\Desktop\\Ardent\\v2password.key")));
discordBotsOrgToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjE2OTkwNDMyNDk4MDI0NDQ4MCIsImlhdCI6MTQ5MzMyNDM1OX0.LQ97UtslzaM5Qo__gkihOX5afaZA5z3TjMjSovMzDTI";
} catch (Exception ex) {
dbPassword = IOUtils.toString(new FileReader(new File("/root/Ardent/.key")));
}
}
Database.setup();
Cursor<HashMap> apiKeys = r.db("data").table("api_keys").run(connection);
apiKeys.forEach((outside) -> {
outside.forEach((uId, uValue) -> {
String id = (String) uId;
String value = (String) uValue;
if (id.equalsIgnoreCase("mashape"))
mashapeKey = value;
else if (id.equalsIgnoreCase("google"))
GOOGLE_API_KEY = value;
else if (id.equalsIgnoreCase("node0"))
node0Url = value;
else if (id.equalsIgnoreCase("node1"))
node1Url = value;
else if (id.equalsIgnoreCase("cleverbotuser"))
cleverbotUser = value;
else if (id.equalsIgnoreCase("cleverbotkey"))
cleverbotKey = value;
else if (id.equalsIgnoreCase("premiumbottoken"))
premiumBotToken = value;
else if (id.equalsIgnoreCase("testbottoken"))
testBotToken = value;
else if (id.equalsIgnoreCase("googlesecret"))
clientSecret = value;
else if (id.equalsIgnoreCase("twitch"))
twitch = value;
});
});
ShardManager.register(shardCount);
BotlistUpdater updater = new BotlistUpdater();
globalExecutorService.scheduleAtFixedRate(updater, 0, 1, TimeUnit.HOURS);
StuckVoiceConnection playerStuckDaemon = new StuckVoiceConnection();
globalExecutorService.scheduleAtFixedRate(playerStuckDaemon, 10, 10, TimeUnit.SECONDS);
UpdatePremiumMembers updatePremiumMembers = new UpdatePremiumMembers();
globalExecutorService.scheduleAtFixedRate(updatePremiumMembers, 0, 1, TimeUnit.MINUTES);
ProfileUpdater profileUpdater = new ProfileUpdater();
globalExecutorService.scheduleWithFixedDelay(profileUpdater, 1, 5, TimeUnit.MINUTES);
if (!premiumBot) {
SparkServer.setup();
/*Class currentClass = new Object() {
}.getClass().getEnclosingClass();
premiumProcess = Runtime.getRuntime().exec("java -jar " + currentClass.getProtectionDomain().getCodeSource().getLocation()
.getPath() + " -premium");*/
} else {
CheckIfPremiumGuild checkIfPremiumGuild = new CheckIfPremiumGuild();
globalExecutorService.scheduleAtFixedRate(checkIfPremiumGuild, 1, 5, TimeUnit.MINUTES);
}
GoogleSearch.setup(GOOGLE_API_KEY);
int status = Unirest.post("https://cleverbot.io/1.0/create").field("user", cleverbotUser).field("key", cleverbotKey).field("nick", "ardent").asString().getStatus();
if (status != 200)
new BotException("Unable to connect to cleverbot!");
WebsiteDaemon websiteDaemon = new WebsiteDaemon();
globalExecutorService.scheduleAtFixedRate(websiteDaemon, 5, 15, TimeUnit.SECONDS);
PermissionsDaemon permissionsDaemon = new PermissionsDaemon();
globalExecutorService.scheduleAtFixedRate(permissionsDaemon, 0, 60, TimeUnit.SECONDS);
GuildDaemon guildDaemon = new GuildDaemon();
globalExecutorService.scheduleAtFixedRate(guildDaemon, 0, 10, TimeUnit.SECONDS);
MuteDaemon muteDaemon = new MuteDaemon();
globalExecutorService.scheduleAtFixedRate(muteDaemon, 1, 5, TimeUnit.SECONDS);
RankableDaemon rankableDaemon = new RankableDaemon();
globalExecutorService.scheduleAtFixedRate(rankableDaemon, 0, 1, TimeUnit.MINUTES);
Music.checkMusicConnections();
globalExecutorService.scheduleAtFixedRate(() -> {
Shard[] shards = ShardManager.getShards();
for (int i = 0; i < shards.length; i++) {
Shard shard = shards[i];
if ((System.currentTimeMillis() - shard.getLAST_EVENT()) > 20000) {
shard.jda.getRegisteredListeners().forEach(shard.jda::removeEventListener);
int finalI = i;
globalExecutorService.schedule(() -> {
shard.jda.shutdown(false);
try {
shards[finalI] = new Shard(testingBot, finalI, shardCount);
} catch (Exception e) {
new BotException(e);
}
}, 3, TimeUnit.SECONDS);
}
}
}, 60, 15, TimeUnit.SECONDS);
if (!testingBot) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setOAuthConsumerKey("Fi9IjqqsGmOXqjR5uYK8YM2Pr").setOAuthConsumerSecret(IOUtils.toString(new FileReader(new File("/root/Ardent/twitterconsumersecret.key")))).setOAuthAccessToken("818984879018954752-aCzxyML6Xp0QcRpq5sjoe8wfp0sjVDt").setOAuthAccessTokenSecret(IOUtils.toString(new FileReader(new File("/root/Ardent/twitteroauthsecret.key"))));
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
}
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.OFF);
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.OFF);
try {
transport = GoogleNetHttpTransport.newTrustedTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
jsonFactory = JacksonFactory.getDefaultInstance();
sheetsApi = getSheetsService();
globalExecutorService.schedule(() -> {
try {
triviaSheet = sheetsApi.spreadsheets().values().get("1qm27kGVQ4BdYjvPSlF0zM64j7nkW4HXzALFNcan4fbs", "A2:C").execute();
} catch (IOException e) {
new BotException(e);
}
List<List<Object>> values = triviaSheet.getValues();
values.forEach(row -> {
String category = (String) row.get(0);
String q = (String) row.get(1);
String answerUnparsed = (String) row.get(2);
TriviaQuestion triviaQuestion = new TriviaQuestion();
triviaQuestion.setQuestion(q);
triviaQuestion.setCategory(category);
for (String answer : answerUnparsed.split("~")) {
triviaQuestion.withAnswer(answer);
}
Trivia.triviaQuestions.add(triviaQuestion);
});
}, 30, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
started = true;
}
use of com.google.api.client.util.store.FileDataStoreFactory in project textdb by TextDB.
the class GoogleResource method createCredential.
/**
* Creates an authorized Credential object for the service account
* Copied from google sheet API (https://developers.google.com/sheets/api/quickstart/java)
* rewrite this part when migrate to user's account
*/
private static Credential createCredential() throws IOException, GeneralSecurityException {
// Load client secrets
File initialFile = new File(CREDENTIALS_FILE_PATH);
InputStream targetStream = new FileInputStream(initialFile);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(targetStream));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(getHttpTransport(), JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH))).setAccessType("offline").build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
use of com.google.api.client.util.store.FileDataStoreFactory in project openhab1-addons by openhab.
the class GCalGoogleOAuth method getCredential.
/**
* <p>
* Perform OAuth2 authorization with Google server based on provided client_id and client_secret and
* stores credential in local persistent store.
* </p>
*
* @param newCredential If true try to obtain new credential (user interaction required)
* @return Authorization credential object.
*/
public static Credential getCredential(boolean newCredential) {
Credential credential = null;
try {
File tokenPath = null;
String userdata = System.getProperty("smarthome.userdata");
if (StringUtils.isEmpty(userdata)) {
tokenPath = new File("etc");
} else {
tokenPath = new File(userdata);
}
File tokenFile = new File(tokenPath, TOKEN_PATH);
FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(tokenFile);
DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore("gcal_oauth2_token");
credential = loadCredential("openhab", datastore);
if (credential == null && newCredential) {
if (StringUtils.isBlank(client_id) || StringUtils.isBlank(client_secret)) {
logger.warn("OAuth2 credentials are not provided");
return null;
}
GenericUrl genericUrl = new GenericUrl("https://accounts.google.com/o/oauth2/device/code");
Map<String, String> mapData = new HashMap<String, String>();
mapData.put("client_id", client_id);
mapData.put("scope", CalendarScopes.CALENDAR);
UrlEncodedContent content = new UrlEncodedContent(mapData);
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
HttpRequest postRequest = requestFactory.buildPostRequest(genericUrl, content);
Device device = postRequest.execute().parseAs(Device.class);
// no access token/secret specified so display the authorisation URL in the log
logger.info("################################################################################################");
logger.info("# Google-Integration: U S E R I N T E R A C T I O N R E Q U I R E D !!");
logger.info("# 1. Open URL '{}'", device.verification_url);
logger.info("# 2. Type provided code {} ", device.user_code);
logger.info("# 3. Grant openHAB access to your Google calendar");
logger.info("# 4. openHAB will automatically detect the permiossions and complete the authentication process");
logger.info("# NOTE: You will only have {} mins before openHAB gives up waiting for the access!!!", device.expires_in);
logger.info("################################################################################################");
if (logger.isDebugEnabled()) {
logger.debug("Got access code");
logger.debug("user code : {}", device.user_code);
logger.debug("device code : {}", device.device_code);
logger.debug("expires in: {}", device.expires_in);
logger.debug("interval : {}", device.interval);
logger.debug("verification_url : {}", device.verification_url);
}
mapData = new HashMap<String, String>();
mapData.put("client_id", client_id);
mapData.put("client_secret", client_secret);
mapData.put("code", device.device_code);
mapData.put("grant_type", "http://oauth.net/grant_type/device/1.0");
content = new UrlEncodedContent(mapData);
postRequest = requestFactory.buildPostRequest(new GenericUrl("https://accounts.google.com/o/oauth2/token"), content);
DeviceToken deviceToken;
do {
deviceToken = postRequest.execute().parseAs(DeviceToken.class);
if (deviceToken.access_token != null) {
if (logger.isDebugEnabled()) {
logger.debug("Got access token");
logger.debug("device access token: {}", deviceToken.access_token);
logger.debug("device token_type: {}", deviceToken.token_type);
logger.debug("device refresh_token: {}", deviceToken.refresh_token);
logger.debug("device expires_in: {}", deviceToken.expires_in);
}
break;
}
logger.debug("waiting for {} seconds", device.interval);
Thread.sleep(device.interval * 1000);
} while (true);
StoredCredential dataCredential = new StoredCredential();
dataCredential.setAccessToken(deviceToken.access_token);
dataCredential.setRefreshToken(deviceToken.refresh_token);
dataCredential.setExpirationTimeMilliseconds((long) deviceToken.expires_in * 1000);
datastore.set(TOKEN_STORE_USER_ID, dataCredential);
credential = loadCredential(TOKEN_STORE_USER_ID, datastore);
}
} catch (Exception e) {
logger.warn("getCredential got exception: {}", e.getMessage());
}
return credential;
}
use of com.google.api.client.util.store.FileDataStoreFactory in project repairnator by Spirals-Team.
the class ManageGoogleAccessToken method initializeCredentialFromGoogleSecret.
public void initializeCredentialFromGoogleSecret(String googleSecretPath) throws IOException {
this.dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
File secretFile = new File(googleSecretPath);
if (!secretFile.exists()) {
throw new IOException("File containing the token information to access Google API does not exist.");
}
// Load client secrets.
InputStream in = new FileInputStream(secretFile);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(this.jsonFactory, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(this.httpTransport, this.jsonFactory, clientSecrets, this.scopes).setDataStoreFactory(this.dataStoreFactory).setAccessType("offline").build();
this.credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
this.logger.info("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
}
Aggregations