Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleCredential fromStream

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleCredential fromStream

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.auth.oauth2 GoogleCredential fromStream.

Prototype

@Beta
public static GoogleCredential fromStream(InputStream credentialStream) throws IOException 

Source Link

Document

Beta
Return a credential defined by a Json file.

Usage

From source file:BO.UserHandler.java

private static String getAccessToken() throws IOException {
    FileInputStream serviceAccount = new FileInputStream(
            "D:\\Firebase\\mobilapp-67b55-firebase-adminsdk-ijhds-43eb2c5271.json");
    String[] scope = { "https://www.googleapis.com/auth/firebase.messaging" };
    GoogleCredential googleCredential = GoogleCredential.fromStream(serviceAccount)
            .createScoped(Arrays.asList("https://www.googleapis.com/auth/firebase.messaging"));
    googleCredential.refreshToken();//www  .j  av a 2s .  c o m
    return googleCredential.getAccessToken();
}

From source file:com.arm.connector.bridge.coordinator.processors.google.GoogleCloudMQTTProcessor.java

License:Open Source License

private boolean googleCloudLogin(String project_id, String auth_json) {
    boolean success = false;
    String edited_auth_json = null;

    try {//w w  w  . j  a v  a 2 s  . c  o  m
        // announce login
        this.errorLogger().info("googleCloudLogin(): logging into project_id: " + project_id + "...");

        // remove \\00A0 as it can be copied during config setting of the auth json by the configurator...
        // hex(A0) = dec(160)... just replace with an ordinary space... that will make Google's JSON parser happy...
        edited_auth_json = com.arm.connector.bridge.core.Utils.replaceAllCharOccurances(auth_json, (char) 160,
                ' ');

        // DEBUG
        //this.errorLogger().info("googleCloudLogin():AUTH:" + edited_auth_json);

        // Build service account credential.
        this.m_credential = GoogleCredential.fromStream(new ByteArrayInputStream(edited_auth_json.getBytes()));

        // add scopes
        if (this.m_credential.createScopedRequired()) {
            this.m_credential = this.m_credential.createScoped(PubsubScopes.all());
        }

        // success!
        success = true;

        // DEBUG
        this.errorLogger().warning("googleCloudLogin(): LOGIN SUCCESSFUL. project_id: " + project_id);
    } catch (com.google.api.client.googleapis.json.GoogleJsonResponseException ex) {
        // caught exception during login
        this.errorLogger()
                .warning("googleCloudLogin(GoogleJsonResponseException): Unable to log into Google Cloud: "
                        + ex.getMessage());
    } catch (IOException ex) {
        // caught exception during login
        this.errorLogger().warning("googleCloudLogin(): Unable to log into Google Cloud: " + ex.getMessage());
        success = false;
    }

    // return our status
    return success;
}

From source file:com.blackberry.bdp.klogger.LogReader.java

License:Apache License

@Override
public void run() {
    UTF8Validator utf8Validator = null;

    GoogleCredential credential = null;//  w ww .  j  av  a2s. c  o m

    // Use credentials from file if available
    try {
        credential = GoogleCredential.fromStream(new FileInputStream("credentials.json"))
                .createScoped(PubsubScopes.all());
    } catch (IOException e) {
        try {
            credential = GoogleCredential.getApplicationDefault().createScoped(PubsubScopes.all());
        } catch (Exception e1) {

        }

    }

    final Pubsub client = new Pubsub.Builder(Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
            credential).setApplicationName("vstoyak-kloger-test").build();

    if (validateUTF8) {
        utf8Validator = new UTF8Validator();
    }

    // Calculate send buffer size. If we're validating UTF-8, then theoretically, each byte could be
    // replaced by the three byte replacement character. So the send buffer needs to be triple
    // the max line length.  If we're encoding the timestamp, then that adds 10 bytes.
    byte[] sendBytes;
    {
        int sendBufferSize = maxLine;

        if (validateUTF8) {
            sendBufferSize *= 3;
        }
        if (encodeTimestamp) {
            sendBufferSize += 10;
        }

        sendBytes = new byte[sendBufferSize];
    }

    ByteBuffer sendBuffer = ByteBuffer.wrap(sendBytes);

    try {
        prepareSource();

        while (!finished) {
            bytesRead = readSource();

            if (bytesRead > 0) {
                LOG.trace("Read {} bytes", bytesRead);
            } else {
                if (bytesRead == 0) {
                    // File's return 0 when they have reached the end of the FileChannel
                    continue;
                } else {
                    if (bytesRead == -1) {
                        LOG.warn("Received -1 while reading from source, finishing up...");
                        finished = true;
                        continue;
                    }
                }
            }

            mBytesReceived.mark(bytesRead);
            mBytesReceivedTotal.mark(bytesRead);

            limit = start + bytesRead;
            start = 0;

            while (true) {
                newline = -1;

                for (int i = start; i < limit; i++) {
                    if (bytes[i] == '\n') {
                        totalLinesRead++;
                        newline = i;
                        break;
                    }
                }

                LOG.trace("Newline at {}", newline);

                if (newline >= 0) {
                    mLinesReceived.mark();
                    mLinesReceivedTotal.mark();

                    LOG.trace("Sending (pos {}, len {}):{}", start, newline - start,
                            new String(bytes, start, newline - start, "UTF-8"));

                    sendBuffer.clear();

                    if (encodeTimestamp) {
                        sendBuffer.put(new byte[] { (byte) 0xFE, 0x00 });

                        sendBuffer.putLong(System.currentTimeMillis());
                    }

                    if (validateUTF8) {
                        utf8Validator.validate(bytes, start, newline - start);
                        sendBuffer.put(utf8Validator.getResultBytes(), 0,
                                utf8Validator.getResultBuffer().limit());
                    } else {
                        sendBuffer.put(bytes, start, newline - start);
                    }

                    String message = "test Message 1";
                    if (!"".equals(message)) {
                        String fullTopicName = String.format("projects/%s/topics/%s", "bbm-staging",
                                "vstoyak-kloger-test");
                        PubsubMessage pubsubMessage = new PubsubMessage();
                        //pubsubMessage.encodeData(message.getBytes("UTF-8"));
                        pubsubMessage.encodeData(sendBytes);
                        PublishRequest publishRequest = new PublishRequest();
                        publishRequest.setMessages(ImmutableList.of(pubsubMessage));

                        try {
                            client.projects().topics().publish(fullTopicName, publishRequest).execute();
                        } catch (Exception e) {
                            LOG.info("PubSub exception", e);
                        }
                    }
                    //producer.send(sendBytes, 0, sendBuffer.position());

                    start = newline + 1;
                    continue;

                } else {
                    LOG.trace("No newline.  start={}, limit={}", start, limit);

                    // if the buffer is full, send it all. Otherwise, do nothing.
                    if (start == 0 && limit == maxLine) {
                        mLinesReceived.mark();
                        mLinesReceivedTotal.mark();

                        LOG.trace("Sending log with no new-line:{}", new String(bytes, 0, maxLine, "UTF-8"));

                        sendBuffer.clear();

                        if (encodeTimestamp) {
                            sendBuffer.put(new byte[] { (byte) 0xFE, 0x00 });
                            sendBuffer.putLong(System.currentTimeMillis());
                        }

                        if (validateUTF8) {
                            utf8Validator.validate(bytes, 0, maxLine);
                            sendBuffer.put(utf8Validator.getResultBytes(), 0,
                                    utf8Validator.getResultBuffer().limit());
                        } else {
                            sendBuffer.put(bytes, 0, maxLine);
                        }

                        String message = "test Message 2";
                        if (!"".equals(message)) {
                            String fullTopicName = String.format("projects/%s/topics/%s", "bbm-staging",
                                    "vstoyak-kloger-test");
                            PubsubMessage pubsubMessage = new PubsubMessage();
                            //pubsubMessage.encodeData(message.getBytes("UTF-8"));
                            pubsubMessage.encodeData(sendBytes);
                            PublishRequest publishRequest = new PublishRequest();
                            publishRequest.setMessages(ImmutableList.of(pubsubMessage));

                            try {
                                client.projects().topics().publish(fullTopicName, publishRequest).execute();
                            } catch (Exception e) {
                                LOG.info("PubSub exception", e);
                            }
                        }

                        //producer.send(sendBytes, 0, sendBuffer.position());

                        start = 0;
                        break;

                    } // if there is still data, then shift it to the start
                    else {
                        if (start > 0 && start < limit) {
                            int toMove = limit - start;
                            int moveSize;
                            int done = 0;

                            while (done < toMove) {
                                moveSize = Math.min(start - done, limit - start);

                                System.arraycopy(bytes, start, bytes, done, moveSize);

                                done += moveSize;
                                start += moveSize;
                            }

                            start = toMove;
                            break;
                        } else {
                            if (start >= limit) {
                                LOG.trace("All the data has been read");
                                start = 0;
                                break;
                            } else {
                                // start == 0, so move it to the limit for the next pass.
                                start = limit;
                                break;
                            }
                        }
                    }
                }
            }

        }
    } catch (Throwable t) {
        LOG.error("An error has occured: {}", t);
    } finally {
        finished();
    }

    LOG.info("Reading source for topic {} is finished", conf.getTopicName());
}

From source file:com.dtolabs.rundeck.plugin.resources.gcp.GCPResourceModelSource.java

License:Apache License

public GCPResourceModelSource(final Properties configuration) {
    logger.error("GCPResourceModelSource Constructor");
    //this.clientId = configuration.getProperty(GCPResourceModelSourceFactory.CLIENT_ID);
    //this.clientSecret = configuration.getProperty(GCPResourceModelSourceFactory.CLIENT_SECRET);
    //this.endpoint = configuration.getProperty(EC2ResourceModelSourceFactory.ENDPOINT);
    //this.httpProxyHost = configuration.getProperty(GCPResourceModelSourceFactory.HTTP_PROXY_HOST);
    this.projectId = configuration.getProperty(GCPResourceModelSourceFactory.PROJECT_ID);
    int proxyPort = 80;

    //final String proxyPortStr = configuration.getProperty(GCPResourceModelSourceFactory.HTTP_PROXY_PORT);
    /*if (null != proxyPortStr && !"".equals(proxyPortStr)) {
    try {/*from  ww  w  .j a v a  2s .com*/
        proxyPort = Integer.parseInt(proxyPortStr);
    } catch (NumberFormatException e) {
        logger.warn(GCPResourceModelSourceFactory.HTTP_PROXY_PORT + " value is not valid: " + proxyPortStr);
    }
    }
    this.httpProxyPort = proxyPort;
    this.httpProxyUser = configuration.getProperty(GCPResourceModelSourceFactory.HTTP_PROXY_USER);
    this.httpProxyPass = configuration.getProperty(GCPResourceModelSourceFactory.HTTP_PROXY_PASS);
    */
    this.filterParams = configuration.getProperty(GCPResourceModelSourceFactory.FILTER_PARAMS);
    this.mappingParams = configuration.getProperty(GCPResourceModelSourceFactory.MAPPING_PARAMS);
    final String mappingFilePath = configuration.getProperty(GCPResourceModelSourceFactory.MAPPING_FILE);
    if (null != mappingFilePath) {
        mappingFile = new File(mappingFilePath);
    }
    int refreshSecs = 30;
    final String refreshStr = configuration.getProperty(GCPResourceModelSourceFactory.REFRESH_INTERVAL);
    if (null != refreshStr && !"".equals(refreshStr)) {
        try {
            refreshSecs = Integer.parseInt(refreshStr);
        } catch (NumberFormatException e) {
            logger.warn(GCPResourceModelSourceFactory.REFRESH_INTERVAL + " value is not valid: " + refreshStr);
        }
    }
    refreshInterval = refreshSecs * 1000;
    if (configuration.containsKey(GCPResourceModelSourceFactory.USE_DEFAULT_MAPPING)) {
        useDefaultMapping = Boolean
                .parseBoolean(configuration.getProperty(GCPResourceModelSourceFactory.USE_DEFAULT_MAPPING));
    }
    if (configuration.containsKey(GCPResourceModelSourceFactory.RUNNING_ONLY)) {
        runningOnly = Boolean
                .parseBoolean(configuration.getProperty(GCPResourceModelSourceFactory.RUNNING_ONLY));
    }
    //if (null != clientId && null != clientSecret) {
    try {
        credential = GoogleCredential
                .fromStream(new FileInputStream("/etc/rundeck/rundeck-gcp-nodes-plugin.json"))
                .createScoped(Collections.singleton(ComputeScopes.COMPUTE_READONLY));
        logger.error("Google Crendential created successfully");
    } catch (FileNotFoundException e) {
        logger.error("Google Crendential failed creation");
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
    //}

    /*if (null != httpProxyHost && !"".equals(httpProxyHost)) {
    clientConfiguration.setProxyHost(httpProxyHost);
    clientConfiguration.setProxyPort(httpProxyPort);
    clientConfiguration.setProxyUsername(httpProxyUser);
    clientConfiguration.setProxyPassword(httpProxyPass);
    }*/

    initialize();
}

From source file:com.example.androidthings.weatherstation.PubsubPublisher.java

License:Apache License

PubsubPublisher(Context context, String appname, String project, String topic, int credentialResourceId)
        throws IOException {
    mContext = context;/*from ww w  .  ja  v  a  2  s  . c  o m*/
    mAppname = appname;
    mTopic = "projects/" + project + "/topics/" + topic;

    mHandlerThread = new HandlerThread("pubsubPublisherThread");
    mHandlerThread.start();
    mHandler = new Handler(mHandlerThread.getLooper());

    InputStream jsonCredentials = mContext.getResources().openRawResource(credentialResourceId);
    final GoogleCredential credentials;
    try {
        credentials = GoogleCredential.fromStream(jsonCredentials)
                .createScoped(Collections.singleton(PubsubScopes.PUBSUB));
    } finally {
        try {
            jsonCredentials.close();
        } catch (IOException e) {
            Log.e(TAG, "Error closing input stream", e);
        }
    }
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            mHttpTransport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mPubsub = new Pubsub.Builder(mHttpTransport, jsonFactory, credentials).setApplicationName(mAppname)
                    .build();
        }
    });
}

From source file:com.example.himanshu.myapplication.LabelApp.java

License:Open Source License

public static Vision getVisionService(Context context) throws IOException, GeneralSecurityException {

    //DefaultCredentialProvider dc;
    Log.d("LabelApp", "The value of GOOGLE_APPLICATION_CREDENTIALS:"
            + System.getProperty("GOOGLE_APPLICATION_CREDENTIALS"));
    //GoogleCredential credential = GoogleCredential.getApplicationDefault();
    GoogleCredential credential;/*from  w w w  . j  a  va2 s.  c o  m*/

    Log.d("LabelApp", "Context inside LabelApp is null or not:" + (context == null));
    Log.d("LabelApp", "context.getResources().openRawResource(R.raw.credentials) is null or not:"
            + (context.getResources().openRawResource(R.raw.credentials) == null));

    credential = GoogleCredential.fromStream(context.getResources().openRawResource(R.raw.credentials))
            .createScoped(VisionScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    /*  return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
        .setApplicationName(APPLICATION_NAME)
        .build();
        */
    return new Vision.Builder(AndroidHttp.newCompatibleTransport(), jsonFactory, credential)
            .setApplicationName(APPLICATION_NAME).build();

}

From source file:com.example.taphan.core1.languageProcessing.AccessTokenLoader.java

License:Open Source License

@Override
public String loadInBackground() {

    final SharedPreferences prefs = getContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);
    String currentToken = prefs.getString(PREF_ACCESS_TOKEN, null);

    // Check if the current token is still valid for a while
    if (currentToken != null) {
        final GoogleCredential credential = new GoogleCredential().setAccessToken(currentToken)
                .createScoped(CloudNaturalLanguageAPIScopes.all());
        final Long seconds = credential.getExpiresInSeconds();
        if (seconds != null && seconds > 3600) {
            return currentToken;
        }/*from ww  w .  ja va 2 s.c om*/
    }

    final InputStream stream = getContext().getResources().openRawResource(R.raw.credential);
    try {
        final GoogleCredential credential = GoogleCredential.fromStream(stream)
                .createScoped(CloudNaturalLanguageAPIScopes.all());
        credential.refreshToken();
        final String accessToken = credential.getAccessToken();
        prefs.edit().putString(PREF_ACCESS_TOKEN, accessToken).apply();
        return accessToken;
    } catch (IOException e) {
        Log.e(TAG, "Failed to obtain access token.", e);
    }
    return null;
}

From source file:com.google.cloud.android.language.AccessTokenLoader.java

License:Open Source License

@Override
public String loadInBackground() {

    final SharedPreferences prefs = getContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE);
    String currentToken = prefs.getString(PREF_ACCESS_TOKEN, null);

    // Check if the current token is still valid for a while
    if (currentToken != null) {
        final GoogleCredential credential = new GoogleCredential().setAccessToken(currentToken)
                .createScoped(CloudNaturalLanguageScopes.all());
        final Long seconds = credential.getExpiresInSeconds();
        if (seconds != null && seconds > 3600) {
            return currentToken;
        }//w w  w.  ja  va2  s .  co m
    }

    // ***** WARNING *****
    // In this sample, we load the credential from a JSON file stored in a raw resource folder
    // of this client app. You should never do this in your app. Instead, store the file in your
    // server and obtain an access token from there.
    // *******************
    final InputStream stream = getContext().getResources().openRawResource(R.raw.credential);
    try {
        final GoogleCredential credential = GoogleCredential.fromStream(stream)
                .createScoped(CloudNaturalLanguageScopes.all());
        credential.refreshToken();
        final String accessToken = credential.getAccessToken();
        prefs.edit().putString(PREF_ACCESS_TOKEN, accessToken).apply();
        return accessToken;
    } catch (IOException e) {
        Log.e(TAG, "Failed to obtain access token.", e);
    }
    return null;
}

From source file:com.google.cloud.crypto.tink.subtle.ServiceAccountGcpCredentialFactory.java

License:Apache License

/**
 * @return {@code GoogleCredential} from {@code serviceAccount}.
 *///ww  w  .  j a va 2s .  co m
public static GoogleCredential createServiceAccountGoogleCredential(File serviceAccount) throws IOException {
    return GoogleCredential.fromStream(new ByteArrayInputStream(Files.readAllBytes(serviceAccount.toPath())));
}

From source file:com.google.cloud.crypto.tink.tinkey.TinkeyUtil.java

License:Apache License

/**
 * @return a {@code GoogleCredential}, using the service account in {@code credentialFile}.
 * If {@code credentialFile} is null, returns an
 * <a href="https://g.co/dv/identity/protocols/application-default-credentials">application
 * default credential</a>.//from   w  w w . j  av  a  2  s .c o m
 */
public static GoogleCredential readGoogleCredential(File credentialFile) throws IOException {
    GoogleCredential cred;
    if (credentialFile != null) {
        byte[] credBytes = Files.readAllBytes(credentialFile.toPath());
        cred = GoogleCredential.fromStream(new ByteArrayInputStream(credBytes));
    } else {
        cred = GoogleCredential.getApplicationDefault();
    }
    // Depending on the environment that provides the default credentials (e.g. Compute Engine, App
    // Engine), the credentials may require us to specify the scopes we need explicitly.
    // Check for this case, and inject the scope if required.
    if (cred.createScopedRequired()) {
        cred = cred.createScoped(CloudKMSScopes.all());
    }
    return cred;
}