index
int64 0
0
| repo_id
stringlengths 9
205
| file_path
stringlengths 31
246
| content
stringlengths 1
12.2M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 |
Create_ds/aries-journaled-events/org.apache.aries.events.api/src/main/java/org/apache/aries/events
|
Create_ds/aries-journaled-events/org.apache.aries.events.api/src/main/java/org/apache/aries/events/api/Messaging.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF licenses this file
* to you 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 org.apache.aries.events.api;
/**
* Journaled messaging API
*/
public interface Messaging {
/**
* Send a message to a topic. When this method returns the message
* is safely persisted.
*
* Messages can be consumed by subscribing to the topic via the #subscribe method.
*
* Two messages sent sequentially to the same topic by the same
* thread, are guaranteed to be consumed in the same order by all subscribers.
*/
void send(String topic, Message message);
/**
* Subscribe to a topic.
* The returned subscription must be closed by the caller to unsubscribe.
*
* @param request to subscribe
*/
Subscription subscribe(SubscribeRequestBuilder request);
/**
* Deserialize the position from the string
*
* @param position
* @return
*/
Position positionFromString(String position);
}
| 8,900 |
0 |
Create_ds/aries-journaled-events/org.apache.aries.events.api/src/main/java/org/apache/aries/events
|
Create_ds/aries-journaled-events/org.apache.aries.events.api/src/main/java/org/apache/aries/events/api/Subscription.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF licenses this file
* to you 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 org.apache.aries.events.api;
import java.io.Closeable;
public interface Subscription extends Closeable {
@Override
void close();
}
| 8,901 |
0 |
Create_ds/aries-journaled-events/org.apache.aries.events.api/src/main/java/org/apache/aries/events
|
Create_ds/aries-journaled-events/org.apache.aries.events.api/src/main/java/org/apache/aries/events/api/Seek.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF licenses this file
* to you 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 org.apache.aries.events.api;
/**
* Starting position when no Position is available
*/
public enum Seek {
/**
* Seek to the first position (happened the earliest) on a topic.
*/
earliest,
/**
* Seek to the last position (happened the latest) on a topic.
*/
latest;
}
| 8,902 |
0 |
Create_ds/aries-journaled-events/org.apache.aries.events.api/src/main/java/org/apache/aries/events
|
Create_ds/aries-journaled-events/org.apache.aries.events.api/src/main/java/org/apache/aries/events/api/package-info.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF licenses this file
* to you 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.
*/
@org.osgi.annotation.bundle.Export
@org.osgi.annotation.versioning.Version("0.1.0")
package org.apache.aries.events.api;
| 8,903 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/MainActivity.java
|
package com.squareup.photobooth;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import com.squareup.photobooth.start.KioskStartActivity;
import com.squareup.photobooth.printer.PrinterSetupActivity;
import com.squareup.photobooth.settings.SettingsActivity;
import com.squareup.photobooth.settings.SettingsStore;
import com.squareup.photobooth.util.Activities;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
public class MainActivity extends AppCompatActivity {
private SettingsStore settingsStore;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settingsStore = App.from(this).settingsStore();
setContentView(R.layout.setup);
findViewById(R.id.photobooth_button).setOnClickListener(v -> startPhotobooth());
findViewById(R.id.printers_button).setOnClickListener(
v -> startActivity(new Intent(MainActivity.this, PrinterSetupActivity.class)));
findViewById(R.id.settings_button).setOnClickListener(
v -> startActivity(new Intent(MainActivity.this, SettingsActivity.class)));
}
@Override protected void onResume() {
super.onResume();
if (settingsStore.shouldLockTask()) {
if (SDK_INT >= LOLLIPOP) {
if (!Activities.isAppInLockTaskMode(this)) {
// This shows a dialog to confirm that we want to go in lock task mode.
startLockTask();
}
} else {
snack("Kiosk not supported on API " + SDK_INT);
}
}
}
private void startPhotobooth() {
startActivity(new Intent(this, KioskStartActivity.class));
}
private void snack(String message) {
Snackbar.make(findViewById(R.id.photobooth_button), message, Snackbar.LENGTH_SHORT).show();
}
}
| 8,904 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/App.java
|
package com.squareup.photobooth;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.support.multidex.MultiDex;
import android.util.Log;
import com.birbit.android.jobqueue.JobManager;
import com.birbit.android.jobqueue.config.Configuration;
import com.birbit.android.jobqueue.scheduling.FrameworkJobSchedulerService;
import com.birbit.android.jobqueue.scheduling.GcmJobSchedulerService;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.squareup.photobooth.job.GcmJobService;
import com.squareup.photobooth.job.JobManagerInjector;
import com.squareup.photobooth.job.JobService;
import com.squareup.photobooth.job.TimberJobLogger;
import com.squareup.photobooth.oauth.GoogleOAuthStore;
import com.squareup.photobooth.printer.CloudPrinter;
import com.squareup.photobooth.settings.SettingsStore;
import com.squareup.photobooth.snap.BitmapBytesHolder;
import com.squareup.photobooth.snap.PictureRenderer;
import com.squareup.sdk.reader.ReaderSdk;
import com.twitter.sdk.android.core.DefaultLogger;
import com.twitter.sdk.android.core.Twitter;
import com.twitter.sdk.android.core.TwitterConfig;
import timber.log.Timber;
public class App extends Application {
// Created by [email protected] on production.
private static final String CLIENT_ID = "sq0idp-8LyKI0yIn42eM_dg8a4ciw";
private GoogleOAuthStore oAuthStore;
private CloudPrinter cloudPrinter;
private PictureRenderer pictureRenderer;
private BitmapBytesHolder bitmapBytesHolder;
private JobManager jobManager;
private SettingsStore settingsStore;
public static App from(Context context) {
return (App) context.getApplicationContext();
}
@Override public void onCreate() {
super.onCreate();
if (BuildConfig.DEBUG) {
Timber.plant(new Timber.DebugTree());
}
TwitterConfig config =
new TwitterConfig.Builder(this).logger(new DefaultLogger(Log.DEBUG)).debug(true).build();
Twitter.initialize(config);
settingsStore = new SettingsStore(this);
oAuthStore = new GoogleOAuthStore(this);
cloudPrinter = CloudPrinter.create(oAuthStore, settingsStore, this);
pictureRenderer = new PictureRenderer(this);
bitmapBytesHolder = new BitmapBytesHolder();
Configuration.Builder builder = new Configuration.Builder(this) //
.minConsumerCount(1) //
.maxConsumerCount(3) //
.loadFactor(3) //
.customLogger(new TimberJobLogger()).injector(new JobManagerInjector(this)) //
.consumerKeepAlive(120);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.scheduler(FrameworkJobSchedulerService.createSchedulerFor(this, JobService.class),
true);
} else {
int enableGcm = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if (enableGcm == ConnectionResult.SUCCESS) {
builder.scheduler(GcmJobSchedulerService.createSchedulerFor(this, GcmJobService.class),
true);
}
}
jobManager = new JobManager(builder.build());
ReaderSdk.initialize(this);
}
public GoogleOAuthStore oAuthStore() {
return oAuthStore;
}
public CloudPrinter cloudPrinter() {
return cloudPrinter;
}
public PictureRenderer pictureRenderer() {
return pictureRenderer;
}
public BitmapBytesHolder bitmapHolder() {
return bitmapBytesHolder;
}
public JobManager jobManager() {
return jobManager;
}
public SettingsStore settingsStore() {
return settingsStore;
}
@Override protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
// Required if minSdkVersion < 21
MultiDex.install(this);
}
}
| 8,905 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/settings/ManualCodeEntryActivity.java
|
package com.squareup.photobooth.settings;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import com.squareup.photobooth.R;
import com.squareup.photobooth.settings.AuthorizingActivity;
import com.squareup.photobooth.settings.StartAuthorizeActivity;
import com.squareup.photobooth.util.TextWatcherAdapter;
public class ManualCodeEntryActivity extends AppCompatActivity {
private EditText authorizationCodeEditText;
private View authorizeButton;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manual_code_entry_activity);
authorizationCodeEditText = findViewById(R.id.authorization_code_edit_text);
authorizationCodeEditText.setOnEditorActionListener((view, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
if (!authorizationCodeEmpty()) {
startAuthorizing();
return true;
}
}
return false;
});
authorizeButton = findViewById(R.id.authorize_button);
authorizeButton.setOnClickListener(v -> startAuthorizing());
authorizationCodeEditText.addTextChangedListener(new TextWatcherAdapter() {
@Override public void onTextChanged(CharSequence text, int start, int before, int count) {
updateSubmitButtonState();
}
});
updateSubmitButtonState();
findViewById(R.id.cancel_button).setOnClickListener(view -> finish());
}
@Override public void onBackPressed() {
startActivity(new Intent(this, StartAuthorizeActivity.class));
finish();
}
private void updateSubmitButtonState() {
authorizeButton.setEnabled(!authorizationCodeEmpty());
}
private boolean authorizationCodeEmpty() {
return authorizationCodeEditText.getText().toString().trim().isEmpty();
}
private void startAuthorizing() {
String authorizationCode = authorizationCodeEditText.getText().toString().trim();
AuthorizingActivity.start(this, authorizationCode);
finish();
}
}
| 8,906 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/settings/StartAuthorizeActivity.java
|
package com.squareup.photobooth.settings;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.squareup.photobooth.R;
public class StartAuthorizeActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_authorize_activity);
View qrCodeButton = findViewById(R.id.qr_code_button);
if (deviceIsEmulator()) {
qrCodeButton.setEnabled(false);
qrCodeButton.setOnClickListener(this::qrCodeScanningNotSupported);
} else {
qrCodeButton.setOnClickListener(view -> startQrCodeScanning());
}
View manualCodeEntryButton = findViewById(R.id.manual_code_entry_button);
manualCodeEntryButton.setOnClickListener(view -> startManualCodeEntry());
}
public static boolean deviceIsEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")
|| Build.MANUFACTURER.contains("Genymotion")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| "google_sdk".equals(Build.PRODUCT);
}
private void qrCodeScanningNotSupported(View view) {
Snackbar.make(view, R.string.not_supported_emulator, Snackbar.LENGTH_SHORT)
.show();
}
private void startQrCodeScanning() {
startActivity(new Intent(this, ScanQRCodeActivity.class));
finish();
}
private void startManualCodeEntry() {
startActivity(new Intent(this, ManualCodeEntryActivity.class));
finish();
}
}
| 8,907 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/settings/AuthorizingActivity.java
|
package com.squareup.photobooth.settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.squareup.photobooth.BuildConfig;
import com.squareup.photobooth.R;
import com.squareup.sdk.reader.ReaderSdk;
import com.squareup.sdk.reader.authorization.AuthorizationManager;
import com.squareup.sdk.reader.authorization.AuthorizationState;
import com.squareup.sdk.reader.authorization.AuthorizeErrorCode;
import com.squareup.sdk.reader.authorization.Location;
import com.squareup.sdk.reader.core.CallbackReference;
import com.squareup.sdk.reader.core.Result;
import com.squareup.sdk.reader.core.ResultError;
public class AuthorizingActivity extends AppCompatActivity {
private static final String AUTHORIZE_CODE_EXTRA = "authorizeCodeExtra";
private static final String TAG = AuthorizingActivity.class.getSimpleName();
public static void start(Activity originActivity, String authorizationCode) {
Intent intent = new Intent(originActivity, AuthorizingActivity.class);
intent.putExtra(AUTHORIZE_CODE_EXTRA, authorizationCode);
originActivity.startActivity(intent);
}
private CallbackReference authorizeCallbackRef;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.authorizing_activity);
AuthorizationManager authorizationManager = ReaderSdk.authorizationManager();
authorizeCallbackRef = authorizationManager.addAuthorizeCallback(this::onAuthorizeResult);
if (savedInstanceState == null) {
authorize();
} else {
AuthorizationState state = authorizationManager.getAuthorizationState();
if (!state.isAuthorizationInProgress()) {
if (state.isAuthorized()) {
finish();
} else {
goToStartAuthorizeActivity();
}
}
}
}
private void authorize() {
String authorizationCode = getIntent().getStringExtra(AUTHORIZE_CODE_EXTRA);
ReaderSdk.authorizationManager().authorize(authorizationCode);
}
private void onAuthorizeResult(Result<Location, ResultError<AuthorizeErrorCode>> result) {
if (result.isSuccess()) {
finish();
} else {
ResultError<AuthorizeErrorCode> error = result.getError();
switch (error.getCode()) {
case NO_NETWORK:
showRetryDialog(error);
break;
case USAGE_ERROR:
showUsageErrorDialog(error);
break;
}
}
}
private void showRetryDialog(ResultError<AuthorizeErrorCode> error) {
new AlertDialog.Builder(this)
.setTitle(getString(R.string.network_error_dialog_title))
.setMessage(error.getMessage())
.setPositiveButton(R.string.retry_button, (dialog, which) -> authorize())
.setOnCancelListener(dialog -> goToStartAuthorizeActivity())
.show();
}
private void showUsageErrorDialog(ResultError<AuthorizeErrorCode> error) {
String dialogMessage = error.getMessage();
if (BuildConfig.DEBUG) {
dialogMessage += "\n\nDebug Message: " + error.getDebugMessage();
Log.d(TAG,
error.getCode() + ": " + error.getDebugCode() + ", " + error.getDebugMessage());
}
new AlertDialog.Builder(this)
.setTitle(getString(R.string.error_dialog_title))
.setMessage(dialogMessage)
.setPositiveButton(R.string.ok,
(dialog, which) -> goToStartAuthorizeActivity())
.setOnCancelListener(dialog -> goToStartAuthorizeActivity())
.show();
}
private void goToStartAuthorizeActivity() {
Intent intent = new Intent(this, StartAuthorizeActivity.class);
startActivity(intent);
finish();
}
@Override public void onBackPressed() {
// Blocking until it's done.
}
@Override protected void onDestroy() {
super.onDestroy();
authorizeCallbackRef.clear();
}
}
| 8,908 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/settings/ScanQRCodeActivity.java
|
package com.squareup.photobooth.settings;
import android.content.Intent;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewStub;
import com.dlazaro66.qrcodereaderview.QRCodeReaderView;
import com.squareup.photobooth.R;
import com.squareup.photobooth.settings.AuthorizingActivity;
import com.squareup.photobooth.settings.StartAuthorizeActivity;
import static android.Manifest.permission.CAMERA;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
/**
* Uses https://github.com/dlazaro66/QRCodeReaderView for QR Code scanning.
*/
public class ScanQRCodeActivity extends AppCompatActivity
implements ActivityCompat.OnRequestPermissionsResultCallback,
QRCodeReaderView.OnQRCodeReadListener {
private static final int CAMERA_REQUEST_CODE = 0;
private QRCodeReaderView qrCodeReaderView;
private ViewStub qrCodeStub;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan_qr_code_activity);
qrCodeStub = findViewById(R.id.qr_code_stub);
findViewById(R.id.cancel_button).setOnClickListener(view -> finish());
if (ActivityCompat.checkSelfPermission(this, CAMERA) == PERMISSION_GRANTED) {
initQRCodeReaderView();
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, CAMERA)) {
Snackbar.make(qrCodeStub, R.string.permission_request, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, view -> requestCameraPermission())
.show();
} else {
requestCameraPermission();
}
}
}
private void initQRCodeReaderView() {
qrCodeStub.inflate();
qrCodeReaderView = findViewById(R.id.qr_code_reader);
qrCodeReaderView.setAutofocusInterval(2000L);
qrCodeReaderView.setOnQRCodeReadListener(this);
qrCodeReaderView.setBackCamera();
qrCodeReaderView.setQRDecodingEnabled(true);
qrCodeReaderView.startCamera();
}
@Override public void onBackPressed() {
startActivity(new Intent(this, StartAuthorizeActivity.class));
finish();
}
@Override public void onQRCodeRead(String authorizationCode, PointF[] points) {
qrCodeReaderView.setOnQRCodeReadListener(null);
AuthorizingActivity.start(this, authorizationCode);
finish();
}
private void requestCameraPermission() {
String[] permissions = { CAMERA };
ActivityCompat.requestPermissions(this, permissions, CAMERA_REQUEST_CODE);
}
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != CAMERA_REQUEST_CODE) {
return;
}
if (grantResults.length == 1 && grantResults[0] == PERMISSION_GRANTED) {
initQRCodeReaderView();
} else {
finish();
}
}
@Override protected void onResume() {
super.onResume();
if (qrCodeReaderView != null) {
qrCodeReaderView.startCamera();
}
}
@Override protected void onPause() {
super.onPause();
if (qrCodeReaderView != null) {
qrCodeReaderView.stopCamera();
}
}
}
| 8,909 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/settings/SettingsStore.java
|
package com.squareup.photobooth.settings;
import android.content.Context;
import android.content.SharedPreferences;
public final class SettingsStore {
public static final int DEFAULT_AMOUNT = 1_00;
private static final String LOCK_TASK_KEY = "lockTask";
private static final String PAYMENTS_ENABLED_KEY = "paymentsEnabled";
private static final String AMOUNT_KEY = "amount";
private static final String TWEET_MESSAGE_KEY = "tweetMessage";
private static final String LOG_HTTP_KEY = "logHttp";
private final SharedPreferences preferences;
public SettingsStore(Context context) {
Context appContext = context.getApplicationContext();
preferences = appContext.getSharedPreferences("settings", Context.MODE_PRIVATE);
}
public void setLockTask(boolean lockTask) {
preferences.edit().putBoolean(LOCK_TASK_KEY, lockTask).apply();
}
public boolean shouldLockTask() {
return preferences.getBoolean(LOCK_TASK_KEY, true);
}
public void setLogHttp(boolean logHttp) {
preferences.edit().putBoolean(LOG_HTTP_KEY, logHttp).apply();
}
public boolean shouldLogHttp() {
return preferences.getBoolean(LOG_HTTP_KEY, false);
}
public void setPaymentsEnabled(boolean paymentsEnabled) {
preferences.edit().putBoolean(PAYMENTS_ENABLED_KEY, paymentsEnabled).apply();
}
public boolean arePaymentsEnabled() {
return preferences.getBoolean(PAYMENTS_ENABLED_KEY, true);
}
public void setPaymentsAmount(int amount) {
preferences.edit().putInt(AMOUNT_KEY, amount).apply();
}
public int getPaymentsAmount() {
return preferences.getInt(AMOUNT_KEY, DEFAULT_AMOUNT);
}
public void setTweetMessage(String message) {
preferences.edit().putString(TWEET_MESSAGE_KEY, message).apply();
}
public String getTweetMessage() {
return preferences.getString(TWEET_MESSAGE_KEY, "Snap!");
}
}
| 8,910 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/settings/SettingsActivity.java
|
package com.squareup.photobooth.settings;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import com.squareup.photobooth.App;
import com.squareup.photobooth.BuildConfig;
import com.squareup.photobooth.R;
import com.squareup.sdk.reader.ReaderSdk;
import com.squareup.sdk.reader.authorization.AuthorizationManager;
import com.squareup.sdk.reader.authorization.AuthorizationState;
import com.squareup.sdk.reader.authorization.DeauthorizeErrorCode;
import com.squareup.sdk.reader.core.CallbackReference;
import com.squareup.sdk.reader.core.ResultError;
import com.squareup.sdk.reader.hardware.ReaderManager;
import com.squareup.sdk.reader.hardware.ReaderSettingsErrorCode;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
public class SettingsActivity extends AppCompatActivity {
private static final String TAG = SettingsActivity.class.getSimpleName();
private TwitterLoginButton twitterLoginButton;
private View twitterLogoutButton;
private TextView twitterStateView;
private EditText tweetMessageView;
private SettingsStore settingsStore;
private View readerSdkLoginButton;
private View readerSdkLogoutButton;
private TextView readerSdkLoginStateView;
private boolean waitingForActivityStart = false;
private CallbackReference deauthorizeCallbackRef;
private CallbackReference readerSettingsCallbackRef;
private EditText paymentAmountEdittext;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
AuthorizationManager authorizationManager = ReaderSdk.authorizationManager();
deauthorizeCallbackRef = authorizationManager.addDeauthorizeCallback(this::onDeauthorizeResult);
ReaderManager readerManager = ReaderSdk.readerManager();
readerSettingsCallbackRef =
readerManager.addReaderSettingsActivityCallback(this::onReaderSettingsResult);
App app = App.from(this);
settingsStore = app.settingsStore();
twitterLoginButton = findViewById(R.id.twitter_login_button);
twitterLogoutButton = findViewById(R.id.twitter_logout_button) ;
twitterLoginButton.setCallback(new Callback<TwitterSession>() {
@Override public void success(Result<TwitterSession> result) {
snack("Twitter login success");
updateTwitterState();
}
@Override public void failure(TwitterException exception) {
snack("Twitter login failure");
updateTwitterState();
}
});
twitterLogoutButton.setOnClickListener(view -> {
TwitterCore.getInstance().getSessionManager().clearActiveSession();
updateTwitterState();
});
CheckBox kioskCheckbox = findViewById(R.id.kiosk_check);
kioskCheckbox.setChecked(settingsStore.shouldLockTask());
kioskCheckbox.setOnCheckedChangeListener(
(compoundButton, checked) -> settingsStore.setLockTask(checked));
CheckBox paymentsCheckbox = findViewById(R.id.payments_check);
paymentsCheckbox.setChecked(settingsStore.arePaymentsEnabled());
paymentsCheckbox.setOnCheckedChangeListener(
(compoundButton, checked) -> settingsStore.setPaymentsEnabled(checked));
CheckBox httpLogCheckbox = findViewById(R.id.http_log_check);
httpLogCheckbox.setChecked(settingsStore.shouldLogHttp());
httpLogCheckbox.setOnCheckedChangeListener(
(compoundButton, checked) -> settingsStore.setLogHttp(checked));
paymentAmountEdittext = findViewById(R.id.payments_amount);
paymentAmountEdittext.setText(Integer.toString(settingsStore.getPaymentsAmount()));
tweetMessageView = findViewById(R.id.tweet_message);
tweetMessageView.setText(settingsStore.getTweetMessage());
twitterStateView = findViewById(R.id.twitter_state);
updateTwitterState();
readerSdkLoginButton = findViewById(R.id.readerSdk_login_button);
readerSdkLogoutButton = findViewById(R.id.readerSdk_logout_button);
readerSdkLoginStateView = findViewById(R.id.readerSdk_login_state);
readerSdkLoginButton.setOnClickListener(v -> goToAuthorizeActivity());
readerSdkLogoutButton.setOnClickListener(v -> deauthorize());
findViewById(R.id.readerSdk_connect_reader_button).setOnClickListener(v -> connectReader());
}
@Override protected void onResume() {
super.onResume();
waitingForActivityStart = false;
updateLoginState();
}
@Override protected void onPause() {
super.onPause();
settingsStore.setTweetMessage(tweetMessageView.getText().toString());
try {
int newAmount = Integer.parseInt(paymentAmountEdittext.getText().toString());
settingsStore.setPaymentsAmount(newAmount);
} catch (NumberFormatException ignored) {
}
}
@Override protected void onDestroy() {
super.onDestroy();
deauthorizeCallbackRef.clear();
readerSettingsCallbackRef.clear();
}
private void snack(String message) {
Snackbar.make(twitterLoginButton, message, Snackbar.LENGTH_SHORT).show();
}
private void updateTwitterState() {
TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
if (session == null) {
twitterStateView.setText("Twitter: not logged in.");
twitterLoginButton.setVisibility(View.VISIBLE);
twitterLogoutButton.setVisibility(View.GONE);
} else {
twitterStateView.setText("Twitter: logged in as " + session.getUserName());
twitterLoginButton.setVisibility(View.GONE);
twitterLogoutButton.setVisibility(View.VISIBLE);
}
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
twitterLoginButton.onActivityResult(requestCode, resultCode, data);
}
private void connectReader() {
if (waitingForActivityStart) {
return;
}
waitingForActivityStart = true;
ReaderManager readerManager = ReaderSdk.readerManager();
readerManager.startReaderSettingsActivity(this);
}
private void goToAuthorizeActivity() {
if (waitingForActivityStart) {
return;
}
waitingForActivityStart = true;
Intent intent = new Intent(this, StartAuthorizeActivity.class);
startActivity(intent);
}
private void deauthorize() {
AuthorizationManager authorizationManager = ReaderSdk.authorizationManager();
if (authorizationManager.getAuthorizationState().canDeauthorize()) {
authorizationManager.deauthorize();
} else {
showDialog(getString(R.string.cannot_deauthorize_dialog_title),
getString(R.string.cannot_deauthorize_dialog_message));
}
}
private void updateLoginState() {
AuthorizationState authorizationState = ReaderSdk.authorizationManager()
.getAuthorizationState();
boolean loggedIn = authorizationState.isAuthorized();
readerSdkLoginButton.setVisibility(loggedIn ? View.GONE : View.VISIBLE);
readerSdkLogoutButton.setVisibility(loggedIn ? View.VISIBLE : View.GONE);
if (!loggedIn) {
readerSdkLoginStateView.setText("Not logged in.");
return;
}
String businessLocation = authorizationState.getAuthorizedLocation().getBusinessName();
readerSdkLoginStateView.setText(Html.fromHtml(
String.format("<b><font color='#2780c4'>Merchant Name</color></b><br>%1$s<br><br><b>",
businessLocation)));
}
private void onDeauthorizeResult(
com.squareup.sdk.reader.core.Result<Void, ResultError<DeauthorizeErrorCode>> result) {
if (result.isSuccess()) {
showDialog("Success", "Sucessfully deauthorized");
updateLoginState();
} else {
showErrorDialog(result.getError());
}
}
private void showErrorDialog(ResultError<?> error) {
String dialogMessage = error.getMessage();
if (BuildConfig.DEBUG) {
dialogMessage += "\n\nDebug Message: " + error.getDebugMessage();
Log.d(TAG, error.getCode() + ": " + error.getDebugCode() + ", " + error.getDebugMessage());
}
showDialog(getString(R.string.error_dialog_title), dialogMessage);
}
private void showDialog(String title, String message) {
new AlertDialog.Builder(this).setTitle(title)
.setMessage(message)
.setPositiveButton("Ok", null)
.show();
}
private void onReaderSettingsResult(
com.squareup.sdk.reader.core.Result<Void, ResultError<ReaderSettingsErrorCode>> result) {
if (result.isError()) {
ResultError<ReaderSettingsErrorCode> error = result.getError();
switch (error.getCode()) {
case SDK_NOT_AUTHORIZED:
showDialog("Error", "Device not authorized");
break;
case USAGE_ERROR:
showErrorDialog(error);
break;
}
}
}
}
| 8,911 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/twitter/SendTweetJob.java
|
package com.squareup.photobooth.twitter;
import android.support.annotation.Nullable;
import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import timber.log.Timber;
public class SendTweetJob extends Job {
private static final int PRIORITY = 2;
private final String message;
private final String mediaId;
public SendTweetJob(String message, String mediaId) {
super(new Params(PRIORITY).requireNetwork().persist());
this.message = message;
this.mediaId = mediaId;
}
@Override public void onAdded() {
}
@Override protected void onCancel(int cancelReason, @Nullable Throwable throwable) {
}
@Override public void onRun() throws Throwable {
Tweeter tweeter = new Tweeter();
tweeter.tweet(message, mediaId);
}
@Override protected RetryConstraint shouldReRunOnThrowable(Throwable throwable, int runCount,
int maxRunCount) {
Timber.d("Could not send tweet", throwable);
RetryConstraint constraint = new RetryConstraint(true);
constraint.setNewDelayInMs(1000L);
return constraint;
}
}
| 8,912 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/twitter/UploadTweetPictureJob.java
|
package com.squareup.photobooth.twitter;
import android.support.annotation.Nullable;
import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.JobManager;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import com.squareup.photobooth.App;
import com.squareup.photobooth.job.InjectedJob;
import timber.log.Timber;
public class UploadTweetPictureJob extends InjectedJob {
private static final int PRIORITY = 2;
private final byte[] jpegBytes;
private final String message;
private transient volatile JobManager jobManager;
public UploadTweetPictureJob(byte[] jpegBytes, String message) {
super(new Params(PRIORITY).requireNetwork().persist());
this.jpegBytes = jpegBytes;
this.message = message;
}
@Override public void onAdded() {
}
@Override protected void onCancel(int cancelReason, @Nullable Throwable throwable) {
}
@Override public void onRun() throws Throwable {
Tweeter tweeter = new Tweeter();
String mediaId = tweeter.uploadPicture(jpegBytes);
jobManager.addJob(new SendTweetJob(message, mediaId));
}
@Override protected RetryConstraint shouldReRunOnThrowable(Throwable throwable, int runCount,
int maxRunCount) {
Timber.d("Could not upload tweet picture", throwable);
RetryConstraint constraint = new RetryConstraint(true);
constraint.setNewDelayInMs(1000L);
return constraint;
}
@Override public void inject(App app) {
jobManager = app.jobManager();
}
}
| 8,913 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/twitter/Tweeter.java
|
package com.squareup.photobooth.twitter;
import com.twitter.sdk.android.core.TwitterApiClient;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.models.Media;
import com.twitter.sdk.android.core.models.Tweet;
import com.twitter.sdk.android.core.services.MediaService;
import com.twitter.sdk.android.core.services.StatusesService;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Response;
public class Tweeter {
public String uploadPicture(byte[] jpegBytes) throws IOException {
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
MediaService mediaService = twitterApiClient.getMediaService();
RequestBody media = RequestBody.create(MediaType.parse("image/jpeg"), jpegBytes);
Response<Media> uploadResponse = mediaService.upload(media, null, null).execute();
if (!uploadResponse.isSuccessful()) {
throw new IOException("Upload not successful");
}
return uploadResponse.body().mediaIdString;
}
public void tweet(String message, String mediaId) throws IOException {
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
StatusesService statusesService = twitterApiClient.getStatusesService();
Response<Tweet> tweetResponse =
statusesService.update(message, null, false, null, null, null, null, false, mediaId)
.execute();
if (!tweetResponse.isSuccessful()) {
throw new IOException("Tweet not successful");
}
}
public boolean isLoggedIn() {
return TwitterCore.getInstance().getSessionManager().getActiveSession() != null;
}
}
| 8,914 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/result/DisplayPictureActivity.java
|
package com.squareup.photobooth.result;
import android.app.Activity;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.print.PrintHelper;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.photobooth.R;
import com.squareup.photobooth.printer.CloudPrinter;
import com.squareup.photobooth.start.KioskStartActivity;
import com.squareup.photobooth.twitter.Tweeter;
import com.squareup.photobooth.util.FullscreenActivity;
import static com.squareup.photobooth.printer.CloudPrinter.PRINT_FILENAME;
public class DisplayPictureActivity extends FullscreenActivity {
private static final String GRAPHIC_INDEX_EXTRA = "graphicIndex";
private static final String PICTURE_RATIO_EXTRA = "pictureRatio";
public static void start(Activity activity, int graphicIndex, float pictureRatio) {
Intent intent = new Intent(activity, DisplayPictureActivity.class);
intent.putExtra(GRAPHIC_INDEX_EXTRA, graphicIndex);
intent.putExtra(PICTURE_RATIO_EXTRA, pictureRatio);
activity.startActivity(intent);
}
private PictureViewModel pictureViewModel;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
findViewById(R.id.back).setOnClickListener(v -> finish());
ImageView pictureView = findViewById(R.id.picture);
TextView printButton = findViewById(R.id.print);
TextView printAndTweetButton = findViewById(R.id.print_tweet);
printButton.setEnabled(false);
printAndTweetButton.setEnabled(false);
Tweeter tweeter = new Tweeter();
if (!tweeter.isLoggedIn()) {
printAndTweetButton.setVisibility(View.GONE);
}
printButton.setOnClickListener(__ -> submit(false));
printAndTweetButton.setOnClickListener(__ -> submit(true));
pictureViewModel = ViewModelProviders.of(this).get(PictureViewModel.class);
if (savedInstanceState == null) {
Intent intent = getIntent();
int graphicIndex = intent.getIntExtra(GRAPHIC_INDEX_EXTRA, -1);
float pictureRatio = intent.getFloatExtra(PICTURE_RATIO_EXTRA, -1f);
pictureViewModel.renderBitmap(graphicIndex, pictureRatio);
}
pictureViewModel.renderedBitmap().observe(this, (bitmap) -> {
printButton.setEnabled(true);
printAndTweetButton.setEnabled(true);
pictureView.setImageBitmap(bitmap);
});
}
private void submit(boolean tweet) {
boolean printingAsync = pictureViewModel.submit(tweet);
if (printingAsync) {
done();
} else {
localPrint();
}
}
private void localPrint() {
Bitmap bitmap = pictureViewModel.renderedBitmap().getValue();
PrintHelper photoPrinter = new PrintHelper(this);
photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
photoPrinter.printBitmap(PRINT_FILENAME, bitmap, this::done);
}
private void done() {
Intent intent = new Intent(this, KioskStartActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
| 8,915 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/result/SavePictureToDiskJob.java
|
package com.squareup.photobooth.result;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.os.Environment;
import android.support.annotation.Nullable;
import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.JobManager;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import com.squareup.photobooth.App;
import com.squareup.photobooth.printer.PrintJob;
import com.squareup.photobooth.twitter.Tweeter;
import com.squareup.photobooth.twitter.UploadTweetPictureJob;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import timber.log.Timber;
/** This job is not serialized. */
public class SavePictureToDiskJob extends Job {
private final SimpleDateFormat timeFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
private static final int PRIORITY = 1;
private final JobManager jobManager;
private final Bitmap bitmap;
private final App app;
private final String message;
private final boolean cloudPrint;
private final boolean tweet;
public SavePictureToDiskJob(App app, Bitmap bitmap, String message, boolean cloudPrint, boolean tweet) {
super(new Params(PRIORITY));
this.app = app;
jobManager = app.jobManager();
this.bitmap = bitmap;
this.message = message;
this.cloudPrint = cloudPrint;
this.tweet = tweet;
}
@Override public void onAdded() {
}
@Override protected void onCancel(int cancelReason, @Nullable Throwable throwable) {
}
@Override public void onRun() throws Throwable {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] jpegBytes = stream.toByteArray();
if (tweet && new Tweeter().isLoggedIn()) {
jobManager.addJob(new UploadTweetPictureJob(jpegBytes, message));
}
if (cloudPrint) {
jobManager.addJob(new PrintJob(jpegBytes));
}
saveToDevice(bitmap);
}
private void saveToDevice(Bitmap bitmap) throws IOException {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String timeStamp = timeFormat.format(new Date());
String imageFileName = "squickpic_" + timeStamp + ".jpeg";
File file = new File(path, imageFileName);
path.mkdirs();
OutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
// Tell the media scanner about the new file so that it is immediately available to the user.
MediaScannerConnection.scanFile(app, new String[] { file.toString() }, null,
(path1, uri) -> Timber.d("Filed added %s", uri));
}
@Override protected RetryConstraint shouldReRunOnThrowable(Throwable throwable, int runCount,
int maxRunCount) {
Timber.d("Could not save picture", throwable);
return RetryConstraint.CANCEL;
}
}
| 8,916 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/result/PictureViewModel.java
|
package com.squareup.photobooth.result;
import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import com.birbit.android.jobqueue.JobManager;
import com.squareup.photobooth.App;
import com.squareup.photobooth.printer.CloudPrinter;
import com.squareup.photobooth.settings.SettingsStore;
import com.squareup.photobooth.snap.BitmapBytesHolder;
import com.squareup.photobooth.snap.PictureRenderer;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class PictureViewModel extends AndroidViewModel {
private final CloudPrinter cloudPrinter;
private final MutableLiveData<Bitmap> renderedBitmap = new MutableLiveData<>();
private final App app;
private final BitmapBytesHolder bitmapBytesHolder;
private final PictureRenderer pictureRenderer;
private final Executor backgroundExecutor;
private final Handler mainHandler;
private final JobManager jobManager;
private final SettingsStore settingsStore;
public PictureViewModel(Application application) {
super(application);
app = App.from(application);
this.cloudPrinter = app.cloudPrinter();
bitmapBytesHolder = app.bitmapHolder();
pictureRenderer = app.pictureRenderer();
settingsStore = app.settingsStore();
jobManager = app.jobManager();
backgroundExecutor = Executors.newSingleThreadExecutor();
mainHandler = new Handler(Looper.getMainLooper());
}
public LiveData<Bitmap> renderedBitmap() {
return renderedBitmap;
}
public void renderBitmap(int graphicIndex, float pictureRatio) {
if (renderedBitmap.getValue() != null) {
throw new IllegalStateException("Can only render bitmap once per view model");
}
byte[] bitmapBytes = bitmapBytesHolder.release();
backgroundExecutor.execute(() -> renderInBackground(bitmapBytes, graphicIndex, pictureRatio));
}
private void renderInBackground(byte[] bitmapBytes, int graphicIndex, float pictureRatio) {
Bitmap bitmap = pictureRenderer.render(bitmapBytes, graphicIndex, pictureRatio);
mainHandler.post(() -> renderedBitmap.setValue(bitmap));
}
public boolean submit(boolean tweet) {
Bitmap bitmap = renderedBitmap.getValue();
if (bitmap == null) {
throw new NullPointerException("bitmap should not be null");
}
boolean cloudPrint = cloudPrinter.isCloudPrintReady();
String tweetMessage = settingsStore.getTweetMessage();
SavePictureToDiskJob job = new SavePictureToDiskJob(app, bitmap, tweetMessage, cloudPrint, tweet);
jobManager.addJobInBackground(job);
return cloudPrint;
}
}
| 8,917 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/oauth/GoogleOAuthActivity.java
|
package com.squareup.photobooth.oauth;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.Toast;
import com.squareup.photobooth.App;
public class GoogleOAuthActivity extends Activity {
private static final String CLOUD_PRINT_SCOPE =
"oauth2:https://www.googleapis.com/auth/cloudprint";
private static final int ACCOUNT_CODE = 1;
private static final int CREDENTIALS_CODE = 2;
private AccountManager accountManager;
private GoogleOAuthStore oAuthStore;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accountManager = AccountManager.get(this);
oAuthStore = App.from(this).oAuthStore();
if (savedInstanceState == null) {
Intent intent =
AccountManager.newChooseAccountIntent(null, null, new String[] { "com.google" }, false,
null, null, null, null);
startActivityForResult(intent, ACCOUNT_CODE);
}
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CREDENTIALS_CODE) {
requestToken();
} else if (requestCode == ACCOUNT_CODE) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
oAuthStore.setAccountName(accountName);
oAuthStore.invalidateOAuthToken();
requestToken();
}
} else {
String message;
if (requestCode == CREDENTIALS_CODE) {
message = "Failed to obtain credentials";
} else if (requestCode == ACCOUNT_CODE) {
message = "Failed to select credentials";
} else {
message =
"Unexpected result code " + resultCode + " for unknown request code " + requestCode;
}
finishWithToast(message);
}
}
private void requestToken() {
String accountName = oAuthStore.getAccountName();
Account userAccount = null;
for (Account account : accountManager.getAccountsByType("com.google")) {
if (account.name.equals(accountName)) {
userAccount = account;
break;
}
}
if (userAccount == null) {
finishWithToast("Could not find account for " + accountName);
return;
}
accountManager.getAuthToken(userAccount,
CLOUD_PRINT_SCOPE, null, this, future -> {
Bundle bundle;
try {
bundle = future.getResult();
} catch (Exception e) {
throw new RuntimeException(e);
}
Intent credentialsIntent = (Intent) bundle.get(AccountManager.KEY_INTENT);
if (credentialsIntent != null) {
startActivityForResult(credentialsIntent, CREDENTIALS_CODE);
} else {
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
oAuthStore.setOAuthToken(token);
finishWithToast("OAuth Successful");
}
}, null);
}
private void finishWithToast(String message) {
Toast.makeText(GoogleOAuthActivity.this, message, Toast.LENGTH_LONG).show();
finish();
}
}
| 8,918 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/oauth/GoogleOAuthStore.java
|
package com.squareup.photobooth.oauth;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.Nullable;
public final class GoogleOAuthStore {
private static final String KEY_ACCOUNT_NAME = "accountName";
private static final String KEY_OAUTH_TOKEN = "token";
private final SharedPreferences preferences;
private final AccountManager accountManager;
public GoogleOAuthStore(Context context) {
Context appContext = context.getApplicationContext();
preferences = appContext.getSharedPreferences("google_oauth", Context.MODE_PRIVATE);
accountManager = AccountManager.get(appContext);
}
public void setOAuthToken(String oAuthToken) {
preferences.edit().putString(KEY_OAUTH_TOKEN, oAuthToken).apply();
}
public @Nullable String getOAuthToken() {
return preferences.getString(KEY_OAUTH_TOKEN, null);
}
public void setAccountName(String accountName) {
preferences.edit().putString(KEY_ACCOUNT_NAME, accountName).apply();
}
public @Nullable String getAccountName() {
return preferences.getString(KEY_ACCOUNT_NAME, null);
}
public void invalidateOAuthToken() {
String token = preferences.getString(KEY_OAUTH_TOKEN, null);
preferences.edit().remove(KEY_OAUTH_TOKEN).apply();
accountManager.invalidateAuthToken("com.google", token);
}
}
| 8,919 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/oauth/OAuthHeaderInterceptor.java
|
package com.squareup.photobooth.oauth;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class OAuthHeaderInterceptor implements Interceptor {
private static final String AUTHORIZATION_HEADER = "Authorization";
private final GoogleOAuthStore oAuthStore;
public OAuthHeaderInterceptor(GoogleOAuthStore oAuthStore) {
this.oAuthStore = oAuthStore;
}
@Override public Response intercept(Chain chain) throws IOException {
String oauthToken = oAuthStore.getOAuthToken();
Request request;
if (oauthToken != null) {
request = chain.request()
.newBuilder()
.addHeader(AUTHORIZATION_HEADER, "OAuth " + oauthToken)
.build();
} else {
request = chain.request();
}
return chain.proceed(request);
}
}
| 8,920 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/util/Preconditions.java
|
package com.squareup.photobooth.util;
import android.os.Looper;
public final class Preconditions {
public static void assertMainThread() {
if (Looper.getMainLooper().getThread() != Thread.currentThread()) {
throw new UnsupportedOperationException(
"Expected main thread, not " + Thread.currentThread());
}
}
private Preconditions() {
throw new AssertionError();
}
}
| 8,921 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/util/Activities.java
|
package com.squareup.photobooth.util;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.M;
public final class Activities {
public static boolean isAppInLockTaskMode(Activity activity) {
ActivityManager activityManager =
(ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
if (SDK_INT >= M) {
// For SDK version 23 and above.
return activityManager.getLockTaskModeState() != ActivityManager.LOCK_TASK_MODE_NONE;
}
if (SDK_INT >= LOLLIPOP) {
// When SDK version >= 21. This API is deprecated in 23.
return activityManager.isInLockTaskMode();
}
return false;
}
private Activities() {
throw new AssertionError();
}
}
| 8,922 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/util/AnimationListenerAdapter.java
|
package com.squareup.photobooth.util;
import android.animation.Animator;
public abstract class AnimationListenerAdapter implements Animator.AnimatorListener {
@Override public void onAnimationStart(Animator animator) {
}
@Override public void onAnimationEnd(Animator animator) {
}
@Override public void onAnimationCancel(Animator animator) {
}
@Override public void onAnimationRepeat(Animator animator) {
}
}
| 8,923 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/util/Animators.java
|
package com.squareup.photobooth.util;
import android.animation.Animator;
public final class Animators {
public interface AnimatorEndListener {
void onAnimationEnd(Animator animator);
}
public static Animator.AnimatorListener onAnimationEnd(AnimatorEndListener listener) {
return new AnimationListenerAdapter() {
@Override public void onAnimationEnd(Animator animator) {
listener.onAnimationEnd(animator);
}
};
}
private Animators() {
throw new AssertionError();
}
}
| 8,924 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/util/FullscreenActivity.java
|
package com.squareup.photobooth.util;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public abstract class FullscreenActivity extends AppCompatActivity {
@Override public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
setFullscreen();
}
}
@Override protected void onResume() {
super.onResume();
setFullscreen();
}
private void setFullscreen() {
getWindow().getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
| 8,925 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/util/SquareFrameLayout.java
|
package com.squareup.photobooth.util;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Point;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Display;
import android.view.WindowManager;
import android.widget.FrameLayout;
public class SquareFrameLayout extends FrameLayout {
// Android is full of nonsense for getting actual screen size including decor. More info at
// http://stackoverflow.com/questions/1016896/how-to-get-screen-dimensions
private static int screenWidth = -1;
private static int screenHeight = -1;
private static boolean generatedInPortait;
public static Point getScreenDimens(Context context) {
if (screenWidth == -1 || screenHeight == -1) {
initDimens(context);
}
if (generatedInPortait == isPortrait(context)) {
return new Point(screenWidth, screenHeight);
} else {
//noinspection SuspiciousNameCombination
return new Point(screenHeight, screenWidth);
}
}
private static void initDimens(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Point screenSize = new Point();
Display display = windowManager.getDefaultDisplay();
display.getRealSize(screenSize);
screenWidth = screenSize.x;
screenHeight = screenSize.y;
generatedInPortait = isPortrait(context);
}
public static boolean isPortrait(Context context) {
Configuration config = context.getResources().getConfiguration();
return config.orientation == Configuration.ORIENTATION_PORTRAIT;
}
private final int panelWidth;
private final int panelHeight;
private final boolean isLandscape;
public SquareFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
Point screenDimens = getScreenDimens(getContext());
panelWidth = screenDimens.x;
panelHeight = screenDimens.y;
isLandscape = panelWidth > panelHeight;
}
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int desiredVerticalPadding;
int desiredHorizontalPadding;
if (isLandscape) {
desiredHorizontalPadding = (width - panelHeight) / 2;
desiredVerticalPadding = 0;
} else {
desiredHorizontalPadding = 0;
desiredVerticalPadding = (height - panelWidth) / 2;
}
setPadding(desiredHorizontalPadding, desiredVerticalPadding, desiredHorizontalPadding,
desiredVerticalPadding);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
| 8,926 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/util/RecyclerSnaps.java
|
package com.squareup.photobooth.util;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SnapHelper;
import android.view.View;
import android.view.ViewTreeObserver;
import com.squareup.photobooth.snap.ui.GraphicRecyclerViewAdapter;
public class RecyclerSnaps {
public interface OnItemSnapListener {
void onItemSnap(int position);
}
public static void snapToView(View view) {
RecyclerView recyclerView = (RecyclerView) view.getParent();
int center = (recyclerView.getLeft() + recyclerView.getRight()) / 2;
int horizontalScroll = center - view.getLeft() - view.getWidth() / 2;
recyclerView.smoothScrollBy(-horizontalScroll, 0);
}
public static void centerSnap(RecyclerView recyclerView, OnItemSnapListener listener) {
Context context = recyclerView.getContext();
SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
LinearLayoutManager layoutManager =
new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(new GraphicRecyclerViewAdapter());
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
int first = layoutManager.findFirstVisibleItemPosition();
int last = layoutManager.findLastVisibleItemPosition();
int viewCenter = (recyclerView.getLeft() + recyclerView.getRight()) / 2;
int centerPosition = -1;
for (int i = first; i <= last; i++) {
View view = layoutManager.findViewByPosition(i);
if (view.getLeft() < viewCenter && view.getRight() > viewCenter) {
centerPosition = i;
break;
}
}
if (centerPosition != -1) {
listener.onItemSnap(centerPosition);
}
}
}
});
recyclerView.smoothScrollToPosition(0);
// We use padding to enable centering the first and last element.
recyclerView.setClipToPadding(false);
recyclerView.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override public void onGlobalLayout() {
recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Add left padding to center first item
View view = layoutManager.findViewByPosition(0);
RecyclerView.LayoutParams layoutParams =
(RecyclerView.LayoutParams) view.getLayoutParams();
int leftPadding =
recyclerView.getWidth() / 2 - view.getWidth() / 2 - layoutParams.getMarginStart();
recyclerView.setPadding(leftPadding, 0, recyclerView.getWidth() / 2, 0);
}
});
}
private RecyclerSnaps() {
throw new AssertionError();
}
}
| 8,927 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/util/TextWatcherAdapter.java
|
package com.squareup.photobooth.util;
import android.text.Editable;
import android.text.TextWatcher;
public abstract class TextWatcherAdapter implements TextWatcher {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override public void afterTextChanged(Editable s) {
}
}
| 8,928 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/printer/PrinterSetupActivity.java
|
package com.squareup.photobooth.printer;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.TextView;
import com.squareup.photobooth.App;
import com.squareup.photobooth.R;
import com.squareup.photobooth.oauth.GoogleOAuthActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PrinterSetupActivity extends AppCompatActivity {
private CloudPrinter cloudPrinter;
private TextView printerNameView;
private PrinterListAdapter listAdapter;
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup_printer);
App app = App.from(this);
cloudPrinter = app.cloudPrinter();
printerNameView = findViewById(R.id.selected_printer);
ListView printerList = findViewById(R.id.printer_list);
listAdapter = new PrinterListAdapter();
printerList.setAdapter(listAdapter);
printerList.setOnItemClickListener((parent, view, position, id) -> {
cloudPrinter.selectPrinter(listAdapter.getItem(position));
selectedPrinterUpdated();
});
findViewById(R.id.clear_printer).setOnClickListener(v -> {
cloudPrinter.clearPrinter();
selectedPrinterUpdated();
});
findViewById(R.id.oauth_button).setOnClickListener(
v -> startActivity(new Intent(PrinterSetupActivity.this, GoogleOAuthActivity.class)));
findViewById(R.id.update_printers).setOnClickListener(v -> downloadPrinterList());
selectedPrinterUpdated();
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
private void downloadPrinterList() {
cloudPrinter.search(new Callback<CloudPrintService.SearchResponse>() {
@Override public void onResponse(Call<CloudPrintService.SearchResponse> call,
Response<CloudPrintService.SearchResponse> response) {
if (response.isSuccessful()) {
CloudPrintService.SearchResponse searchResponse = response.body();
if (searchResponse.success) {
listAdapter.updatePrinterList(searchResponse.printers);
} else {
Snackbar.make(printerNameView, "Error: " + searchResponse.message, Snackbar.LENGTH_LONG)
.show();
}
} else {
Snackbar.make(printerNameView, "Http error", Snackbar.LENGTH_LONG).show();
}
}
@Override public void onFailure(Call<CloudPrintService.SearchResponse> call, Throwable t) {
Snackbar.make(printerNameView, "Network failure", Snackbar.LENGTH_LONG).show();
}
});
}
private void selectedPrinterUpdated() {
String printerName = cloudPrinter.getSelectedPrinterName();
if (printerName != null) {
printerNameView.setText("Selected printer: " + printerName);
} else {
printerNameView.setText("No printer selected");
}
}
}
| 8,929 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/printer/PrintJob.java
|
package com.squareup.photobooth.printer;
import android.support.annotation.Nullable;
import com.birbit.android.jobqueue.Params;
import com.birbit.android.jobqueue.RetryConstraint;
import com.squareup.photobooth.App;
import com.squareup.photobooth.job.InjectedJob;
import timber.log.Timber;
public class PrintJob extends InjectedJob {
private static final int PRIORITY = 1;
private final byte[] jpegBytes;
private transient volatile CloudPrinter cloudPrinter;
public PrintJob(byte[] jpegBytes) {
super(new Params(PRIORITY).requireNetwork().persist());
this.jpegBytes = jpegBytes;
}
@Override public void onAdded() {
}
@Override protected void onCancel(int cancelReason, @Nullable Throwable throwable) {
}
@Override public void onRun() throws Throwable {
cloudPrinter.cloudPrint(jpegBytes);
}
@Override protected RetryConstraint shouldReRunOnThrowable(Throwable throwable, int runCount,
int maxRunCount) {
Timber.d("Could not submit picture", throwable);
RetryConstraint constraint = new RetryConstraint(true);
constraint.setNewDelayInMs(1000L);
return constraint;
}
@Override public void inject(App app) {
cloudPrinter = app.cloudPrinter();
}
}
| 8,930 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/printer/PrinterListAdapter.java
|
package com.squareup.photobooth.printer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
import static java.util.Locale.US;
public class PrinterListAdapter extends BaseAdapter {
private List<CloudPrintService.Printer> printers = emptyList();
@Override public int getCount() {
return printers.size();
}
public void updatePrinterList(List<CloudPrintService.Printer> printers) {
this.printers = printers;
notifyDataSetChanged();
}
@Override public CloudPrintService.Printer getItem(int position) {
return printers.get(position);
}
@Override public long getItemId(int position) {
return position;
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
TextView textView;
if (convertView == null) {
textView = (TextView) LayoutInflater.from(parent.getContext())
.inflate(android.R.layout.simple_list_item_1, parent, false);
} else {
textView = (TextView) convertView;
}
CloudPrintService.Printer printer = getItem(position);
textView.setText(format(US, "%s (%s)", printer.description, printer.ownerName));
return textView;
}
}
| 8,931 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/printer/CloudPrintService.java
|
package com.squareup.photobooth.printer;
import java.util.List;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface CloudPrintService {
String CONNECTION_STATUS_ALL = "ALL";
@FormUrlEncoded //
@POST("search") //
Call<SearchResponse> search(@Field("connection_status") String connectionStatus,
@Field("q") String q, @Field("use_cdd") boolean useCdd);
@Multipart //
@POST("submit") //
Call<SubmitResponse> submit(@Part("printerid") RequestBody printerId,
@Part("title") RequestBody title, @Part("ticket") RequestBody ticket,
@Part MultipartBody.Part content, @Part("contentType") RequestBody contentType);
class SearchResponse {
public boolean success;
public String message;
public List<Printer> printers;
}
class SubmitResponse {
public boolean success;
public String message;
}
class Printer {
String id;
String name;
String displayName;
String description;
String ownerId;
String ownerName;
}
class Ticket {
final String version = "1.0";
final TicketPrint submit = new TicketPrint();
}
class TicketPrint {
final TicketPrintColor color = new TicketPrintColor();
final TicketPrintCopies copies = new TicketPrintCopies();
final TicketMediaSize media_size = new TicketMediaSize();
final TicketDpi dpi = new TicketDpi();
}
class TicketPrintColor {
enum ColorType {STANDARD_COLOR, STANDARD_MONOCHROME}
ColorType type = ColorType.STANDARD_COLOR;
}
// Defaults to max resolution of Selphy CP1300
class TicketDpi {
int horizontal_dpi = 300;
int vertical_dpi = 300;
}
class TicketPrintCopies {
int copies = 1;
}
// Defaults to card size, KC-36IP
class TicketMediaSize {
int width_microns = 54000;
int height_microns = 86000;
boolean is_continuous_feed = false;
}
}
| 8,932 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/printer/CloudPrinter.java
|
package com.squareup.photobooth.printer;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import com.squareup.photobooth.BuildConfig;
import com.squareup.photobooth.oauth.GoogleOAuthStore;
import com.squareup.photobooth.oauth.OAuthHeaderInterceptor;
import com.squareup.photobooth.settings.SettingsStore;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import timber.log.Timber;
import static com.squareup.photobooth.printer.CloudPrintService.CONNECTION_STATUS_ALL;
public class CloudPrinter {
public static final String PRINT_FILENAME = "squickpic.jpeg";
private static final String CLOUDPRINT_URL = "https://www.google.com/cloudprint/";
private static final String KEY_PRINTER_ID = "printerId";
private static final String KEY_PRINTER_NAME = "printerName";
private static final String FILE_TITLE = "Squickpic";
public static CloudPrinter create(GoogleOAuthStore oAuthStore, SettingsStore settingsStore,
Context context) {
Interceptor authorizationInterceptor = new OAuthHeaderInterceptor(oAuthStore);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG && settingsStore.shouldLogHttp()) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
builder.addInterceptor(loggingInterceptor);
}
OkHttpClient client = builder.addInterceptor(authorizationInterceptor).build();
Retrofit retrofit = new Retrofit.Builder().baseUrl(CLOUDPRINT_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
CloudPrintService cloudPrintService = retrofit.create(CloudPrintService.class);
return new CloudPrinter(cloudPrintService, context);
}
private final CloudPrintService cloudPrintService;
private final SharedPreferences preferences;
private final Gson gson;
private CloudPrinter(CloudPrintService cloudPrintService, Context context) {
this.cloudPrintService = cloudPrintService;
Context appContext = context.getApplicationContext();
preferences = appContext.getSharedPreferences("submit", Context.MODE_PRIVATE);
gson = new Gson();
}
public void search(Callback<CloudPrintService.SearchResponse> callback) {
cloudPrintService.search(CONNECTION_STATUS_ALL, null, true).enqueue(callback);
}
public void selectPrinter(CloudPrintService.Printer printer) {
preferences.edit()
.putString(KEY_PRINTER_ID, printer.id)
.putString(KEY_PRINTER_NAME, printer.description)
.apply();
}
@Nullable public String getSelectedPrinterName() {
return preferences.getString(KEY_PRINTER_NAME, null);
}
public void clearPrinter() {
preferences.edit().remove(KEY_PRINTER_ID).remove(KEY_PRINTER_NAME).apply();
}
public void cloudPrint(byte[] jpegBytes) throws IOException {
String printerId = preferences.getString(KEY_PRINTER_ID, null);
if (printerId == null) {
throw new UnsupportedOperationException("Please check isCloudPrintReady() first");
}
CloudPrintService.Ticket ticket = new CloudPrintService.Ticket();
String serializedTicket = gson.toJson(ticket);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), jpegBytes);
MultipartBody.Part content =
MultipartBody.Part.createFormData("content", PRINT_FILENAME, requestFile);
RequestBody printerIdBody = RequestBody.create(MultipartBody.FORM, printerId);
RequestBody titleBody = RequestBody.create(MultipartBody.FORM, FILE_TITLE);
RequestBody ticketBody = RequestBody.create(MultipartBody.FORM, serializedTicket);
RequestBody contentTypeBody = RequestBody.create(MultipartBody.FORM, "image/jpeg");
Response<CloudPrintService.SubmitResponse> printResponse =
cloudPrintService.submit(printerIdBody, titleBody, ticketBody, content, contentTypeBody)
.execute();
if (!printResponse.isSuccessful()) {
throw new IOException("Print submit not successful");
}
CloudPrintService.SubmitResponse submitResponse = printResponse.body();
if (!submitResponse.success) {
throw new IOException("Server error: " + submitResponse.message);
}
}
public boolean isCloudPrintReady() {
String printerId = preferences.getString(KEY_PRINTER_ID, null);
return printerId != null;
}
}
| 8,933 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/start/KioskStartActivity.java
|
package com.squareup.photobooth.start;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.squareup.photobooth.App;
import com.squareup.photobooth.BuildConfig;
import com.squareup.photobooth.R;
import com.squareup.photobooth.settings.SettingsStore;
import com.squareup.photobooth.settings.StartAuthorizeActivity;
import com.squareup.photobooth.snap.SnapActivity;
import com.squareup.photobooth.util.Activities;
import com.squareup.photobooth.util.FullscreenActivity;
import com.squareup.sdk.reader.ReaderSdk;
import com.squareup.sdk.reader.authorization.AuthorizationManager;
import com.squareup.sdk.reader.checkout.CheckoutErrorCode;
import com.squareup.sdk.reader.checkout.CheckoutManager;
import com.squareup.sdk.reader.checkout.CheckoutParameters;
import com.squareup.sdk.reader.checkout.CheckoutResult;
import com.squareup.sdk.reader.checkout.CurrencyCode;
import com.squareup.sdk.reader.checkout.Money;
import com.squareup.sdk.reader.core.CallbackReference;
import com.squareup.sdk.reader.core.Result;
import com.squareup.sdk.reader.core.ResultError;
import timber.log.Timber;
public class KioskStartActivity extends FullscreenActivity {
private CallbackReference checkoutCallbackRef;
private boolean waitingForActivityStart = false;
private SettingsStore settingsStore;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kiosk_start_activity);
settingsStore = App.from(this).settingsStore();
CheckoutManager checkoutManager = ReaderSdk.checkoutManager();
checkoutCallbackRef = checkoutManager.addCheckoutActivityCallback(this::onCheckoutResult);
View entireScreen = findViewById(R.id.entire_screen);
entireScreen.setOnClickListener(view -> onScreenTapped());
}
private void onScreenTapped() {
AuthorizationManager authorizationManager = ReaderSdk.authorizationManager();
boolean readerSdkAuthorized = authorizationManager.getAuthorizationState().isAuthorized();
if (settingsStore.arePaymentsEnabled() && readerSdkAuthorized) {
startCheckout();
} else {
startActivity(new Intent(this, SnapActivity.class));
}
}
private void startCheckout() {
if (waitingForActivityStart) {
return;
}
waitingForActivityStart = true;
Money checkoutAmount = new Money(settingsStore.getPaymentsAmount(), CurrencyCode.current());
CheckoutManager checkoutManager = ReaderSdk.checkoutManager();
CheckoutParameters.Builder params = CheckoutParameters.newBuilder(checkoutAmount)
.skipReceipt(true)
.alwaysRequireSignature(false)
.note("Smile! 📸");
checkoutManager.startCheckoutActivity(this, params.build());
}
private void onCheckoutResult(Result<CheckoutResult, ResultError<CheckoutErrorCode>> result) {
if (result.isSuccess()) {
startActivity(new Intent(getBaseContext(), SnapActivity.class));
} else {
ResultError<CheckoutErrorCode> error = result.getError();
switch (error.getCode()) {
case SDK_NOT_AUTHORIZED:
authorizeReaderSdk();
break;
case CANCELED:
Toast.makeText(this, R.string.checkout_canceled_toast, Toast.LENGTH_SHORT).show();
break;
case USAGE_ERROR:
showErrorDialog(error);
break;
}
}
}
private void authorizeReaderSdk() {
if (waitingForActivityStart) {
return;
}
waitingForActivityStart = true;
Intent intent = new Intent(this, StartAuthorizeActivity.class);
startActivity(intent);
finish();
}
private void showErrorDialog(ResultError<?> error) {
String dialogMessage = error.getMessage();
if (BuildConfig.DEBUG) {
dialogMessage += "\n\nDebug Message: " + error.getDebugMessage();
Timber.d("%s: %s, %s", error.getCode(), error.getDebugCode(), error.getDebugMessage());
}
showDialog(getString(R.string.error_dialog_title), dialogMessage);
}
private void showDialog(CharSequence title, CharSequence message) {
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok,
(dialogInterface, i) -> startActivity(new Intent(getBaseContext(), SnapActivity.class)))
.setOnDismissListener(
dialogInterface -> startActivity(new Intent(getBaseContext(), SnapActivity.class)))
.show();
}
@Override protected void onResume() {
super.onResume();
waitingForActivityStart = false;
}
@Override protected void onDestroy() {
super.onDestroy();
checkoutCallbackRef.clear();
}
@Override public void onBackPressed() {
if (Activities.isAppInLockTaskMode(this)) {
Toast.makeText(this, R.string.app_task_locked, Toast.LENGTH_SHORT).show();
return;
}
super.onBackPressed();
}
}
| 8,934 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/Scaler.java
|
package com.squareup.photobooth.snap;
public interface Scaler {
Scaler ISO = new Scaler() {
@Override public float translateX(float x) {
return x;
}
@Override public float translateY(float y) {
return y;
}
@Override public float scaleHorizontal(float width) {
return width;
}
@Override public float scaleVertical(float height) {
return height;
}
@Override public boolean isFrontFacing() {
return false;
}
};
/** Use for x positions */
float translateX(float x);
/** Use for y positions */
float translateY(float y);
float scaleHorizontal(float width);
float scaleVertical(float height);
boolean isFrontFacing();
}
| 8,935 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/BitmapBytesHolder.java
|
package com.squareup.photobooth.snap;
import static com.squareup.photobooth.util.Preconditions.assertMainThread;
public class BitmapBytesHolder {
private byte[] bitmapBytes;
public void hold(byte[] bitmapBytes) {
assertMainThread();
this.bitmapBytes = bitmapBytes;
}
public byte[] release() {
assertMainThread();
byte[] bitmapBytes = this.bitmapBytes;
this.bitmapBytes = null;
return bitmapBytes;
}
}
| 8,936 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/SnapActivity.java
|
package com.squareup.photobooth.snap;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.MultiProcessor;
import com.google.android.gms.vision.Tracker;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import com.squareup.photobooth.App;
import com.squareup.photobooth.R;
import com.squareup.photobooth.result.DisplayPictureActivity;
import com.squareup.photobooth.settings.SettingsStore;
import com.squareup.photobooth.snap.camera.CameraSourcePreview;
import com.squareup.photobooth.snap.camera.GraphicOverlay;
import com.squareup.photobooth.snap.graphic.FaceGraphic;
import com.squareup.photobooth.snap.graphic.GraphicFactory;
import com.squareup.photobooth.util.Activities;
import com.squareup.photobooth.util.FullscreenActivity;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import timber.log.Timber;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static com.squareup.photobooth.util.Animators.onAnimationEnd;
import static com.squareup.photobooth.util.RecyclerSnaps.centerSnap;
public class SnapActivity extends FullscreenActivity {
// Higher frame rates can lead to dark preview
// https://github.com/googlesamples/android-vision/issues/162#issuecomment-271508706
//private static final float MAX_FRAME_RATE = 15.0f;
// On the other hands, 30fps works fine on Pixel-C and lower leads to lag on activity transition.
private static final float MAX_FRAME_RATE = 30f;
private static final int COUNT_DOWN_SECONDS = 4;
private CameraSource cameraSource = null;
private CameraSourcePreview preview;
private GraphicOverlay graphicOverlay;
private static final int RC_HANDLE_GMS = 9001;
private static final int PERMISSION_REQUEST_CODE = 1;
private volatile int graphicIndex;
private final List<GraphicFaceTracker> faceTrackers = new ArrayList<>();
private BitmapBytesHolder bitmapBytesHolder;
private int countDown = 0;
private TextView countDownView;
private SettingsStore settingsStore;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.snap);
App app = App.from(this);
bitmapBytesHolder = app.bitmapHolder();
settingsStore = app.settingsStore();
preview = findViewById(R.id.preview);
countDownView = findViewById(R.id.count_down);
graphicOverlay = preview.getGraphicOverlay();
if (hasPermission(CAMERA) && hasPermission(WRITE_EXTERNAL_STORAGE)) {
createCameraSource();
} else {
requestRequiredPermissions();
}
RecyclerView recyclerView = findViewById(R.id.graphic_recycler_view);
centerSnap(recyclerView, (position) -> updateGraphicFactory(GraphicFactory.values()[position]));
}
private boolean hasPermission(String permission) {
return ActivityCompat.checkSelfPermission(this, permission) == PERMISSION_GRANTED;
}
public void updateGraphicFactory(GraphicFactory graphicFactory) {
graphicIndex = graphicFactory.ordinal();
for (GraphicFaceTracker faceTracker : faceTrackers) {
faceTracker.faceGraphic = createFaceGraphic();
}
graphicOverlay.postInvalidate();
}
private FaceGraphic createFaceGraphic() {
return GraphicFactory.values()[graphicIndex].create(this);
}
private void requestRequiredPermissions() {
String[] permissions = new String[] { CAMERA, WRITE_EXTERNAL_STORAGE };
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, CAMERA)
&& !ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
return;
}
View.OnClickListener listener =
view -> ActivityCompat.requestPermissions(SnapActivity.this, permissions,
PERMISSION_REQUEST_CODE);
Snackbar.make(graphicOverlay, "Access to camera and external storage permissions required.",
Snackbar.LENGTH_INDEFINITE).setAction(R.string.ok, listener).show();
}
private void createCameraSource() {
Context context = getApplicationContext();
FaceDetector detector = createFaceDetector(context);
detector.setProcessor(new MultiProcessor.Builder<>(new GraphicFaceTrackerFactory()).build());
if (!detector.isOperational()) {
Timber.d("Face detector dependencies are not yet available.");
}
cameraSource = new CameraSource.Builder(context, detector) //
// Camera will decide actual size, and we'll crop accordingly in layout.
.setRequestedPreviewSize(640, 480)
.setFacing(CameraSource.CAMERA_FACING_FRONT)
.setRequestedFps(MAX_FRAME_RATE)
.setAutoFocusEnabled(true)
.build();
findViewById(R.id.photo_button).setOnClickListener(v -> startCountDown());
}
private void startCountDown() {
countDown = COUNT_DOWN_SECONDS + 1;
countDownView.setVisibility(View.VISIBLE);
countDown();
}
private void countDown() {
countDownView.setScaleX(1);
countDownView.setScaleY(1);
countDownView.animate()
.setDuration(1000)
.scaleX(0)
.scaleY(0)
.setListener(onAnimationEnd((animator) -> {
if (countDown == COUNT_DOWN_SECONDS + 1) {
// count down got restarted.
return;
}
if (countDown == 1) {
countDownView.setVisibility(View.INVISIBLE);
takePicture();
} else {
countDown();
}
}));
countDown--;
countDownView.setText(String.format(Locale.getDefault(), "%d", countDown));
}
private void takePicture() {
CameraSource.ShutterCallback shutterCallback = () -> {
};
CameraSource.PictureCallback pictureCallback = data -> {
bitmapBytesHolder.hold(data);
DisplayPictureActivity.start(this, graphicIndex, PictureRenderer.PRINTED_CARD_RATIO);
};
try {
cameraSource.takePicture(shutterCallback, pictureCallback);
} catch (RuntimeException e) {
// Sometimes Camera.native_takePicture throws with no explanation.
Timber.d(e, "takePicture native code threw an exception");
Toast.makeText(this, "Failed to take picture", Toast.LENGTH_SHORT).show();
}
}
private FaceDetector createFaceDetector(Context context) {
return new FaceDetector.Builder(context) //
.setLandmarkType(FaceDetector.ALL_LANDMARKS) //
.setClassificationType(FaceDetector.NO_CLASSIFICATIONS) //
.setTrackingEnabled(true).setMode(FaceDetector.FAST_MODE).build();
}
@Override protected void onResume() {
super.onResume();
startCameraSource();
}
@Override protected void onPause() {
super.onPause();
preview.stop();
}
@Override public void onBackPressed() {
if (settingsStore.arePaymentsEnabled()) {
new AlertDialog.Builder(this).setTitle("Are you sure?")
.setMessage("You will lose your credit if you leave now")
.setPositiveButton("No Picture for me!", (dialog, which) -> finish())
.setNegativeButton("Stay here", null)
.show();
} else {
if (Activities.isAppInLockTaskMode(this)) {
Toast.makeText(this, "App task is locked", Toast.LENGTH_SHORT).show();
return;
} else {
finish();
}
}
}
/**
* Releases the resources associated with the camera source, the associated detector, and the
* rest of the processing pipeline.
*/
@Override protected void onDestroy() {
super.onDestroy();
if (cameraSource != null) {
cameraSource.release();
}
}
@Override public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode != PERMISSION_REQUEST_CODE) {
Timber.d("Got unexpected permission result: " + requestCode);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
return;
}
if (grantResults.length == 2
&& grantResults[0] == PERMISSION_GRANTED
&& grantResults[1] == PERMISSION_GRANTED) {
Timber.d("Permissions granted - initialize the camera source");
createCameraSource();
return;
}
new AlertDialog.Builder(this).setTitle("Camera or storage permission missing")
.setMessage("The camera and storage permissions are required to take pictures.")
.setPositiveButton(R.string.ok, (dialog, id) -> finish())
.show();
}
private void startCameraSource() {
// check that the device has play services available.
int code =
GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS).show();
}
if (cameraSource != null) {
preview.start(cameraSource, graphicOverlay, PictureRenderer.PRINTED_CARD_RATIO);
}
}
private class GraphicFaceTrackerFactory implements MultiProcessor.Factory<Face> {
@Override public Tracker<Face> create(Face face) {
return new GraphicFaceTracker();
}
}
private class GraphicFaceTracker extends Tracker<Face> implements Graphic {
// Updated when changing graphic.
private FaceGraphic faceGraphic;
@Override public void onNewItem(int i, Face face) {
faceGraphic = createFaceGraphic();
faceTrackers.add(this);
}
@Override public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {
faceGraphic.updateFace(face);
graphicOverlay.update(this);
}
@Override public void onMissing(FaceDetector.Detections<Face> detectionResults) {
graphicOverlay.forget(this);
faceGraphic.forgetFace();
}
@Override public void onDone() {
graphicOverlay.forget(this);
faceGraphic.forgetFace();
faceTrackers.remove(this);
}
@Override public void draw(Canvas canvas) {
faceGraphic.draw(canvas, graphicOverlay);
}
}
}
| 8,937 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/Graphic.java
|
package com.squareup.photobooth.snap;
import android.graphics.Canvas;
public interface Graphic {
void draw(Canvas canvas);
}
| 8,938 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/PictureRenderer.java
|
package com.squareup.photobooth.snap;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.support.media.ExifInterface;
import android.util.SparseArray;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import com.squareup.photobooth.R;
import com.squareup.photobooth.snap.graphic.FaceGraphic;
import com.squareup.photobooth.snap.graphic.GraphicFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import timber.log.Timber;
import static android.support.media.ExifInterface.ORIENTATION_UNDEFINED;
import static android.support.media.ExifInterface.TAG_ORIENTATION;
public class PictureRenderer {
private static final int PRINTED_WIDTH_INCH = 86;
private static final int PRINTED_HEIGHT_INCH = 54;
private static final int PRINTER_DPI = 300;
/** Ratio of the KC-36IP cards, 54x86mm */
public static final float PRINTED_CARD_RATIO = (PRINTED_WIDTH_INCH * 1.0f) / PRINTED_HEIGHT_INCH;
private final Context context;
private final Paint textPaint;
private final Paint textShadowPaint;
public PictureRenderer(Context context) {
this.context = context.getApplicationContext();
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(context.getResources().getColor(R.color.white));
textPaint.setTextAlign(Paint.Align.RIGHT);
textShadowPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textShadowPaint.setColor(context.getResources().getColor(R.color.grey));
textShadowPaint.setTextAlign(Paint.Align.RIGHT);
}
public Bitmap render(byte[] data, int graphicIndex, float requiredRatio) {
FaceGraphic faceGraphic = GraphicFactory.values()[graphicIndex].create(context);
InputStream inputStream = new ByteArrayInputStream(data);
int orientation;
try {
ExifInterface exif = new ExifInterface(inputStream);
orientation = exif.getAttributeInt(TAG_ORIENTATION, ORIENTATION_UNDEFINED);
} catch (IOException unexpected) {
Timber.d(unexpected);
orientation = ORIENTATION_UNDEFINED;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inMutable = true;
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
bitmap = rotateBitmap(bitmap, orientation);
if (!bitmap.isMutable()) {
// If rotation created an immutable bitmap
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
bitmap.recycle();
bitmap = mutableBitmap;
}
FaceDetector detector = new FaceDetector.Builder(context) //
.setLandmarkType(FaceDetector.ALL_LANDMARKS) //
.setClassificationType(FaceDetector.NO_CLASSIFICATIONS) //
.setTrackingEnabled(false) //
.setMode(FaceDetector.ACCURATE_MODE).build();
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<Face> faces = detector.detect(frame);
Canvas canvas = new Canvas(bitmap);
for (int i = 0; i < faces.size(); i++) {
int key = faces.keyAt(i);
Face face = faces.get(key);
faceGraphic.updateFace(face);
faceGraphic.draw(canvas, Scaler.ISO);
faceGraphic.forgetFace();
}
detector.release();
int height = bitmap.getHeight();
int width = bitmap.getWidth();
if (height > width) {
requiredRatio = 1f / requiredRatio;
}
float bitmapRatio = (width * 1f) / height;
boolean bitmapHasLargerWidth = bitmapRatio > requiredRatio;
if (bitmapHasLargerWidth) {
int requiredWidth = (int) (requiredRatio * height);
int offset = (width - requiredWidth) / 2;
Bitmap oldBitmap = bitmap;
bitmap = Bitmap.createBitmap(bitmap, offset, 0, requiredWidth, height);
oldBitmap.recycle();
} else {
int requiredHeight = (int) (width / requiredRatio);
int offset = (height - requiredHeight) / 2;
Bitmap oldBitmap = bitmap;
bitmap = Bitmap.createBitmap(bitmap, 0, offset, width, requiredHeight);
oldBitmap.recycle();
}
int newWidth = bitmap.getWidth();
int newHeight = bitmap.getHeight();
int smallestSide = Math.min(newWidth, newHeight);
//int watermarkSize = smallestSide / 4;
canvas = new Canvas(bitmap);
int textSize = smallestSide / 16;
int textTopMargin = textSize;
int textRightMargin = textSize /2;
textPaint.setTextSize(textSize);
textShadowPaint.setTextSize(textSize);
//canvas.drawBitmap(watermark, null, rect, null);
int x = newWidth - textRightMargin;
canvas.drawText("squ.re/SquickPic", x + 4, textTopMargin + 4, textShadowPaint);
canvas.drawText("squ.re/SquickPic", x, textTopMargin, textPaint);
int maxHeight = PRINTER_DPI * PRINTED_HEIGHT_INCH;
if (smallestSide > maxHeight) {
float scaleRatio = (maxHeight * 1f) / smallestSide;
int scaledWidth = (int) (newWidth * scaleRatio);
int scaledHeight = (int) (newHeight * scaleRatio);
Bitmap oldBitmap = bitmap;
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
oldBitmap.recycle();
}
return bitmap;
}
// https://stackoverflow.com/a/20480741/703646
private static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
Bitmap rotatedBitmap =
Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return rotatedBitmap;
}
}
| 8,939 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/ui/GraphicRecyclerViewAdapter.java
|
package com.squareup.photobooth.snap.ui;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.photobooth.R;
import com.squareup.photobooth.snap.graphic.GraphicFactory;
import com.squareup.photobooth.util.RecyclerSnaps;
public class GraphicRecyclerViewAdapter
extends RecyclerView.Adapter<GraphicRecyclerViewAdapter.ViewHolder> {
@Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(R.layout.graphic_item, parent, false);
return new ViewHolder(itemView);
}
@Override public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(GraphicFactory.values()[position]);
}
@Override public int getItemCount() {
return GraphicFactory.values().length;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
}
public void bind(GraphicFactory graphicFactory) {
((ImageView) itemView).setImageResource(graphicFactory.drawableResId);
itemView.setOnClickListener((view) -> RecyclerSnaps.snapToView(itemView));
}
}
}
| 8,940 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/ui/CameraButton.java
|
package com.squareup.photobooth.snap.ui;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import com.squareup.photobooth.R;
public class CameraButton extends View {
private final Paint outerPaint;
private final Paint innerPaint;
private final int strokeWidth;
public CameraButton(Context context, AttributeSet attrs) {
super(context, attrs);
strokeWidth = getResources().getDimensionPixelSize(R.dimen.camera_button_stroke);
outerPaint = new Paint();
outerPaint.setColor(0xffffffff);
outerPaint.setStyle(Paint.Style.STROKE);
outerPaint.setStrokeWidth(strokeWidth);
outerPaint.setAntiAlias(true);
innerPaint = new Paint();
innerPaint.setColor(context.getResources().getColor(R.color.reader_blue));
innerPaint.setStyle(Paint.Style.STROKE);
innerPaint.setStrokeWidth(strokeWidth / 2f);
innerPaint.setAntiAlias(true);
}
@Override public boolean onTouchEvent(MotionEvent event) {
boolean handled = super.onTouchEvent(event);
if (handled) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
animate().scaleX(0.5f)
.scaleY(0.5f)
.setInterpolator(new AccelerateDecelerateInterpolator());
break;
case MotionEvent.ACTION_UP:
animate().scaleX(1f).scaleY(1f).setInterpolator(new AccelerateDecelerateInterpolator());
break;
}
}
return handled;
}
@Override protected void onDraw(Canvas canvas) {
int width = getWidth();
float centerX = width / 2f;
int height = getHeight();
float centerY = height / 2f;
float radius = Math.min(width, height) / 2 - strokeWidth;
canvas.drawCircle(centerX, centerY, radius, outerPaint);
canvas.drawCircle(centerX, centerY, radius, innerPaint);
}
}
| 8,941 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/camera/GraphicOverlay.java
|
package com.squareup.photobooth.snap.camera;
import android.content.Context;
import android.graphics.Canvas;
import android.view.View;
import com.google.android.gms.vision.CameraSource;
import com.squareup.photobooth.snap.Graphic;
import com.squareup.photobooth.snap.Scaler;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* A view which renders a series of custom graphics to be overlayed on top of an associated preview
* (i.e., the camera preview). The creator can add graphics objects, update the objects, and
* update them, triggering the appropriate drawing and invalidation within the view.<p>
*
* Supports scaling and mirroring of the graphics relative the camera's preview properties. The
* idea is that detection items are expressed in terms of a preview size, but need to be scaled up
* to the full view size, and also mirrored in the case of the front-facing camera.<p>
*/
public class GraphicOverlay extends View implements Scaler {
private final Object lock = new Object();
private final Set<Graphic> graphics = new LinkedHashSet<>();
private int previewWidth;
private float widthScaleFactor = 1.0f;
private int previewHeight;
private float heightScaleFactor = 1.0f;
private int facing = CameraSource.CAMERA_FACING_BACK;
@Override public float scaleHorizontal(float horizontal) {
return horizontal * widthScaleFactor;
}
@Override public float scaleVertical(float vertical) {
return vertical * heightScaleFactor;
}
@Override public boolean isFrontFacing() {
return facing == CameraSource.CAMERA_FACING_FRONT;
}
@Override public float translateX(float x) {
if (facing == CameraSource.CAMERA_FACING_FRONT) {
return getWidth() - scaleHorizontal(x);
} else {
return scaleHorizontal(x);
}
}
@Override public float translateY(float y) {
return scaleVertical(y);
}
public GraphicOverlay(Context context) {
super(context);
}
/**
* Removes all graphics from the overlay.
*/
public void clear() {
synchronized (lock) {
graphics.clear();
}
postInvalidate();
}
/**
* Adds a graphic to the overlay.
*/
public void update(Graphic graphic) {
synchronized (lock) {
graphics.add(graphic);
}
postInvalidate();
}
/**
* Removes a graphic from the overlay.
*/
public void forget(Graphic graphic) {
synchronized (lock) {
graphics.remove(graphic);
}
postInvalidate();
}
/**
* Sets the camera attributes for size and facing direction, which informs how to transform
* image coordinates later.
*/
public void setCameraInfo(int previewWidth, int previewHeight, int facing) {
synchronized (lock) {
this.previewWidth = previewWidth;
this.previewHeight = previewHeight;
this.facing = facing;
}
postInvalidate();
}
/**
* Draws the overlay with its associated graphic objects.
*/
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
synchronized (lock) {
if ((previewWidth != 0) && (previewHeight != 0)) {
widthScaleFactor = (float) canvas.getWidth() / (float) previewWidth;
heightScaleFactor = (float) canvas.getHeight() / (float) previewHeight;
}
for (Graphic graphic : graphics) {
graphic.draw(canvas);
}
}
}
}
| 8,942 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/camera/CameraSourcePreview.java
|
package com.squareup.photobooth.snap.camera;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.common.images.Size;
import com.google.android.gms.vision.CameraSource;
import com.squareup.photobooth.R;
import java.io.IOException;
import timber.log.Timber;
public class CameraSourcePreview extends ViewGroup {
private final Context context;
private final SurfaceView surfaceView;
private final View cropLayer;
private final GraphicOverlay graphicOverlay;
private boolean startRequested;
private boolean surfaceAvailable;
private CameraSource cameraSource;
private GraphicOverlay overlay;
private float requiredRatio;
public CameraSourcePreview(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
startRequested = false;
surfaceAvailable = false;
surfaceView = new SurfaceView(context);
surfaceView.getHolder().addCallback(new SurfaceCallback());
addView(surfaceView);
cropLayer = new View(context);
cropLayer.setBackgroundColor(context.getResources().getColor(R.color.background_color));
addView(cropLayer);
graphicOverlay = new GraphicOverlay(context);
addView(graphicOverlay);
}
public GraphicOverlay getGraphicOverlay() {
return graphicOverlay;
}
public void start(CameraSource cameraSource, GraphicOverlay overlay, float requiredRatio) {
this.requiredRatio = requiredRatio;
this.overlay = overlay;
this.cameraSource = cameraSource;
startRequested = true;
startIfReady();
}
public void stop() {
if (cameraSource != null) {
cameraSource.stop();
}
}
// Permission checking is handled by the activity.
@SuppressLint("MissingPermission") //
private void startIfReady() {
if (startRequested && surfaceAvailable) {
boolean noPreviewSize = cameraSource.getPreviewSize() == null;
try {
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
cameraSource.release();
Timber.d("Could not start camera source.", e);
return;
}
if (noPreviewSize) {
// We called start() so we now have a preview size, ready to layout correctly.
requestLayout();
}
if (overlay != null) {
Size size = cameraSource.getPreviewSize();
int min = Math.min(size.getWidth(), size.getHeight());
int max = Math.max(size.getWidth(), size.getHeight());
if (isPortraitMode()) {
// Swap width and height sizes when in portrait, since it will be rotated by
// 90 degrees
overlay.setCameraInfo(min, max, cameraSource.getCameraFacing());
} else {
overlay.setCameraInfo(max, min, cameraSource.getCameraFacing());
}
overlay.clear();
}
startRequested = false;
}
}
private class SurfaceCallback implements SurfaceHolder.Callback {
@Override public void surfaceCreated(SurfaceHolder surface) {
surfaceAvailable = true;
startIfReady();
}
@Override public void surfaceDestroyed(SurfaceHolder surface) {
surfaceAvailable = false;
}
@Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
}
@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int layoutWidth = right - left;
int layoutHeight = bottom - top;
Size size = null;
if (cameraSource != null) {
size = cameraSource.getPreviewSize();
}
if (size == null) {
// This triggers the surface creation
surfaceView.layout(0, 0, layoutWidth, layoutHeight);
// We don't know the camera preview size because we haven't started yet, so we can't layout.
return;
}
int previewWidth = size.getWidth();
int previewHeight = size.getHeight();
// Swap width and height sizes when in portrait, since it will be rotated 90 degrees
float requiredRatio;
if (isPortraitMode()) {
int tmp = previewWidth;
//noinspection SuspiciousNameCombination
previewWidth = previewHeight;
previewHeight = tmp;
requiredRatio = 1 / this.requiredRatio;
} else {
requiredRatio = this.requiredRatio;
}
// We're dealing with 3 rectangles with distinct ratios here: the layout, the camera, and
// the printed photo.
float previewRatio = (previewWidth * 1f) / previewHeight;
float layoutRatio = (layoutWidth * 1f) / layoutHeight;
boolean previewHasLargerWidth = previewRatio > requiredRatio;
boolean layoutHasLargerWidth = layoutRatio > requiredRatio;
int displayedSurfaceWidth;
int displayedSurfaceHeight;
if (layoutHasLargerWidth) {
displayedSurfaceWidth = (int) (requiredRatio * layoutHeight);
displayedSurfaceHeight = layoutHeight;
} else {
displayedSurfaceWidth = layoutWidth;
displayedSurfaceHeight = (int) (layoutWidth / requiredRatio);
}
if (layoutHasLargerWidth) {
if (previewHasLargerWidth) {
cropLayer.layout(displayedSurfaceWidth + 1, 0, layoutWidth, displayedSurfaceHeight);
} else {
// no need for crop layer
cropLayer.layout(0, 0, 0, 0);
}
} else {
if (previewHasLargerWidth) {
// no need for crop layer
cropLayer.layout(0, 0, 0, 0);
} else {
cropLayer.layout(0, displayedSurfaceHeight + 1, layoutWidth, layoutHeight);
}
}
if (previewHasLargerWidth) {
int surfaceWidth = (int) (previewRatio * displayedSurfaceHeight);
int surfaceHeight = displayedSurfaceHeight;
int leftOffset = (surfaceWidth - displayedSurfaceWidth) / 2;
int surfaceLeft = -leftOffset;
int surfaceRight = surfaceLeft + surfaceWidth;
surfaceView.layout(surfaceLeft, 0, surfaceRight, surfaceHeight);
graphicOverlay.layout(surfaceLeft, 0, surfaceRight, surfaceHeight);
} else {
int surfaceWidth = displayedSurfaceWidth;
int surfaceHeight = (int) (displayedSurfaceWidth / previewRatio);
int topOffset = (surfaceHeight - displayedSurfaceHeight) / 2;
int surfaceTop = -topOffset;
int surfaceBottom = surfaceTop + surfaceHeight;
surfaceView.layout(0, surfaceTop, surfaceWidth, surfaceBottom);
graphicOverlay.layout(0, surfaceTop, surfaceWidth, surfaceBottom);
}
startIfReady();
}
private boolean isPortraitMode() {
int orientation = context.getResources().getConfiguration().orientation;
return orientation == Configuration.ORIENTATION_PORTRAIT;
}
}
| 8,943 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/graphic/OreoNoseRingGraphic.java
|
package com.squareup.photobooth.snap.graphic;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.RectF;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.Landmark;
import com.squareup.photobooth.R;
import com.squareup.photobooth.snap.Scaler;
public class OreoNoseRingGraphic implements FaceGraphic {
private final Bitmap oreoBitmap;
private final RectF noseRect;
private PointF nose;
private Face face;
public OreoNoseRingGraphic(Context context) {
oreoBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.orenose);
noseRect = new RectF();
}
@Override public void updateFace(Face face) {
for (Landmark landmark : face.getLandmarks()) {
switch (landmark.getType()) {
case Landmark.NOSE_BASE:
nose = landmark.getPosition();
break;
}
}
this.face = face;
}
@Override public void draw(Canvas canvas, Scaler translator) {
if (face == null || nose == null) {
return;
}
float faceWidth = translator.scaleHorizontal(face.getWidth());
float ringSize = faceWidth / 7f;
float centerX = translator.translateX(nose.x);
float centerY = translator.translateY(nose.y);
float halfRingSize = ringSize / 2;
noseRect.left = centerX - halfRingSize;
noseRect.top = centerY - halfRingSize;
noseRect.right = noseRect.left + ringSize;
noseRect.bottom = noseRect.top + ringSize;
canvas.drawBitmap(oreoBitmap, null, noseRect, null);
}
@Override public void forgetFace() {
nose = null;
face = null;
}
}
| 8,944 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/graphic/PieGraphic.java
|
package com.squareup.photobooth.snap.graphic;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.DisplayMetrics;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.Landmark;
import com.squareup.photobooth.R;
import com.squareup.photobooth.snap.Scaler;
public class PieGraphic implements FaceGraphic {
private final Bitmap bitmap;
private final Bitmap reversedBitmap;
private final RectF eyeRect;
private final float ratio;
private PointF leftEye;
private PointF rightEye;
private Face face;
public PieGraphic(Context context) {
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.pie);
ratio = (bitmap.getHeight() * 1f) / bitmap.getWidth();
eyeRect = new RectF();
Matrix m = new Matrix();
m.preScale(-1, 1);
reversedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, false);
}
@Override public void updateFace(Face face) {
for (Landmark landmark : face.getLandmarks()) {
switch (landmark.getType()) {
case Landmark.LEFT_EYE:
leftEye = landmark.getPosition();
break;
case Landmark.RIGHT_EYE:
rightEye = landmark.getPosition();
break;
}
}
this.face = face;
}
@Override public void draw(Canvas canvas, Scaler translator) {
if (face == null) {
return;
}
float faceWidth = translator.scaleHorizontal(face.getWidth());
float eyeSize = faceWidth / 5f;
drawEye(canvas, translator, leftEye, eyeSize);
drawEye(canvas, translator, rightEye, eyeSize);
}
@Override public void forgetFace() {
leftEye = null;
rightEye = null;
face = null;
}
private void drawEye(Canvas canvas, Scaler scaler, PointF eye, float eyeSize) {
float centerX = scaler.translateX(eye.x);
float centerY = scaler.translateY(eye.y);
float halfEyeSize = eyeSize / 2;
float eyeHeight = eyeSize * ratio;
eyeRect.left = centerX - halfEyeSize;
eyeRect.top = centerY - halfEyeSize;
eyeRect.right = eyeRect.left + eyeSize;
eyeRect.bottom = eyeRect.top + eyeHeight;
if (scaler.isFrontFacing()) {
canvas.drawBitmap(reversedBitmap, null, eyeRect, null);
} else {
canvas.drawBitmap(bitmap, null, eyeRect, null);
}
}
}
| 8,945 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/graphic/FaceGraphic.java
|
package com.squareup.photobooth.snap.graphic;
import android.graphics.Canvas;
import com.google.android.gms.vision.face.Face;
import com.squareup.photobooth.snap.Scaler;
public interface FaceGraphic {
void draw(Canvas canvas, Scaler translator);
void updateFace(Face face);
void forgetFace();
}
| 8,946 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/graphic/GraphicFactory.java
|
package com.squareup.photobooth.snap.graphic;
import android.content.Context;
import android.support.annotation.DrawableRes;
import com.squareup.photobooth.R;
public enum GraphicFactory {
PIE(R.drawable.pie) {
@Override public FaceGraphic create(Context context) {
return new PieGraphic(context);
}
},
ORENOSE(R.drawable.orenose) {
@Override public FaceGraphic create(Context context) {
return new OreoNoseRingGraphic(context);
}
},
LEAK_CANARY(R.drawable.leakcanary) {
@Override public FaceGraphic create(Context context) {
return new LeakCanaryGraphic(context);
}
},
JAKE(R.drawable.jake) {
@Override public FaceGraphic create(Context context) {
return new JakeGraphic(context);
}
},
OREO(R.drawable.oreo) {
@Override public FaceGraphic create(Context context) {
return new OreoGraphic(context);
}
},
ROBOT(R.drawable.robot) {
@Override public FaceGraphic create(Context context) {
return new RobotGraphic(context);
}
},
//
;
public final @DrawableRes int drawableResId;
GraphicFactory(@DrawableRes int drawableResId) {
this.drawableResId = drawableResId;
}
public abstract FaceGraphic create(Context context);
}
| 8,947 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/graphic/RobotGraphic.java
|
package com.squareup.photobooth.snap.graphic;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.Landmark;
import com.squareup.photobooth.R;
import com.squareup.photobooth.snap.Scaler;
public class RobotGraphic implements FaceGraphic {
private final Bitmap oreoBitmap;
private final Matrix matrix;
private PointF leftEye;
private PointF rightEye;
private Face face;
public RobotGraphic(Context context) {
oreoBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.robot);
matrix = new Matrix();
}
@Override public void updateFace(Face face) {
for (Landmark landmark : face.getLandmarks()) {
switch (landmark.getType()) {
case Landmark.LEFT_EYE:
leftEye = landmark.getPosition();
break;
case Landmark.RIGHT_EYE:
rightEye = landmark.getPosition();
break;
}
}
this.face = face;
}
@Override public void draw(Canvas canvas, Scaler translator) {
if (leftEye == null || rightEye == null) {
return;
}
PointF facePosition = face.getPosition();
float faceX = translator.translateX(facePosition.x);
float faceY = translator.translateY(facePosition.y);
float faceWidth = translator.scaleHorizontal(face.getWidth());
float centerY = translator.translateY((leftEye.y + rightEye.y) / 2);
float robotHeadHeightRatio = 0.813f;
float robotToHumanWidthRatio = 0.8f;
float robotWidth = faceWidth * robotToHumanWidthRatio;
float robotHeight = (centerY - faceY) / robotHeadHeightRatio;
float robotX = faceX + ((faceWidth - robotWidth) / 2);
if (translator.isFrontFacing()) {
robotX -= faceWidth;
}
float robotY = faceY;
matrix.reset();
float scaleX = (robotWidth * 1f) / oreoBitmap.getWidth();
float scaleY = (robotHeight * 1f) / oreoBitmap.getHeight();
matrix.postScale(scaleX, scaleY);
matrix.postTranslate(robotX, robotY);
float angle = face.getEulerZ();
if (!translator.isFrontFacing()) {
angle = -angle;
}
matrix.postRotate(angle, robotX + robotWidth / 2, robotY + robotHeight / 2);
canvas.drawBitmap(oreoBitmap, matrix, null);
}
@Override public void forgetFace() {
leftEye = null;
rightEye = null;
face = null;
}
}
| 8,948 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/graphic/JakeGraphic.java
|
package com.squareup.photobooth.snap.graphic;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PointF;
import com.google.android.gms.vision.face.Face;
import com.squareup.photobooth.R;
import com.squareup.photobooth.snap.Scaler;
public class JakeGraphic implements FaceGraphic {
private final Bitmap bitmap;
private final Matrix matrix;
private Face face;
public JakeGraphic(Context context) {
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.jake);
matrix = new Matrix();
}
@Override public void updateFace(Face face) {
this.face = face;
}
@Override public void draw(Canvas canvas, Scaler translator) {
if (face == null) {
return;
}
PointF facePosition = face.getPosition();
float faceX = translator.translateX(facePosition.x);
float faceY = translator.translateY(facePosition.y);
float faceWidth = translator.scaleHorizontal(face.getWidth());
float faceHeight = translator.scaleHorizontal(face.getHeight());
float jakeWidth = faceWidth;
float jakeHeight = faceHeight;
float jakeX = faceX + ((faceWidth - jakeHeight) / 2);
if (translator.isFrontFacing()) {
jakeX -= faceWidth;
}
float jakeY = faceY;
matrix.reset();
float scaleX = (jakeWidth * 1.2f) / bitmap.getWidth();
float scaleY = (jakeHeight * 1.2f) / bitmap.getHeight();
matrix.postScale(scaleX, scaleY);
matrix.postTranslate(jakeX, jakeY);
float angle = face.getEulerZ();
if (!translator.isFrontFacing()) {
angle = -angle;
}
matrix.postRotate(angle, jakeX + jakeHeight / 2, jakeY + jakeHeight / 2);
canvas.drawBitmap(bitmap, matrix, null);
}
@Override public void forgetFace() {
face = null;
}
}
| 8,949 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/graphic/OreoGraphic.java
|
package com.squareup.photobooth.snap.graphic;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.RectF;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.Landmark;
import com.squareup.photobooth.R;
import com.squareup.photobooth.snap.Scaler;
public class OreoGraphic implements FaceGraphic {
private final Bitmap oreoBitmap;
private final RectF eyeRect;
private PointF leftEye;
private PointF rightEye;
private Face face;
public OreoGraphic(Context context) {
oreoBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.oreo);
eyeRect = new RectF();
}
@Override public void updateFace(Face face) {
for (Landmark landmark : face.getLandmarks()) {
switch (landmark.getType()) {
case Landmark.LEFT_EYE:
leftEye = landmark.getPosition();
break;
case Landmark.RIGHT_EYE:
rightEye = landmark.getPosition();
break;
}
}
this.face = face;
}
@Override public void draw(Canvas canvas, Scaler scaler) {
if (face == null) {
return;
}
float faceWidth = scaler.scaleHorizontal(face.getWidth());
float eyeSize = faceWidth / 5f;
drawEye(canvas, scaler, leftEye, eyeSize);
drawEye(canvas, scaler, rightEye, eyeSize);
}
@Override public void forgetFace() {
leftEye = null;
rightEye = null;
face = null;
}
private void drawEye(Canvas canvas, Scaler translator, PointF eye, float eyeSize) {
if (eye == null) {
return;
}
float centerX = translator.translateX(eye.x);
float centerY = translator.translateY(eye.y);
float halfEyeSize = eyeSize / 2;
eyeRect.left = centerX - halfEyeSize;
eyeRect.top = centerY - halfEyeSize;
eyeRect.right = eyeRect.left + eyeSize;
eyeRect.bottom = eyeRect.top + eyeSize;
canvas.drawBitmap(oreoBitmap, null, eyeRect, null);
}
}
| 8,950 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/snap/graphic/LeakCanaryGraphic.java
|
package com.squareup.photobooth.snap.graphic;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.RectF;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.Landmark;
import com.squareup.photobooth.R;
import com.squareup.photobooth.snap.Scaler;
public class LeakCanaryGraphic implements FaceGraphic {
private final Bitmap bitmap;
private final RectF rect;
private PointF leftEye;
private PointF rightEye;
private Face face;
public LeakCanaryGraphic(Context context) {
bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.leakcanary);
rect = new RectF();
}
@Override public void updateFace(Face face) {
for (Landmark landmark : face.getLandmarks()) {
switch (landmark.getType()) {
case Landmark.LEFT_EYE:
leftEye = landmark.getPosition();
break;
case Landmark.RIGHT_EYE:
rightEye = landmark.getPosition();
break;
}
}
this.face = face;
}
@Override public void draw(Canvas canvas, Scaler translator) {
if (leftEye == null || rightEye == null) {
return;
}
float eyeAverageY = translator.translateY((leftEye.y + rightEye.y) / 2);
PointF facePosition = face.getPosition();
// top left, reversed with front camera so top right.
float faceX = translator.translateX(facePosition.x);
float faceY = translator.translateY(facePosition.y);
float faceWidth = translator.scaleHorizontal(face.getWidth());
float shieldWidth = faceWidth * 0.60f;
float shieldHeight = (shieldWidth * bitmap.getHeight()) / bitmap.getWidth();
float shieldX;
if (translator.isFrontFacing()) {
shieldX = (faceX - faceWidth / 2) - shieldWidth / 2;
} else {
shieldX = (faceX + faceWidth / 2) - shieldWidth / 2;
}
// tip of shield is on forefront
float shieldY = faceY + ((eyeAverageY - faceY) * 0.65f) - shieldHeight;
rect.left = shieldX;
rect.top = shieldY;
rect.right = shieldX + shieldWidth;
rect.bottom = shieldY + shieldHeight;
canvas.drawBitmap(bitmap, null, rect, null);
}
@Override public void forgetFace() {
leftEye = null;
rightEye = null;
face = null;
}
}
| 8,951 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/job/JobService.java
|
package com.squareup.photobooth.job;
import com.birbit.android.jobqueue.JobManager;
import com.birbit.android.jobqueue.scheduling.FrameworkJobSchedulerService;
import com.squareup.photobooth.App;
public class JobService extends FrameworkJobSchedulerService {
@Override protected JobManager getJobManager() {
return App.from(this).jobManager();
}
}
| 8,952 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/job/InjectedJob.java
|
package com.squareup.photobooth.job;
import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.Params;
import com.squareup.photobooth.App;
public abstract class InjectedJob extends Job {
protected InjectedJob(Params params) {
super(params);
}
public abstract void inject(App app);
}
| 8,953 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/job/TimberJobLogger.java
|
package com.squareup.photobooth.job;
import com.birbit.android.jobqueue.log.CustomLogger;
import com.squareup.photobooth.BuildConfig;
import timber.log.Timber;
public class TimberJobLogger implements CustomLogger {
@Override public boolean isDebugEnabled() {
return BuildConfig.DEBUG;
}
@Override public void d(String text, Object... args) {
Timber.d(text, args);
}
@Override public void e(Throwable t, String text, Object... args) {
Timber.d(t, text, args);
}
@Override public void e(String text, Object... args) {
Timber.d(text, args);
}
@Override public void v(String text, Object... args) {
Timber.d(text, args);
}
}
| 8,954 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/job/GcmJobService.java
|
package com.squareup.photobooth.job;
import com.birbit.android.jobqueue.JobManager;
import com.birbit.android.jobqueue.scheduling.GcmJobSchedulerService;
import com.squareup.photobooth.App;
public class GcmJobService extends GcmJobSchedulerService {
@Override protected JobManager getJobManager() {
return App.from(this).jobManager();
}
}
| 8,955 |
0 |
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth
|
Create_ds/squickpic/app/src/main/java/com/squareup/photobooth/job/JobManagerInjector.java
|
package com.squareup.photobooth.job;
import com.birbit.android.jobqueue.Job;
import com.birbit.android.jobqueue.di.DependencyInjector;
import com.squareup.photobooth.App;
public class JobManagerInjector implements DependencyInjector {
private final App app;
public JobManagerInjector(App app) {
this.app = app;
}
@Override public void inject(Job job) {
if (job instanceof InjectedJob) {
((InjectedJob) job).inject(app);
}
}
}
| 8,956 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-registry/src/main/java/org/apache/brooklyn/ui/modularity/module
|
Create_ds/brooklyn-ui/modularity-server/module-registry/src/main/java/org/apache/brooklyn/ui/modularity/module/registry/RestUiModuleRegistry.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.registry;
import java.util.Collection;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.brooklyn.ui.modularity.module.api.UiModule;
import org.apache.brooklyn.ui.modularity.module.api.UiModuleRegistry;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
@Path("/")
public class RestUiModuleRegistry {
private UiModuleRegistry uiModuleRegistry;
private static final Function<UiModule, String> GET_NAME_FUNCTION = new Function<UiModule, String>() {
@Override
public String apply(UiModule input) {
if (input != null) {
return input.getName();
}
return "";
}
};
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
public Collection<UiModule> getRegisteredWebComponents() {
return Ordering.natural()
.onResultOf(GET_NAME_FUNCTION)
.immutableSortedCopy(
// turn it from a proxy to a serializable bean
Iterables.transform(uiModuleRegistry.getRegisteredModules(), x -> UiModule.Utils.copyUiModule(x)));
}
public void setUiModuleRegistry(final UiModuleRegistry uiModuleRegistry) {
this.uiModuleRegistry = uiModuleRegistry;
}
}
| 8,957 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-registry/src/main/java/org/apache/brooklyn/ui/modularity/module
|
Create_ds/brooklyn-ui/modularity-server/module-registry/src/main/java/org/apache/brooklyn/ui/modularity/module/registry/UiModuleRegistryImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.registry;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.brooklyn.ui.modularity.module.api.UiModule;
import org.apache.brooklyn.ui.modularity.module.api.UiModuleRegistry;
public class UiModuleRegistryImpl implements UiModuleRegistry {
private static final Logger LOG = LoggerFactory.getLogger(UiModuleRegistryImpl.class);
// keyed on UUID (doesn't really matter what)
// also note the context paths will normally be unique, as even if diff versions of same bundle are installed,
// only one will have the servlet context initialized and thus only one will normally be available here;
// however due to asynchronous callback of unregister the register(v2) and unregister(v1) might occur in either order,
// so we mustn't key on the slug or the context path here!
private final ConcurrentHashMap<String, UiModule> registry = new ConcurrentHashMap<>();
public void register(final UiModule uiModule) {
if (uiModule.getId()==null) {
LOG.error("Skipping invalid Brooklyn UI module "+uiModule, new Throwable("source of error"));
return;
}
LOG.info("Registering new Brooklyn web component [{}] [{}]", uiModule.getId(), uiModule.getName());
registry.put(uiModule.getId(), uiModule);
}
public void unregister(final UiModule uiModule) {
if (uiModule != null) {
LOG.info("Unregistered new Brooklyn web component [{}] [{}]", uiModule.getId(), uiModule.getName());
registry.remove(uiModule.getId());
}
}
public Collection<UiModule> getRegisteredModules() {
return registry.values();
}
}
| 8,958 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-registry/src/main/java/org/apache/brooklyn/ui/modularity/module/registry
|
Create_ds/brooklyn-ui/modularity-server/module-registry/src/main/java/org/apache/brooklyn/ui/modularity/module/registry/internal/RedirectServlet.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.registry.internal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RedirectServlet extends HttpServlet {
private static final Logger LOG = LoggerFactory.getLogger(RedirectServlet.class);
private final String redirect;
public RedirectServlet(final String redirect) {
this.redirect = redirect;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doRedirect(req, resp);
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doRedirect(req, resp);
}
@Override
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doRedirect(req, resp);
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doRedirect(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doRedirect(req, resp);
}
@Override
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doRedirect(req, resp);
}
@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doRedirect(req, resp);
}
private void doRedirect(HttpServletRequest req, HttpServletResponse resp) throws IOException {
LOG.debug("Redirecting request from [{}] to [{}{}]", req.getRequestURI(), redirect, req.getRequestURI());
resp.sendRedirect(redirect + req.getRequestURI());
}
}
| 8,959 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-registry/src/main/java/org/apache/brooklyn/ui/modularity/module/registry
|
Create_ds/brooklyn-ui/modularity-server/module-registry/src/main/java/org/apache/brooklyn/ui/modularity/module/registry/command/ListUiModulesCommand.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.registry.command;
import org.apache.brooklyn.ui.modularity.module.api.UiModule;
import org.apache.brooklyn.ui.modularity.module.api.UiModuleRegistry;
import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.apache.karaf.shell.support.table.ShellTable;
@Command(scope = "brooklyn", name = "list-ui-modules", description = "List registered Brooklyn UI Modules")
@Service
public class ListUiModulesCommand implements Action {
@Reference
private UiModuleRegistry registry;
public Object execute() throws Exception {
ShellTable table = new ShellTable();
table.column("ID");
table.column("NAME");
table.column("TYPES");
table.column("PATH");
for (final UiModule component : registry.getRegisteredModules()) {
table.addRow().addContent(
component.getId(), component.getName(), component.getTypes(), component.getPath());
}
table.print(System.out, true);
return null;
}
}
| 8,960 |
0 |
Create_ds/brooklyn-ui/modularity-server/metadata-registry/src/main/java/org/apache/brooklyn/ui/modularity/metadata
|
Create_ds/brooklyn-ui/modularity-server/metadata-registry/src/main/java/org/apache/brooklyn/ui/modularity/metadata/registry/RestUiMetadataRegistry.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.metadata.registry;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.Map;
@Path("/")
public class RestUiMetadataRegistry {
private static final Logger logger = LoggerFactory.getLogger(RestUiMetadataRegistry.class);
private UiMetadataRegistry metadataRegistry;
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
public Map get(
@QueryParam("id") final String id, @QueryParam("type") final String type) {
if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(type)) {
return metadataRegistry.getByTypeAndId(type, id);
} else if (StringUtils.isNotEmpty(id)) {
return metadataRegistry.getById(id);
} else if (StringUtils.isNotEmpty(type)) {
return metadataRegistry.getByType(type);
}
return metadataRegistry.getAll();
}
public void setMetadataRegistry(UiMetadataRegistry metadataRegistry) {
this.metadataRegistry = metadataRegistry;
}
}
| 8,961 |
0 |
Create_ds/brooklyn-ui/modularity-server/metadata-registry/src/main/java/org/apache/brooklyn/ui/modularity/metadata
|
Create_ds/brooklyn-ui/modularity-server/metadata-registry/src/main/java/org/apache/brooklyn/ui/modularity/metadata/registry/UiMetadataRegistry.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.metadata.registry;
import java.util.Map;
public interface UiMetadataRegistry {
String METADATA_TYPE = "type";
String METADATA_ID = "id";
String METADATA_TYPE_DEFAULT = "generic";
void registerMetadata(final String type, final String id, final Map<String, String> metadata);
void modifyMetadata(final String type, final String id, final Map<String, String> metadata);
void unregisterMetadata(final String type, final String id);
Map<String,Map<String,String>> getById(final String id);
Map<String, Map<String, String>> getByType(final String type);
Map<String, String> getByTypeAndId(final String type, final String id);
Map<String, Map<String, Map<String, String>>> getAll();
}
| 8,962 |
0 |
Create_ds/brooklyn-ui/modularity-server/metadata-registry/src/main/java/org/apache/brooklyn/ui/modularity/metadata/registry
|
Create_ds/brooklyn-ui/modularity-server/metadata-registry/src/main/java/org/apache/brooklyn/ui/modularity/metadata/registry/impl/UiMetadataRegistryImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.metadata.registry.impl;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.apache.brooklyn.ui.modularity.metadata.registry.UiMetadataRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class UiMetadataRegistryImpl implements UiMetadataRegistry {
private static final Logger logger = LoggerFactory.getLogger(UiMetadataRegistryImpl.class);
final Table<String, String, Map<String, String>> metadataTable = HashBasedTable.create();
@Override
public void registerMetadata(final String type, final String id, final Map<String, String> metadata) {
modifyMetadata(type, id, metadata);
}
@Override
public void modifyMetadata(final String type, final String id, final Map<String, String> metadata) {
metadataTable.put(type, id, metadata);
}
@Override
public void unregisterMetadata(final String type, final String id) {
metadataTable.remove(type, id);
}
@Override
public Map<String, Map<String, String>> getById(final String id) {
return metadataTable.column(id);
}
@Override
public Map<String, Map<String, String>> getByType(final String type) {
return metadataTable.row(type);
}
@Override
public Map<String, String> getByTypeAndId(final String type, final String id) {
return metadataTable.get(type, id);
}
@Override
public Map<String, Map<String, Map<String, String>>> getAll() {
return metadataTable.rowMap();
}
}
| 8,963 |
0 |
Create_ds/brooklyn-ui/modularity-server/metadata-registry/src/main/java/org/apache/brooklyn/ui/modularity/metadata/registry
|
Create_ds/brooklyn-ui/modularity-server/metadata-registry/src/main/java/org/apache/brooklyn/ui/modularity/metadata/registry/impl/UiMetadataConfigListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.metadata.registry.impl;
import com.google.common.collect.Maps;
import org.apache.brooklyn.ui.modularity.metadata.registry.UiMetadataRegistry;
import org.osgi.service.component.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
@Component(
//name = "Brooklyn UI Metadata", // name as class is common and the default
configurationPid = UiMetadataConfigListener.PID, configurationPolicy = ConfigurationPolicy.OPTIONAL, immediate = true,
property = {UiMetadataRegistry.METADATA_TYPE + ":String=" + UiMetadataRegistry.METADATA_TYPE_DEFAULT}
)
public class UiMetadataConfigListener {
static final String PID = "org.apache.brooklyn.ui.modularity.metadata";
private static final Logger logger = LoggerFactory.getLogger(PID);
private static final List<String> EXCLUDE = Arrays.asList(
"felix.fileinstall.filename", "service.factoryPid", "component.name", "component.id"
);
@Reference
private UiMetadataRegistry metadataRegistry;
protected String getId(final Map<String, String> properties) {
return properties.containsKey(UiMetadataRegistry.METADATA_ID) ?
properties.get(UiMetadataRegistry.METADATA_ID) : properties.get("service.pid");
}
@Activate
public void activate(final Map<String, String> properties) {
logger.debug("Activate "+this+": "+properties);
if (getId(properties)==null) {
logger.debug("Skipping recording of metadata config for irrelevant activation record: "+properties);
} else {
modified(properties);
}
}
@Modified
public void modified(final Map<String, String> properties) {
logger.debug("Modified "+this+": "+properties);
String id = getId(properties);
if (id==null) {
logger.warn("Skipping update of UI metadata because ID is not specified: "+properties);
return;
}
metadataRegistry.modifyMetadata(
properties.containsKey(UiMetadataRegistry.METADATA_TYPE) ?
properties.get(UiMetadataRegistry.METADATA_TYPE) : UiMetadataRegistry.METADATA_TYPE_DEFAULT,
id,
Maps.filterKeys(properties, not(in(EXCLUDE)))
);
}
@Deactivate
public void deactivate(final Map<String, String> properties) {
logger.debug("Deactivate "+this+": "+properties);
String id = getId(properties);
if (id==null) {
logger.debug("Skipping deactivation of UI metadata because ID is not specified: "+properties);
return;
}
metadataRegistry.unregisterMetadata(
properties.containsKey(UiMetadataRegistry.METADATA_TYPE) ?
properties.get(UiMetadataRegistry.METADATA_TYPE) : UiMetadataRegistry.METADATA_TYPE_DEFAULT,
id);
}
}
| 8,964 |
0 |
Create_ds/brooklyn-ui/modularity-server/proxy/src/test/java/org/apache/brooklyn/ui
|
Create_ds/brooklyn-ui/modularity-server/proxy/src/test/java/org/apache/brooklyn/ui/proxy/UIProxyTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.proxy;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.UUID;
import static org.mockito.Mockito.*;
import static org.mockito.BDDMockito.*;
import static org.assertj.core.api.Assertions.*;
/**
* Created by mark on 22/03/2016.
*/
public class UIProxyTest {
private static final Logger LOG = LoggerFactory.getLogger(UIProxyTest.class);
private UiProxy uiProxy;
private HttpServletRequest mockReq;
@BeforeTest
public void setup() {
uiProxy = new UiProxy();
mockReq = mock(HttpServletRequest.class);
}
@Test(dataProvider = "success")
public void happyPath(String alias, String target, String reqURI, String reqQueryString) {
given(mockReq.getRequestURI()).willReturn(alias + reqURI);
given(mockReq.getQueryString()).willReturn(reqQueryString);
uiProxy.activate(ImmutableMap.of("alias", alias, "target", target));
final String result = uiProxy.rewriteTarget(mockReq);
LOG.info("Rewritten URI [{}]", result);
assertThat(result).isNotEmpty();
assertThat(result).startsWith(target);
if (StringUtils.isNotEmpty(reqQueryString)) {
assertThat(result).endsWith("?" + reqQueryString);
} else {
assertThat(result).endsWith(reqURI);
}
}
@Test(expectedExceptions = MissingResourceException.class, expectedExceptionsMessageRegExp = "The field \\[.*\\] is marked as required")
public void missingRequiredField() {
uiProxy.activate(ImmutableMap.of("target", UUID.randomUUID().toString()));
}
@DataProvider(name = "success")
public Object[][] dataProvider() {
return new Object[][]{
{"/seg1", "http://example.com", "/some/path", null},
{"/seg1", "http://example.com", "/some/path", "key1=val1&key2=true"},
{"/seg1/", "http://example.com/", "some/path", "key1=val1&key2=true"},
{"/test", "http://example.com/path", "/test/test/test", null},
{"/seg1/seg2/", "http://example.com/test", "", null}
};
}
}
| 8,965 |
0 |
Create_ds/brooklyn-ui/modularity-server/proxy/src/main/java/org/apache/brooklyn/ui
|
Create_ds/brooklyn-ui/modularity-server/proxy/src/main/java/org/apache/brooklyn/ui/proxy/UiProxyHttpContext.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.proxy;
import com.google.common.base.Optional;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.http.HttpHeader;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.http.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
@Component(
name = "UiProxyHttpContext",
configurationPid = "org.apache.brooklyn.ui.proxy.security",
configurationPolicy = ConfigurationPolicy.OPTIONAL,
immediate = true,
service = HttpContext.class, property = {"httpContext.id:String=proxy-context", "ui.proxy.security.realm:String=karaf"}
)
public class UiProxyHttpContext implements HttpContext {
private static final Logger LOG = LoggerFactory.getLogger(UiProxyHttpContext.class);
private String realm = "webconsole";
@Override
public boolean handleSecurity(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
final HttpSession session = request.getSession(true);
LOG.info("Handling security for session [{}] in realm [{}]", session.getId(), realm);
final Optional<String[]> credentials = readCredentials(request.getHeader(HttpHeader.AUTHORIZATION.name()));
if (credentials.isPresent()) {
try {
final LoginContext login = new LoginContext(realm, new UsernamePasswordCallbackHandler(credentials.get()[0], credentials.get()[1]));
login.login();
request.setAttribute(HttpContext.AUTHENTICATION_TYPE, "Basic");
request.setAttribute(HttpContext.REMOTE_USER, credentials.get()[0]);
final Subject subject = login.getSubject();
subject.setReadOnly();
session.setAttribute("javax.security.auth.subject", subject);
return true;
} catch (LoginException e) {
LOG.warn("Login attempt failed for user [{}] on session [{}]", credentials.get()[0], session.getId());
}
}
response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Must be authenticated to access this resource");
return false;
}
private Optional<String[]> readCredentials(String header) {
if (StringUtils.startsWith(header, "Basic")) {
final String credentials = new String(Base64.decodeBase64(StringUtils.substringAfter(header, "Basic").trim()));
return Optional.of(credentials.split(":", 2));
}
return Optional.absent();
}
@Override
public URL getResource(String name) {
return null;
}
@Override
public String getMimeType(String name) {
return null;
}
@Activate
public void activate(final Map<String, String> properties) {
modified(properties);
}
public void modified(final Map<String, String> properties) {
final String realmFromProperties = properties.get("ui.proxy.security.realm");
if (StringUtils.isNotEmpty(realmFromProperties)) {
realm = realmFromProperties;
}
}
private class UsernamePasswordCallbackHandler implements CallbackHandler {
private final String username;
private final String password;
public UsernamePasswordCallbackHandler(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (final Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName(username);
} else if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword(password.toCharArray());
}
}
}
}
}
| 8,966 |
0 |
Create_ds/brooklyn-ui/modularity-server/proxy/src/main/java/org/apache/brooklyn/ui
|
Create_ds/brooklyn-ui/modularity-server/proxy/src/main/java/org/apache/brooklyn/ui/proxy/UiProxy.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.proxy;
import com.google.common.base.Optional;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.proxy.ProxyServlet;
import org.osgi.service.component.annotations.*;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.concurrent.TimeUnit;
@Component(
name = "UiProxy",
configurationPid = "org.apache.brooklyn.ui.proxy",
configurationPolicy = ConfigurationPolicy.REQUIRE,
service = Servlet.class,
property = {"httpContext.id:String=proxy-context"}
)
public class UiProxy extends ProxyServlet {
private static final Logger LOG = LoggerFactory.getLogger(UiProxy.class);
private static final String SERVICE_PID = "service.pid";
private static final String ALIAS = "alias";
private static final String TARGET = "target";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final String METRICS_TOPIC = "decanter/collect/brooklyn-ui/ui-proxy";
@Reference
private EventAdmin eventAdmin;
private String alias;
private String target;
private Boolean useAuthentication = Boolean.FALSE;
private String authHeader;
private String proxyId;
@Override
protected void service(final HttpServletRequest request,
final HttpServletResponse response) throws ServletException, IOException {
final Stopwatch sw = Stopwatch.createStarted();
super.service(request, response);
sw.stop();
eventAdmin.postEvent(new Event(METRICS_TOPIC, ImmutableMap.of(
"id", proxyId,
"type", "ui-proxy::remote-latency",
"alias", alias,
"target", target,
"remote-latency", sw.toString()
)));
}
@Override
protected String rewriteTarget(final HttpServletRequest clientRequest) {
final StringBuffer sb = new StringBuffer(target);
sb.append(StringUtils.removeStart(clientRequest.getRequestURI(), alias));
if (StringUtils.isNotEmpty(clientRequest.getQueryString())) {
sb.append("?").append(clientRequest.getQueryString());
}
return sb.toString();
}
@Override
protected void addProxyHeaders(HttpServletRequest clientRequest, Request proxyRequest) {
super.addProxyHeaders(clientRequest, proxyRequest);
if (useAuthentication) {
proxyRequest.getHeaders().remove(HttpHeader.AUTHORIZATION);
proxyRequest.header(HttpHeader.AUTHORIZATION, authHeader);
}
}
@Override
protected void onProxyResponseSuccess(final HttpServletRequest clientRequest,
final HttpServletResponse proxyResponse, final Response serverResponse) {
super.onProxyResponseSuccess(clientRequest, proxyResponse, serverResponse);
eventAdmin.postEvent(new Event(METRICS_TOPIC, ImmutableMap.of(
"id", proxyId,
"type", "ui-proxy::response",
"alias", alias,
"target", target,
"status", serverResponse.getStatus()
)));
}
@Activate
public void activate(final Map<String, String> properties) {
LOG.info("Creating new proxy instance :: [{}]", properties.get(SERVICE_PID));
modified(properties);
}
@Modified
public void modified(final Map<String, String> properties) {
proxyId = getFromProperties(properties, SERVICE_PID, false, "");
alias = getFromProperties(properties, ALIAS, true, "");
target = getFromProperties(properties, TARGET, true, "");
if (properties.containsKey(USERNAME) && properties.containsKey(PASSWORD)) {
useAuthentication = Boolean.TRUE;
authHeader = generateAuthHeader(properties.get(USERNAME), properties.get(PASSWORD));
} else {
useAuthentication = Boolean.FALSE;
}
LOG.info("Updating proxy [{}] :: Proxy [{}] -> [{}], Authenticated [{}]", proxyId, alias, target, useAuthentication);
}
@Deactivate
public void deactivate() {
LOG.info("Destroying proxy [{}] :: Proxy [{}] -> [{}], Authenticated [{}]", proxyId, alias, target, useAuthentication);
destroy();
}
private String getFromProperties(final Map<String, String> properties, final String key, final Boolean required, final String defaultValue) {
Optional<String> result = Optional.fromNullable(properties.get(key));
if (required && !result.isPresent()) {
throw new MissingResourceException("The field [" + key + "] is marked as required", UiProxy.class.getName(), key);
}
return result.or(defaultValue);
}
private String generateAuthHeader(final String username, final String password) {
return "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes()));
}
private String clean(final String path) {
if (StringUtils.endsWith(path, "/")) {
return path.substring(0, path.length() - 1);
} else {
return path;
}
}
public EventAdmin getEventAdmin() {
return eventAdmin;
}
public void setEventAdmin(EventAdmin eventAdmin) {
this.eventAdmin = eventAdmin;
}
}
| 8,967 |
0 |
Create_ds/brooklyn-ui/modularity-server/external-modules/src/test/java/org/apache/brooklyn/ui/modularity
|
Create_ds/brooklyn-ui/modularity-server/external-modules/src/test/java/org/apache/brooklyn/ui/modularity/enricher/BrooklynExternalUiModuleTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.enricher;
import org.apache.brooklyn.api.location.LocationSpec;
import org.apache.brooklyn.api.mgmt.ManagementContext;
import org.apache.brooklyn.api.sensor.EnricherSpec;
import org.apache.brooklyn.core.test.entity.TestApplication;
import org.apache.brooklyn.location.localhost.LocalhostMachineProvisioningLocation;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.UUID;
public class BrooklynExternalUiModuleTest {
private String testId;
private TestApplication app;
private ManagementContext managementContext;
private LocalhostMachineProvisioningLocation location;
@BeforeTest
public void setup() {
testId = UUID.randomUUID().toString();
app = TestApplication.Factory.newManagedInstanceForTests();
managementContext = app.getManagementContext();
location = managementContext.getLocationManager()
.createLocation(LocationSpec.create(LocalhostMachineProvisioningLocation.class)
.configure("name", testId));
}
@AfterTest
public void tearDown() {
app.stop();
}
@Test
public void testApp() {
EnricherSpec enricherSpec = EnricherSpec.create(BrooklynExternalUiModuleEnricher.class)
.configure(BrooklynExternalUiModuleEnricher.MODULE_ICON, "test-icon")
.configure(BrooklynExternalUiModuleEnricher.MODULE_NAME, "test-name")
.configure(BrooklynExternalUiModuleEnricher.MODULE_SLUG, "test-slug");
app.enrichers().add(enricherSpec);
app.start(Arrays.asList(location));
}
}
| 8,968 |
0 |
Create_ds/brooklyn-ui/modularity-server/external-modules/src/main/java/org/apache/brooklyn/ui
|
Create_ds/brooklyn-ui/modularity-server/external-modules/src/main/java/org/apache/brooklyn/ui/modularity/ExternalUiModule.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity;
import java.util.Arrays;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.brooklyn.ui.modularity.module.api.UiModule;
import org.apache.brooklyn.ui.modularity.module.api.UiModuleAction;
import org.apache.brooklyn.util.collections.MutableList;
import org.apache.brooklyn.util.collections.MutableSet;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Modified;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
@Component(
// name = ExternalUiModule.PID, // omitting the name / using default seems to prevent warning about it being unable to be installed?
configurationPid = ExternalUiModule.PID,
configurationPolicy = ConfigurationPolicy.REQUIRE, // only trigger if there is a corresponding PID config admin, setting up an external ui module?
immediate = true
)
public class ExternalUiModule implements UiModule {
static final String PID = "org.apache.brooklyn.ui.external.module";
private static final Logger LOG = LoggerFactory.getLogger(PID);
private static final Dictionary<String, ?> EMPTY_DICTIONARY = new Hashtable<>();
private final String MODULE_TYPE = "external-ui-module";
private final String KEY_ID = "service.pid";
private final String KEY_NAME = "name";
private final String KEY_URL = "url";
private final String KEY_ICON = "icon";
private final String KEY_TYPES = "types";
private final String[] REQUIRED_KEYS = new String[] {KEY_ID, KEY_NAME, KEY_URL, KEY_ICON};
private final String KEY_SUPERSEDES = "supersedes";
private final String KEY_STOP_EXISTING = "stopExisting";
private String id;
private String name;
private String icon;
private String url;
private Set<String> types;
private Set<String> supersedes;
private boolean stopExisting;
@Activate
public void activate(final Map<String, String> properties) {
LOG.debug("Activating module "+this+": "+properties);
if (!properties.containsKey(KEY_URL) && properties.containsKey("component.id")) {
// activation properties aren't usually for a module; do this check to suppress warning
LOG.debug("Not setting module properties for activation properties "+properties);
} else {
this.setModuleProperties(properties);
}
}
@Modified
public void modified(final Map<String, String> properties) {
LOG.debug("Modified module "+this+": "+properties);
this.setModuleProperties(properties);
}
private void setModuleProperties(Map<String, String> properties) {
List<String> issues = MutableList.of();
// Check if the required keys are available
for (String requiredKey : REQUIRED_KEYS) {
if (!properties.containsKey(requiredKey)) {
issues.add("Key [" + requiredKey + "] is required");
}
}
if (issues.size() > 0) {
LOG.error("Invalid UI module (ignoring) [" + properties.get(KEY_ID) + "] ... " + issues.toString()+"; properties: "+properties, new Throwable("source of error"));
return;
}
this.id = properties.get(KEY_ID);
this.name = properties.get(KEY_NAME);
this.icon = properties.get(KEY_ICON);
this.url = properties.get(KEY_URL);
this.types = MutableSet.of(MODULE_TYPE);
final String userTypes = properties.get(KEY_TYPES);
if (userTypes != null) {
this.types.addAll(Arrays.asList(userTypes.split(",")));
}
this.supersedes = MutableSet.of(MODULE_TYPE);
final String userSupersedes = properties.get(KEY_SUPERSEDES);
if (userSupersedes != null) {
this.supersedes.addAll(Arrays.asList(userSupersedes.split(",")));
}
this.stopExisting = properties.get(KEY_STOP_EXISTING)!=null ? Boolean.parseBoolean(properties.get(KEY_STOP_EXISTING)) : true;
}
@Override
public String getId() {
return this.id;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getSlug() {
return this.id;
}
@Override
public String getDescription() {
return null; // not supported here; could be but isn't needed
}
@Override
public String getIcon() {
return this.icon;
}
@Override
public Set<String> getTypes() {
return this.types;
}
@Override
public Set<String> getSupersedesBundles() {
return supersedes;
}
@Override
public boolean getStopExisting() {
return stopExisting;
}
@Override
public String getPath() {
return this.url;
}
@Override
public List<UiModuleAction> getActions() {
return ImmutableList.of();
}
}
| 8,969 |
0 |
Create_ds/brooklyn-ui/modularity-server/external-modules/src/main/java/org/apache/brooklyn/ui/modularity
|
Create_ds/brooklyn-ui/modularity-server/external-modules/src/main/java/org/apache/brooklyn/ui/modularity/enricher/BrooklynExternalUiModuleEnricher.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.enricher;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import org.apache.brooklyn.api.entity.EntityLocal;
import org.apache.brooklyn.api.sensor.AttributeSensor;
import org.apache.brooklyn.api.sensor.Sensor;
import org.apache.brooklyn.api.sensor.SensorEvent;
import org.apache.brooklyn.api.sensor.SensorEventListener;
import org.apache.brooklyn.config.ConfigKey;
import org.apache.brooklyn.core.config.ConfigKeys;
import org.apache.brooklyn.core.enricher.AbstractEnricher;
import org.apache.brooklyn.core.entity.Attributes;
import org.apache.brooklyn.ui.modularity.module.api.UiModule;
import org.apache.brooklyn.ui.modularity.module.api.UiModuleAction;
import org.apache.brooklyn.util.collections.MutableSet;
import org.apache.brooklyn.util.core.flags.TypeCoercions;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.TypeToken;
public class BrooklynExternalUiModuleEnricher extends AbstractEnricher {
private static final Logger LOG = LoggerFactory.getLogger(BrooklynExternalUiModuleEnricher.class);
private static final Dictionary<String, ?> EMPTY_DICTIONARY = new Hashtable<>();
public static final ConfigKey<String> MODULE_ICON = ConfigKeys.newStringConfigKey(
"external.ui.module.icon", "Module icon", "fa-external-link");
public static final ConfigKey<String> MODULE_NAME = ConfigKeys.newStringConfigKey(
"external.ui.module.name", "Module name");
public static final ConfigKey<String> MODULE_SLUG = ConfigKeys.newStringConfigKey(
"external.ui.module.slug", "Module slug");
public static final ConfigKey<List<String>> MODULE_TYPE = ConfigKeys.newConfigKey(new TypeToken<List<String>>() {}, "external.ui.module.types", "Module types", ImmutableList.<String>of());
public static final ConfigKey<List<String>> SUPERSEDES_BUNDLES = ConfigKeys.newConfigKey(new TypeToken<List<String>>() {}, "external.ui.module.supersedes", "Bundles supersedes", ImmutableList.<String>of());
public static final ConfigKey<Boolean> STOP_EXISTING = ConfigKeys.newConfigKey(new TypeToken<Boolean>() {}, "external.ui.module.stopExisting", "Module stops existing", true);
public static final ConfigKey<Sensor<?>> MODULE_URL_SENSOR_TO_MONITOR =
(ConfigKey) ConfigKeys.newConfigKey(Sensor.class, "external.ui.module.url.sensor", "Module URL Sensor", Attributes.MAIN_URI);
private ServiceRegistration<UiModule> registration;
@Override
public void setEntity(final EntityLocal entity) {
super.setEntity(entity);
if (getConfig(MODULE_NAME) == null) {
config().set(MODULE_NAME, entity.getDisplayName() + " UI");
}
entity.subscriptions().subscribe(entity, Attributes.SERVICE_UP, new SensorEventListener<Boolean>() {
@Override
public void onEvent(final SensorEvent<Boolean> event) {
if (event.getValue() != null && event.getValue()) {
register((String) entity.sensors().get((AttributeSensor<Object>) getConfig(MODULE_URL_SENSOR_TO_MONITOR)));
} else {
unregister();
}
}
});
entity.subscriptions().subscribe(entity, getConfig(MODULE_URL_SENSOR_TO_MONITOR), new SensorEventListener<Object>() {
@Override
public void onEvent(SensorEvent<Object> event) {
if (event.getValue() != null) {
register(TypeCoercions.coerce(event.getValue(), String.class));
}
}
});
}
synchronized private void register(final String url) {
try {
unregister();
final Bundle bundle = FrameworkUtil.getBundle(this.getClass());
if (bundle == null) {
LOG.debug("Could not register external UI module [{} :: {}] ... Could not load bundle context", getId(), getConfig(MODULE_NAME));
} else {
final Set<String> types = MutableSet.<String>builder().add("external-ui-module").addAll(getConfig(MODULE_TYPE)).build();
final UiModule uiModule = newUiModule(getId(), getConfig(MODULE_NAME), getConfig(MODULE_SLUG), types, url, getConfig(MODULE_ICON), getConfig(SUPERSEDES_BUNDLES), getConfig(STOP_EXISTING));
registration = bundle.getBundleContext().registerService(
UiModule.class, uiModule, EMPTY_DICTIONARY);
LOG.debug("Registered external UI module [{} :: {}]", getId(), getConfig(MODULE_NAME));
}
} catch (Exception e) {
LOG.info("Could not register external UI module [{} :: {}] ... {}", new Object[]{getId(), getConfig(MODULE_NAME), e.getMessage()});
}
}
synchronized private void unregister() {
if (registration != null) {
try {
registration.unregister();
LOG.debug("Unregistered external UI module [{} :: {}]", getId(), getConfig(MODULE_NAME));
} catch (IllegalStateException e) {
LOG.debug("Could not unregister external UI module [{} :: {}] ... {}", new Object[]{getId(), getConfig(MODULE_NAME), e.getMessage()});
}
registration = null;
}
}
private UiModule newUiModule(final String id, final String name, final String slug, final Set<String> types, final String url, final String icon, final Collection<String> supersedes, final boolean stopExisting) {
return new UiModule() {
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public String getSlug() {
return slug;
}
@Override
public String getDescription() {
// not supported here (it could be but isn't needed)
return null;
}
@Override
public String getIcon() {
return icon;
}
@Override
public Set<String> getTypes() {
return types;
}
@Override
public String getPath() {
return url;
}
@Override
public List<UiModuleAction> getActions() {
return ImmutableList.of();
}
@Override
public Set<String> getSupersedesBundles() {
return ImmutableSet.copyOf(supersedes);
}
@Override
public boolean getStopExisting() {
return stopExisting;
}
};
}
}
| 8,970 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-api/src/test/java/org/apache/brooklyn/ui/modularity/module
|
Create_ds/brooklyn-ui/modularity-server/module-api/src/test/java/org/apache/brooklyn/ui/modularity/module/api/UiModuleImplTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.api;
import java.util.Map;
import org.assertj.core.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import org.yaml.snakeyaml.Yaml;
import org.apache.brooklyn.ui.modularity.module.api.internal.UiModuleImpl;
public class UiModuleImplTest {
private static final Logger LOG = LoggerFactory.getLogger(UiModuleImplTest.class);
@Test
public void testUiModuleYamlLoad() {
final String test = "" +
"name: test-module\n" +
"types: single-page-app\n" +
"slug: my-test-app\n" +
"actions:\n" +
"- name: Test Action1\n" +
" icon: test-icon1\n" +
" path: '#/one/two/three'\n" +
"- name: Test Action2\n" +
" icon: test-icon2\n" +
" path: '#/three/two/one'\n";
final Map<String, ?> map = (Map<String, ?>) new Yaml().load(test);
final UiModuleImpl result = UiModuleImpl.createFromMap(map);
Assertions.assertThat(result.getId()).isNotEmpty();
Assertions.assertThat(result.getName()).isEqualTo("test-module");
Assertions.assertThat(result.getSlug()).isEqualTo("my-test-app");
Assertions.assertThat(result.getIcon()).isEqualTo(UiModule.DEFAULT_ICON);
Assertions.assertThat(result.getTypes()).hasSize(0);
Assertions.assertThat(result.getActions()).hasSize(2);
Assertions.assertThat(result.getActions().get(0).getName()).isEqualTo("Test Action1");
Assertions.assertThat(result.getActions().get(0).getPath()).isEqualTo("#/one/two/three");
Assertions.assertThat(result.getActions().get(0).getIcon()).isEqualTo("test-icon1");
Assertions.assertThat(result.getActions().get(1).getName()).isEqualTo("Test Action2");
Assertions.assertThat(result.getActions().get(1).getPath()).isEqualTo("#/three/two/one");
Assertions.assertThat(result.getActions().get(1).getIcon()).isEqualTo("test-icon2");
}
@Test
public void testUiModuleYamlLoadWithTypesArray() {
final String test = "" +
"name: test-module\n" +
"types:\n" +
"- single-page-app\n" +
"- home-ui-module\n" +
"slug: my-test-app\n";
final Map<String, ?> map = (Map<String, ?>) new Yaml().load(test);
final UiModuleImpl result = UiModuleImpl.createFromMap(map);
Assertions.assertThat(result.getId()).isNotEmpty();
Assertions.assertThat(result.getName()).isEqualTo("test-module");
Assertions.assertThat(result.getSlug()).isEqualTo("my-test-app");
Assertions.assertThat(result.getIcon()).isEqualTo(UiModule.DEFAULT_ICON);
Assertions.assertThat(result.getTypes()).hasSize(2);
Assertions.assertThat(result.getTypes().contains("single-page-app")).isTrue();
Assertions.assertThat(result.getTypes().contains("home-ui-module")).isTrue();
}
@Test
public void testUiModuleYamlLoadWithTypesArrayAvoidDuplicates() {
final String test = "" +
"name: test-module\n" +
"types:\n" +
"- single-page-app\n" +
"- single-page-app\n" +
"slug: my-test-app\n";
final Map<String, ?> map = (Map<String, ?>) new Yaml().load(test);
final UiModuleImpl result = UiModuleImpl.createFromMap(map);
Assertions.assertThat(result.getId()).isNotEmpty();
Assertions.assertThat(result.getName()).isEqualTo("test-module");
Assertions.assertThat(result.getSlug()).isEqualTo("my-test-app");
Assertions.assertThat(result.getIcon()).isEqualTo(UiModule.DEFAULT_ICON);
Assertions.assertThat(result.getTypes()).hasSize(1);
Assertions.assertThat(result.getTypes().contains("single-page-app")).isTrue();
}
}
| 8,971 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module
|
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module/api/UiModuleFilter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.api;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UiModuleFilter implements Filter {
private static final String CACHE_CONTROL = "Cache-Control";
private String cacheHeaderValue;
private boolean addCacheHeader = false;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
if (filterConfig.getInitParameter(CACHE_CONTROL) != null) {
addCacheHeader = true;
cacheHeaderValue = filterConfig.getInitParameter(CACHE_CONTROL);
}
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (addCacheHeader && servletResponse instanceof HttpServletResponse) {
((HttpServletResponse) servletResponse).setHeader(CACHE_CONTROL, cacheHeaderValue);
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
| 8,972 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module
|
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module/api/UiModuleAction.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.api;
public interface UiModuleAction {
String DEFAULT_ICON = "fa-cog";
/**
* @return The action name
*/
String getName();
/**
* @return The action path
*/
String getPath();
/**
* @return The action icon
*/
String getIcon();
}
| 8,973 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module
|
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module/api/UiModuleListener.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.api;
import java.io.InputStream;
import java.net.URL;
import java.time.Duration;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.brooklyn.ui.modularity.module.api.internal.UiModuleImpl;
import org.apache.karaf.web.WebBundle;
import org.apache.karaf.web.WebContainerService;
import org.ops4j.pax.web.service.spi.WebEvent;
import org.ops4j.pax.web.service.spi.WebListener;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
/** Invoked by modules in their web.xml to create and register the {@link UiModule} service for that UI module. */
public class UiModuleListener implements ServletContextListener {
private static final Logger LOG = LoggerFactory.getLogger(UiModuleListener.class);
private static final Dictionary<String, ?> EMPTY_DICTIONARY = new Hashtable<>();
public static final String CONFIG_PATH = "/WEB-INF/classes/ui-module/config.yaml";
private ServiceRegistration<UiModule> registration;
private AtomicReference<WebListener> listener = new AtomicReference<>();
public UiModuleListener() {
}
public void contextInitialized(ServletContextEvent servletContextEvent) {
final UiModule uiModule = createUiModule(servletContextEvent.getServletContext());
Object moduleBundle = servletContextEvent.getServletContext().getAttribute("osgi-bundlecontext");
final Bundle bundle = moduleBundle instanceof BundleContext ? ((BundleContext)moduleBundle).getBundle() : FrameworkUtil.getBundle(this.getClass());
initWebListener(bundle);
// register service against the bundle where it came from if possible (it always is, from what I've seen)
// this prevents errors if this.getClass()'s bundle is not yet active and avoids needing to delay
// (it also means service would be unregistered on that bundle destroy without listening for servlet context
// destroy but servlet context destroy is useful for symmetry with this and in case it is destroyed without
// destroying the bundle; also we were already doing it)
try {
if (bundle.getState() != Bundle.ACTIVE) {
final Duration TIMEOUT = Duration.ofMinutes(2);
LOG.warn("Bundle [{}] not ACTIVE to register Brooklyn UI module [{}], bundle current state [{}], will wait up to {}",
bundle.getSymbolicName(), uiModule.getName(), bundle.getState(), TIMEOUT);
blockUntilBundleStarted(bundle, TIMEOUT);
}
LOG.debug("Registering new Brooklyn UI module {}:{} [{}] called '{}' on context-path '{}'",
bundle.getSymbolicName(), bundle.getVersion(), bundle.getVersion(), uiModule.getName(), uiModule.getPath() );
registration = bundle.getBundleContext().registerService(UiModule.class, uiModule, EMPTY_DICTIONARY);
LOG.trace("ServletContextListener on initializing UI module "+bundle.getSymbolicName()+" ["+bundle.getBundleId()+"] "
+ "to "+uiModule.getPath()+", checking whether any bundles need stopping");
stopAnyExistingOrSuperseded(uiModule, bundle);
} catch (Exception e) {
LOG.error("Failed registration of Brooklyn UI module [" + uiModule.getName() + "] to [" + uiModule.getPath() + "]: "+e, e);
}
}
private void initWebListener(Bundle bundle) {
if (listener.compareAndSet(null, new UiModuleWebListener())) {
bundle.getBundleContext().registerService(WebListener.class, listener.get(), null);
}
}
public class UiModuleWebListener implements WebListener {
long lastId = -1;
@Override
public void webEvent(WebEvent event) {
try {
if (event.getType() == WebEvent.DEPLOYING && lastId != event.getBundleId()) {
// on deployment of new bundles check whether they are UI modules
// (this seems to be called about 10 times for any deployment; keep a note of the last bundle id to avoid duplication
lastId = event.getBundleId();
URL config = event.getBundle().getResource(CONFIG_PATH);
if (config!=null) {
LOG.trace("WebListener on deploying UI module "+event.getBundle().getSymbolicName()+" ["+event.getBundleId()+"] "
+ "to "+event.getContextPath()+", checking whether any bundles need stopping");
stopAnyExistingOrSuperseded(createUiModule(config.openStream(), event.getContextPath()), event.getBundle());
}
}
} catch (Exception e) {
if (!isBundleStartingOrActive(event.getBundle())) {
LOG.debug("Error listening to UI module bundle "+event.getBundleName()+" in state "+event.getBundle().getState()+" (not starting/active, so not a serious problem, esp if we just stopped it): "+e);
} else {
LOG.warn("Error listening to UI module bundle "+event.getBundleName()+" start: "+e, e);
}
}
}
}
protected void stopAnyExistingOrSuperseded(final UiModule uiModule, final Bundle bundle) throws Exception {
if (uiModule.getStopExisting()) {
stopExistingModulesListeningOnOurEndpoint(bundle, uiModule);
}
if (!uiModule.getSupersedesBundles().isEmpty()) {
stopSupersededBundles(bundle, uiModule);
}
}
/** stop modules on the same endpoint that with a lower number ID;
* or if a module supersedes us, stop ourselves */
private void stopExistingModulesListeningOnOurEndpoint(Bundle bundle, UiModule uiModule) throws Exception {
ServiceReference<WebContainerService> webS = bundle.getBundleContext().getServiceReference(WebContainerService.class);
WebContainerService web = bundle.getBundleContext().getService(webS);
for (WebBundle bi: web.list()) {
if (bi.getBundleId()==bundle.getBundleId()) continue;
if (uiModule.getPath().equals(bi.getContextPath()) || (uiModule.getPath().equals("") && bi.getContextPath().equals("/"))) {
Bundle bb = bundle.getBundleContext().getBundle(bi.getBundleId());
Collection<ServiceReference<UiModule>> modules = bundle.getBundleContext().getServiceReferences(UiModule.class, null);
for (ServiceReference<UiModule> modS: modules) {
if (modS.getBundle()!=null && modS.getBundle().getBundleId()==bi.getBundleId()) {
// found UiModule for the potentially conflicting bundle
UiModule mod = bundle.getBundleContext().getService(modS);
if (isBundleSuperseded(mod, bundle)) {
// if that module supersedes us, don't stop them, stop us!
stopBundle(bundle, "context path "+bi.getContextPath()+" is in use by "+bb.getSymbolicName()+" ["+bb.getBundleId()+"]");
return;
}
}
}
if (bb.getBundleId() < bundle.getBundleId()) {
// in case of context-path conflict with no declared supersedes relationship, prefer the higher number (later installed)
stopBundle(bb, "context path "+bi.getContextPath()+" is needed for installation of "+bundle.getSymbolicName()+" ["+bundle.getBundleId()+"]");
}
}
}
}
/** stop modules superseded by us */
private void stopSupersededBundles(Bundle bundle, UiModule uiModule) {
LOG.trace("Calling stopSuperseded on install of "+bundle.getSymbolicName()+"; will stop any of "+uiModule.getSupersedesBundles());
for (Bundle b: bundle.getBundleContext().getBundles()) {
if (b.getBundleId()==bundle.getBundleId()) continue;
if (isBundleSuperseded(uiModule, b)) {
stopBundle(b, "it is superseded by "+bundle.getSymbolicName()+" ["+bundle.getBundleId()+"]");
}
}
}
private boolean isBundleSuperseded(UiModule module, Bundle bundle) {
if (module.getSupersedesBundles()!=null) {
for (String superseded: module.getSupersedesBundles()) {
String bn = superseded;
String version = null;
int split = bn.indexOf(':');
if (split>=0) {
version = bn.substring(split+1);
bn = bn.substring(0, split);
}
if (bundle.getSymbolicName().matches(bn) && (version==null || bundle.getVersion().toString().matches(version))) {
return true;
}
}
}
return false;
}
protected void stopBundle(Bundle bundleToStop, String reason) {
boolean isActive = isBundleStartingOrActive(bundleToStop);
String message = "stopping bundle "+bundleToStop.getSymbolicName()+" ["+bundleToStop.getBundleId()+"]; "+reason;
if (!isActive) {
LOG.trace("Not "+message+"; but that conflicting bundle is not starting or active");
// if it tries to start it should abort itself
return;
}
LOG.debug("UiModules: " + message);
new Thread(() -> {
try {
bundleToStop.stop();
} catch (Exception e) {
LOG.warn("UiModules: error "+message+": "+e, e);
}
}).start();
}
protected boolean isBundleStartingOrActive(Bundle bundleToStop) {
switch (bundleToStop.getState()) {
case Bundle.START_TRANSIENT:
case Bundle.STARTING:
case Bundle.ACTIVE:
return true;
}
return false;
}
private void blockUntilBundleStarted(final Bundle bundle, Duration timeout) throws InterruptedException {
long endTime = System.currentTimeMillis() + timeout.toMillis();
do {
TimeUnit.MILLISECONDS.sleep(100);
LOG.trace("Waiting for bundle [{}] to be ACTIVE, current state [{}]", bundle.getSymbolicName(), bundle.getState());
if (bundle.getState() == Bundle.ACTIVE) {
return;
}
} while (System.currentTimeMillis() < endTime);
throw new IllegalStateException("Bundle "+bundle.getSymbolicName()+":"+bundle.getVersion()+" is not ACTIVE, even after waiting");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
LOG.debug("Unregistering Brooklyn UI module at [{}]", servletContextEvent.getServletContext().getContextPath());
if (registration != null) {
try {
registration.unregister();
} catch (IllegalStateException e) {
if (e.toString().contains("already unregistered")) {
LOG.debug("In {}, service already unregistered, on contextDestroyed for context {}", this, servletContextEvent);
} else {
LOG.warn("Problem unregistering service in " + this + ", on contextDestroyed for context " + servletContextEvent + " (continuing)", e);
}
}
registration = null;
}
}
private UiModule createUiModule(ServletContext servletContext) {
final InputStream is = servletContext.getResourceAsStream(CONFIG_PATH);
final String path = servletContext.getContextPath();
return createUiModule(is, path);
}
protected UiModule createUiModule(final InputStream is, final String path) {
if (is == null) {
throw new RuntimeException(String.format("Module on path [%s] will not be registered as it does not have any configuration", path));
}
@SuppressWarnings("unchecked")
Map<String, ?> config = (Map<String, ?>) new Yaml().load(is);
LOG.debug("Creating Brooklyn UI module definition for "+path+"; "+config+" / "+is);
return UiModuleImpl.createFromMap(config).path(path);
}
}
| 8,974 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module
|
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module/api/UiModule.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.api;
import java.util.List;
import java.util.Set;
import org.apache.brooklyn.ui.modularity.module.api.internal.UiModuleImpl;
public interface UiModule {
String DEFAULT_ICON = "fa-cogs";
int DEFAULT_ORDER = 10_000;
/**
* @return The unique ID of the module
*/
String getId();
/**
* @return The module name
*/
String getName();
/**
* @return The human readable id in form (part1-part2-part3...)
*/
String getSlug();
/**
* @return A description of the module, in HTML format
*/
String getDescription();
/**
* @return The icon to be used for the module
*/
String getIcon();
/**
* @return The module types eg single-page-app, external-ui
*/
Set<String> getTypes();
/**
* @return List of "bundle-regex" or "bundle-regex:version-regex" of bundles that should be stopped when this is installed.
* Useful if supplying a bundle to replace other bundles.
*/
Set<String> getSupersedesBundles();
/**
* @return Whether to web-stop any bundles listening on the same endpoint.
*/
boolean getStopExisting();
/**
* @return The module path
*/
String getPath();
/**
* @return Registered module actions
*/
List<UiModuleAction> getActions();
default int getOrder(){
return DEFAULT_ORDER;
}
public class Utils {
public static UiModule copyUiModule(UiModule src) {
return UiModuleImpl.copyOf(src);
}
}
}
| 8,975 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module
|
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module/api/UiModuleRegistry.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.api;
import java.util.Collection;
public interface UiModuleRegistry {
void register(final UiModule uiModule);
void unregister(final UiModule uiModule);
Collection<UiModule> getRegisteredModules();
}
| 8,976 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module/api
|
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module/api/internal/UiModuleActionImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.api.internal;
import com.google.common.base.Optional;
import org.apache.brooklyn.ui.modularity.module.api.UiModuleAction;
import java.util.Map;
public class UiModuleActionImpl implements UiModuleAction {
private String name;
private String path;
private String icon;
public static UiModuleActionImpl createFromMap(Map<String, ?> incomingMap) {
UiModuleActionImpl result = new UiModuleActionImpl();
result.setName(Optional.fromNullable((String) incomingMap.get("name")).or(""));
result.setPath(Optional.fromNullable((String) incomingMap.get("path")).or("#/"));
result.setIcon(Optional.fromNullable((String) incomingMap.get("icon")).or(DEFAULT_ICON));
return result;
}
@Override
public String getName() {
return name;
}
@Override
public String getPath() {
return path;
}
@Override
public String getIcon() {
return icon;
}
public void setName(final String name) {
this.name = name;
}
public void setPath(final String path) {
this.path = path;
}
public void setIcon(final String icon) {
this.icon = icon;
}
public UiModuleAction name(final String name) {
this.name = name;
return this;
}
public UiModuleAction path(final String path) {
this.path = path;
return this;
}
public UiModuleAction icon(final String icon) {
this.icon = icon;
return this;
}
}
| 8,977 |
0 |
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module/api
|
Create_ds/brooklyn-ui/modularity-server/module-api/src/main/java/org/apache/brooklyn/ui/modularity/module/api/internal/UiModuleImpl.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.brooklyn.ui.modularity.module.api.internal;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.brooklyn.ui.modularity.module.api.UiModule;
import org.apache.brooklyn.ui.modularity.module.api.UiModuleAction;
import com.google.common.base.Optional;
public class UiModuleImpl implements UiModule {
private String id;
private String name;
private String slug;
private String description;
private String icon;
private Set<String> types = new LinkedHashSet<>();
private Set<String> supersedesBundles = new LinkedHashSet<>();
private boolean stopExisting = true;
private String path;
private List<UiModuleAction> actions = new ArrayList<>();
private int order;
public static UiModuleImpl copyOf(UiModule src) {
final UiModuleImpl result = new UiModuleImpl();
result.setId(src.getId());
result.setName(src.getName());
result.setOrder(src.getOrder());
result.setSlug(src.getSlug());
result.setDescription(src.getDescription());
result.setIcon(src.getIcon());
if (src.getTypes()!=null) result.types.addAll(src.getTypes());
if (src.getSupersedesBundles()!=null) result.supersedesBundles.addAll(src.getSupersedesBundles());
result.setStopExisting(src.getStopExisting());
result.setPath(src.getPath());
if (src.getActions()!=null) result.actions.addAll(src.getActions());
return result;
}
public static UiModuleImpl createFromMap(final Map<String, ?> incomingMap) {
final UiModuleImpl result = new UiModuleImpl();
result.setId(Optional.fromNullable((String) incomingMap.get("id")).or(UUID.randomUUID().toString()));
result.setName(Optional.fromNullable((String) incomingMap.get("name")).or(result.getId()));
result.setOrder(Optional.fromNullable((Integer) incomingMap.get("order")).or(UiModule.DEFAULT_ORDER));
result.setSlug((String) incomingMap.get("slug"));
result.setDescription((String) incomingMap.get("description"));
result.setIcon(Optional.fromNullable((String) incomingMap.get("icon")).or(DEFAULT_ICON));
final Object types = incomingMap.get("types");
if (types != null && types instanceof List) {
@SuppressWarnings("unchecked")
List<String> typesTyped = (List<String>) types;
result.setTypes(new LinkedHashSet<String>(typesTyped));
}
final Object supersedes = incomingMap.get("supersedes");
if (supersedes != null && supersedes instanceof List) {
@SuppressWarnings("unchecked")
List<String> supersedesTyped = (List<String>) supersedes;
result.setSupersedesBundles(new LinkedHashSet<String>(supersedesTyped));
}
if (incomingMap.containsKey("stopExisting")) {
result.setStopExisting(Boolean.getBoolean((String) incomingMap.get("stopExisting")));
}
final Object actions = incomingMap.get("actions");
if (actions != null && actions instanceof List) {
for (Object action : (List<?>) actions) {
@SuppressWarnings("unchecked")
Map<String, ?> actionTyped = (Map<String, ?>) action;
result.action(UiModuleActionImpl.createFromMap(actionTyped));
}
}
return result;
}
@Override
public String getId() {
return id;
}
@Override
public String getIcon() {
return icon;
}
@Override
public String getName() {
return name;
}
@Override
public String getSlug() {
return slug;
}
@Override
public String getDescription() {
return description;
}
@Override
public Set<String> getTypes() {
return types;
}
@Override
public Set<String> getSupersedesBundles() {
return supersedesBundles;
}
@Override
public boolean getStopExisting() {
return stopExisting;
}
@Override
public String getPath() {
return path;
}
@Override
public List<UiModuleAction> getActions() {
return actions;
}
@Override
public int getOrder() {
return order;
}
public void setId(final String id) {
this.id = id;
}
public void setIcon(final String icon) {
this.icon = icon;
}
public void setName(final String name) {
this.name = name;
}
public void setOrder(final int order){
this.order = order;
}
public void setSlug(final String slug) {
this.slug = slug;
}
public void setDescription(final String description) {
this.description = description;
}
public void setTypes(final Set<String> types) {
this.types = types;
}
public void setSupersedesBundles(final Set<String> supersedesBundles) {
this.supersedesBundles = supersedesBundles;
}
public void setStopExisting(final boolean stopExisting) {
this.stopExisting = stopExisting;
}
public void setPath(String path) {
this.path = path;
}
public void setActions(final List<UiModuleAction> actions) {
this.actions = actions;
}
public UiModuleImpl id(final String id) {
this.id = id;
return this;
}
public UiModuleImpl icon(final String icon) {
this.icon = icon;
return this;
}
public UiModuleImpl name(final String name) {
this.name = name;
return this;
}
public UiModuleImpl slug(final String slug) {
this.slug = slug;
return this;
}
public UiModuleImpl description(final String description) {
this.description = description;
return this;
}
public UiModuleImpl types(final Set<String> types) {
this.types = types;
return this;
}
public UiModuleImpl path(final String path) {
this.path = path;
return this;
}
public UiModuleImpl action(final UiModuleAction action) {
actions.add(action);
return this;
}
public UiModuleImpl order(final int order) {
this.order=order;
return this;
}
}
| 8,978 |
0 |
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth
|
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/IAMClientCallbackHandlerTest.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam;
import software.amazon.msk.auth.iam.internals.AWSCredentialsCallback;
import software.amazon.msk.auth.iam.internals.SystemPropertyCredentialsUtils;
import org.junit.jupiter.api.Test;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class IAMClientCallbackHandlerTest {
private static final String ACCESS_KEY_VALUE = "ACCESS_KEY_VALUE";
private static final String SECRET_KEY_VALUE = "SECRET_KEY_VALUE";
@Test
public void testDefaultCredentials() throws IOException, UnsupportedCallbackException {
IAMClientCallbackHandler clientCallbackHandler = new IAMClientCallbackHandler();
clientCallbackHandler.configure(Collections.emptyMap(), "AWS_MSK_IAM", Collections.emptyList());
SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> {
AWSCredentialsCallback callback = new AWSCredentialsCallback();
try {
clientCallbackHandler.handle(new Callback[]{callback});
} catch (Exception e) {
throw new RuntimeException("Test failed", e);
}
assertTrue(callback.isSuccessful());
assertEquals(ACCESS_KEY_VALUE, callback.getAwsCredentials().getAWSAccessKeyId());
assertEquals(SECRET_KEY_VALUE, callback.getAwsCredentials().getAWSSecretKey());
}, ACCESS_KEY_VALUE, SECRET_KEY_VALUE);
}
@Test
public void testDifferentMechanism() {
IAMClientCallbackHandler clientCallbackHandler = new IAMClientCallbackHandler();
assertThrows(IllegalArgumentException.class, () -> clientCallbackHandler
.configure(Collections.emptyMap(), "SOME_OTHER_MECHANISM", Collections.emptyList()));
}
@Test
public void testDifferentCallback() {
IAMClientCallbackHandler clientCallbackHandler = new IAMClientCallbackHandler();
UnsupportedCallbackException callbackException = assertThrows(UnsupportedCallbackException.class,
() -> clientCallbackHandler.handle(new Callback[]{new Callback() {
}}));
assertTrue(callbackException.getMessage().startsWith("Unsupported"));
}
@Test
public void testDebugClassString() {
String debug1 = IAMClientCallbackHandler.debugClassString(this.getClass());
assertTrue(debug1.contains("software.amazon.msk.auth.iam.IAMClientCallbackHandlerTest"));
IAMClientCallbackHandler clientCallbackHandler = new IAMClientCallbackHandler();
String debug2 = IAMClientCallbackHandler.debugClassString(clientCallbackHandler.getClass());
assertTrue(debug2.contains("software.amazon.msk.auth.iam.IAMClientCallbackHandler"));
}
}
| 8,979 |
0 |
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth
|
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/IAMOAuthBearerLoginCallbackHandlerTest.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule;
import org.apache.kafka.common.security.oauthbearer.OAuthBearerToken;
import org.apache.kafka.common.security.oauthbearer.OAuthBearerTokenCallback;
import org.apache.kafka.common.security.scram.ScramCredentialCallback;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import com.amazonaws.auth.internal.SignerConstants;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class IAMOAuthBearerLoginCallbackHandlerTest {
private static final String ACCESS_KEY_VALUE = "ACCESS_KEY_VALUE";
private static final String SECRET_KEY_VALUE = "SECRET_KEY_VALUE";
private static final String SESSION_TOKEN = "SESSION_TOKEN";
private static final String TEST_REGION = "us-west-1";
@Test
public void configureWithInvalidMechanismShouldFail() {
// Given
IAMOAuthBearerLoginCallbackHandler iamOAuthBearerLoginCallbackHandler
= new IAMOAuthBearerLoginCallbackHandler();
// When & Then
Assertions.assertThrows(IllegalArgumentException.class, () -> iamOAuthBearerLoginCallbackHandler.configure(
Collections.emptyMap(), "SCRAM-SHA-512", Collections.emptyList()));
}
@Test
public void handleWithoutConfigureShouldThrow() {
// Given
IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler
= new IAMOAuthBearerLoginCallbackHandler();
// When & Then
Assertions.assertThrows(IllegalStateException.class,
() -> iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{new OAuthBearerTokenCallback()}));
}
@Test
public void handleWithDifferentCallbackShouldThrow() {
// Given
IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler
= new IAMOAuthBearerLoginCallbackHandler();
iamoAuthBearerLoginCallbackHandler.configure(
Collections.emptyMap(), OAuthBearerLoginModule.OAUTHBEARER_MECHANISM, Collections.emptyList());
// When & Then
Assertions.assertThrows(UnsupportedCallbackException.class,
() -> iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{new ScramCredentialCallback()}));
}
@Test
public void handleWithTokenValuePresentShouldThrow() {
// Given
IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler
= new IAMOAuthBearerLoginCallbackHandler();
iamoAuthBearerLoginCallbackHandler.configure(
Collections.emptyMap(), OAuthBearerLoginModule.OAUTHBEARER_MECHANISM, Collections.emptyList());
OAuthBearerTokenCallback callback = new OAuthBearerTokenCallback();
callback.token(getTestToken("token"));
// When & Then
Assertions.assertThrows(IllegalArgumentException.class,
() -> iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{callback}));
}
@Test
public void handleWithDefaultCredentials() throws IOException, UnsupportedCallbackException, URISyntaxException, ParseException {
// Given
IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler
= new IAMOAuthBearerLoginCallbackHandler();
iamoAuthBearerLoginCallbackHandler.configure(
Collections.emptyMap(), OAuthBearerLoginModule.OAUTHBEARER_MECHANISM, Collections.emptyList());
System.setProperty("aws.accessKeyId", ACCESS_KEY_VALUE);
System.setProperty("aws.secretKey", SECRET_KEY_VALUE);
System.setProperty("aws.sessionToken", SESSION_TOKEN);
System.setProperty("aws.region", TEST_REGION);
OAuthBearerTokenCallback callback = new OAuthBearerTokenCallback();
// When
iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{callback});
// Then
assertTokenValidity(callback.token(), TEST_REGION, ACCESS_KEY_VALUE, SESSION_TOKEN);
cleanUp();
}
@Test
public void testGovCloudRegionHandler() throws IOException, UnsupportedCallbackException, URISyntaxException, ParseException {
// Given
IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler
= new IAMOAuthBearerLoginCallbackHandler();
iamoAuthBearerLoginCallbackHandler.configure(
Collections.emptyMap(), OAuthBearerLoginModule.OAUTHBEARER_MECHANISM, Collections.emptyList());
System.setProperty("aws.accessKeyId", ACCESS_KEY_VALUE);
System.setProperty("aws.secretKey", SECRET_KEY_VALUE);
System.setProperty("aws.sessionToken", SESSION_TOKEN);
System.setProperty("aws.region", "us-gov-west-2");
OAuthBearerTokenCallback callback = new OAuthBearerTokenCallback();
// When
iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{callback});
// Then
assertTokenValidity(callback.token(), "us-gov-west-2", ACCESS_KEY_VALUE, SESSION_TOKEN);
cleanUp();
}
@Test
public void handleWithProfileCredentials() throws IOException, UnsupportedCallbackException, URISyntaxException, ParseException {
// Given
final String accessKey = "PROFILE_ACCESS_KEY";
final String secretKey = "PROFILE_SECRET_KEY";
final String sessionToken = "PROFILE_SESSION_TOKEN";
final String profileName = "dev";
IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler
= new IAMOAuthBearerLoginCallbackHandler();
iamoAuthBearerLoginCallbackHandler.configure(
Collections.singletonMap("awsProfileName", profileName), OAuthBearerLoginModule.OAUTHBEARER_MECHANISM, Collections.emptyList());
System.setProperty("aws.accessKeyId", accessKey);
System.setProperty("aws.secretKey", secretKey);
System.setProperty("aws.sessionToken", sessionToken);
System.setProperty("aws.profile", profileName);
System.setProperty("aws.region", TEST_REGION);
OAuthBearerTokenCallback callback = new OAuthBearerTokenCallback();
// When
iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{callback});
// Then
assertTokenValidity(callback.token(), TEST_REGION, accessKey, sessionToken);
cleanUp();
}
@Test
public void testDebugClassString() {
String debug1 = IAMOAuthBearerLoginCallbackHandler.debugClassString(this.getClass());
assertTrue(debug1.contains("software.amazon.msk.auth.iam.IAMOAuthBearerLoginCallbackHandlerTest"));
IAMOAuthBearerLoginCallbackHandler loginCallbackHandler = new IAMOAuthBearerLoginCallbackHandler();
String debug2 = IAMOAuthBearerLoginCallbackHandler.debugClassString(loginCallbackHandler.getClass());
assertTrue(debug2.contains("software.amazon.msk.auth.iam.IAMOAuthBearerLoginCallbackHandler"));
}
private OAuthBearerToken getTestToken(final String tokenValue) {
return new IAMOAuthBearerToken(tokenValue, TimeUnit.MINUTES.toSeconds(15));
}
private void assertTokenValidity(OAuthBearerToken token, String region, String accessKey, String sessionToken) throws URISyntaxException, ParseException {
Assertions.assertNotNull(token);
String tokenValue = token.value();
Assertions.assertNotNull(tokenValue);
Assertions.assertEquals("kafka-cluster", token.principalName());
Assertions.assertEquals(Collections.emptySet(), token.scope());
Assertions.assertTrue(token.startTimeMs() <= System.currentTimeMillis());
byte[] tokenBytes = tokenValue.getBytes(StandardCharsets.UTF_8);
String decodedPresignedUrl = new String(Base64.getUrlDecoder()
.decode(tokenBytes), StandardCharsets.UTF_8);
final URI uri = new URI(decodedPresignedUrl);
Assertions.assertEquals(String.format("kafka.%s.amazonaws.com", region), uri.getHost());
Assertions.assertEquals("https", uri.getScheme());
List<NameValuePair> params = URLEncodedUtils.parse(uri, StandardCharsets.UTF_8);
Map<String, String> paramMap = params.stream()
.collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));
Assertions.assertEquals("kafka-cluster:Connect", paramMap.get("Action"));
Assertions.assertEquals(SignerConstants.AWS4_SIGNING_ALGORITHM, paramMap.get(SignerConstants.X_AMZ_ALGORITHM));
final Integer expirySeconds = Integer.parseInt(paramMap.get(SignerConstants.X_AMZ_EXPIRES));
Assertions.assertTrue(expirySeconds <= 900);
Assertions.assertTrue(token.lifetimeMs() <= System.currentTimeMillis() + Integer.parseInt(paramMap.get(SignerConstants.X_AMZ_EXPIRES)) * 1000);
Assertions.assertEquals(sessionToken, paramMap.get(SignerConstants.X_AMZ_SECURITY_TOKEN));
Assertions.assertEquals("host", paramMap.get(SignerConstants.X_AMZ_SIGNED_HEADER));
String credential = paramMap.get(SignerConstants.X_AMZ_CREDENTIAL);
Assertions.assertNotNull(credential);
String[] credentialArray = credential.split("/");
Assertions.assertEquals(5, credentialArray.length);
Assertions.assertEquals(accessKey, credentialArray[0]);
Assertions.assertEquals("kafka-cluster", credentialArray[3]);
Assertions.assertEquals(SignerConstants.AWS4_TERMINATOR, credentialArray[4]);
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'");
final LocalDateTime signedDate = LocalDateTime.parse(paramMap.get(SignerConstants.X_AMZ_DATE), dateFormat);
long signedDateEpochMillis = signedDate.toInstant(ZoneOffset.UTC)
.toEpochMilli();
Assertions.assertTrue(signedDateEpochMillis <= Instant.now()
.toEpochMilli());
Assertions.assertEquals(signedDateEpochMillis, token.startTimeMs());
Assertions.assertEquals(signedDateEpochMillis + expirySeconds * 1000, token.lifetimeMs());
String userAgent = paramMap.get("User-Agent");
Assertions.assertNotNull(userAgent);
Assertions.assertTrue(userAgent.startsWith("aws-msk-iam-auth"));
}
private void cleanUp() {
System.clearProperty("aws.accessKeyId");
System.clearProperty("aws.secretKey");
System.clearProperty("aws.sessionToken");
System.clearProperty("aws.profile");
System.clearProperty("aws.region");
}
}
| 8,980 |
0 |
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth
|
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/ProducerClientTest.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.util.Properties;
public class ProducerClientTest {
private static final String SASL_IAM_JAAS_CONFIG_VALUE = "software.amazon.msk.auth.iam.IAMLoginModule required awsProfileName=\"dadada bbbb\";";
@Test
@Tag("ignored")
public void testProducer() {
Properties producerProperties = new Properties();
producerProperties.put("bootstrap.servers", "localhost:9092");
producerProperties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
producerProperties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
producerProperties.put("sasl.jaas.config", SASL_IAM_JAAS_CONFIG_VALUE);
producerProperties.put("security.protocol", "SASL_SSL");
producerProperties.put("sasl.mechanism", "AWS_MSK_IAM");
producerProperties
.put("sasl.client.callback.handler.class", "software.amazon.msk.auth.iam.IAMClientCallbackHandler");
KafkaProducer<String, String> producer = new KafkaProducer<String, String>(producerProperties);
producer.send(new ProducerRecord<>("test", "keys", "values"));
}
}
| 8,981 |
0 |
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/IAMSaslClientTest.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import com.amazonaws.auth.BasicAWSCredentials;
import org.junit.jupiter.api.BeforeEach;
import software.amazon.msk.auth.iam.IAMClientCallbackHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.kafka.common.errors.IllegalSaslStateException;
import org.junit.jupiter.api.Test;
import software.amazon.msk.auth.iam.internals.IAMSaslClient.ClassLoaderAwareIAMSaslClientFactory;
import static java.util.Collections.emptyMap;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
import java.io.IOException;
import java.text.ParseException;
import java.util.Collections;
import java.util.function.Supplier;
public class IAMSaslClientTest {
private static final String VALID_HOSTNAME = "b-3.unit-test.abcdef.kafka.us-west-2.amazonaws.com";
private static final String AWS_MSK_IAM = "AWS_MSK_IAM";
private static final String ACCESS_KEY_VALUE = "ACCESS_KEY_VALUE";
private static final String SECRET_KEY_VALUE = "SECRET_KEY_VALUE";
private static final String ACCESS_KEY_VALUE_TWO = "ACCESS_KEY_VALUE_TWO";
private static final String SECRET_KEY_VALUE_TWO = "SECRET_KEY_VALUE_TWO";
private static final String RESPONSE_VERSION = "2020_10_22";
private static final BasicAWSCredentials BASIC_AWS_CREDENTIALS = new BasicAWSCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE);
@BeforeEach
public void setUp() {
IAMSaslClientProvider.initialize();
}
@Test
public void testCompleteValidExchange() throws IOException {
IAMSaslClient saslClient = getSuccessfulIAMClient(getIamClientCallbackHandler());
runValidExchangeForSaslClient(saslClient, ACCESS_KEY_VALUE, SECRET_KEY_VALUE);
}
private void runValidExchangeForSaslClient(IAMSaslClient saslClient, String accessKey, String secretKey) {
assertEquals(getMechanismName(), saslClient.getMechanismName());
assertTrue(saslClient.hasInitialResponse());
SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> {
try {
byte[] response = saslClient.evaluateChallenge(new byte[] {});
SignedPayloadValidatorUtils
.validatePayload(response,
AuthenticationRequestParams
.create(VALID_HOSTNAME, new BasicAWSCredentials(accessKey, secretKey),
UserAgentUtils.getUserAgentValue()));
assertFalse(saslClient.isComplete());
String requestId = RandomStringUtils.randomAlphabetic(10);
saslClient.evaluateChallenge(getServerResponse(RESPONSE_VERSION, requestId));
assertTrue(saslClient.isComplete());
assertEquals(requestId, saslClient.getResponseRequestId());
} catch (Exception e) {
throw new RuntimeException("Test failed", e);
}
}, accessKey, secretKey);
}
private byte [] getServerResponse(String version, String requestId) throws JsonProcessingException {
AuthenticationResponse response = new AuthenticationResponse(version, requestId);
return new ObjectMapper().writeValueAsBytes(response);
}
@Test
public void testMultipleSaslClients() throws IOException, ParseException {
IAMClientCallbackHandler cbh = getIamClientCallbackHandler();
//test the first Sasl client with 1 set of credentials.
IAMSaslClient saslClient1 = getSuccessfulIAMClient(cbh);
runValidExchangeForSaslClient(saslClient1, ACCESS_KEY_VALUE, SECRET_KEY_VALUE);
//test second sasl client with another set of credentials
IAMSaslClient saslClient2 = getSuccessfulIAMClient(cbh);
runValidExchangeForSaslClient(saslClient2, ACCESS_KEY_VALUE_TWO, SECRET_KEY_VALUE_TWO);
}
private IAMClientCallbackHandler getIamClientCallbackHandler() {
IAMClientCallbackHandler cbh = new IAMClientCallbackHandler();
cbh.configure(emptyMap(), AWS_MSK_IAM, Collections.emptyList());
return cbh;
}
@Test
public void testNonEmptyChallenge() throws SaslException {
SaslClient saslClient = getSuccessfulIAMClient(getIamClientCallbackHandler());
SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> {
assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(new byte[]{2, 3}));
}, ACCESS_KEY_VALUE, SECRET_KEY_VALUE);
assertFalse(saslClient.isComplete());
}
@Test
public void testFailedCallback() throws SaslException {
SaslClient saslClient = getFailureIAMClient();
assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(new byte[]{}));
assertFalse(saslClient.isComplete());
}
@Test
public void testThrowingCallback() throws SaslException {
SaslClient saslClient = getThrowingIAMClient();
assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(new byte[]{}));
assertFalse(saslClient.isComplete());
}
@Test
public void testInvalidServerResponse() throws SaslException {
SaslClient saslClient = getSuccessfulIAMClient(getIamClientCallbackHandler());
assertEquals(getMechanismName(), saslClient.getMechanismName());
assertTrue(saslClient.hasInitialResponse());
SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> {
try {
saslClient.evaluateChallenge(new byte[]{});
} catch (SaslException e) {
throw new RuntimeException("Test failed", e);
}
assertFalse(saslClient.isComplete());
assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(new byte[]{3, 4}));
assertFalse(saslClient.isComplete());
assertThrows(IllegalSaslStateException.class, () -> saslClient.evaluateChallenge(new byte[]{}));
}, ACCESS_KEY_VALUE, SECRET_KEY_VALUE);
}
@Test
public void testInvalidResponseVersion() throws SaslException {
SaslClient saslClient = getSuccessfulIAMClient(getIamClientCallbackHandler());
SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> {
try {
saslClient.evaluateChallenge(new byte[]{});
} catch (SaslException e) {
throw new RuntimeException("Test failed", e);
}
assertFalse(saslClient.isComplete());
assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(getResponseWithInvalidVersion()));
assertFalse(saslClient.isComplete());
assertThrows(IllegalSaslStateException.class, () -> saslClient.evaluateChallenge(new byte[]{}));
}, ACCESS_KEY_VALUE, SECRET_KEY_VALUE);
}
private byte[] getResponseWithInvalidVersion() {
AuthenticationResponse response = new AuthenticationResponse(RESPONSE_VERSION, "TEST_REQUEST_ID");
try {
return new ObjectMapper().writeValueAsString(response).replaceAll(RESPONSE_VERSION,"INVALID_VERSION").getBytes();
} catch (JsonProcessingException e) {
throw new RuntimeException("Test failed", e);
}
}
@Test
public void testEmptyServerResponse() throws SaslException {
SaslClient saslClient = getSuccessfulIAMClient(getIamClientCallbackHandler());
assertEquals(getMechanismName(), saslClient.getMechanismName());
assertTrue(saslClient.hasInitialResponse());
SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> {
try {
saslClient.evaluateChallenge(new byte[]{});
} catch (SaslException e) {
throw new RuntimeException("Test failed", e);
}
assertFalse(saslClient.isComplete());
assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(new byte[]{}));
assertFalse(saslClient.isComplete());
}, ACCESS_KEY_VALUE, SECRET_KEY_VALUE);
}
@Test
public void testFactoryMechanisms() {
assertArrayEquals(new String[] { getMechanismName() },
new IAMSaslClient.IAMSaslClientFactory().getMechanismNames(emptyMap()));
}
@Test
public void testInvalidMechanism() {
assertThrows(SaslException.class, () -> new IAMSaslClient.IAMSaslClientFactory()
.createSaslClient(new String[]{AWS_MSK_IAM + "BAD"}, "AUTH_ID", "PROTOCOL", VALID_HOSTNAME,
emptyMap(),
new SuccessfulIAMCallbackHandler(BASIC_AWS_CREDENTIALS)));
}
@Test
public void testClassLoaderAwareIAMSaslClientFactoryMechanisms() {
assertArrayEquals(new String[] { AWS_MSK_IAM },
new ClassLoaderAwareIAMSaslClientFactory().getMechanismNames(emptyMap()));
}
private static class SuccessfulIAMCallbackHandler extends IAMClientCallbackHandler {
private final BasicAWSCredentials basicAWSCredentials;
public SuccessfulIAMCallbackHandler(BasicAWSCredentials basicAWSCredentials) {
this.basicAWSCredentials = basicAWSCredentials;
}
@Override
protected void handleCallback(AWSCredentialsCallback callback) {
callback.setAwsCredentials(basicAWSCredentials);
}
}
private IAMSaslClient getSuccessfulIAMClient(IAMClientCallbackHandler cbh) throws SaslException {
return getIAMClient(() -> cbh);
}
private SaslClient getFailureIAMClient() throws SaslException {
return getIAMClient(() -> new IAMClientCallbackHandler() {
@Override
protected void handleCallback(AWSCredentialsCallback callback) {
callback.setLoadingException(new IllegalArgumentException("TEST Exception"));
}
});
}
private SaslClient getThrowingIAMClient() throws SaslException {
return getIAMClient(() -> new IAMClientCallbackHandler() {
@Override
protected void handleCallback(AWSCredentialsCallback callback) throws IOException {
throw new IOException("TEST IO Exception");
}
});
}
private IAMSaslClient getIAMClient(Supplier<IAMClientCallbackHandler> handlerSupplier) throws SaslException {
return (IAMSaslClient) new IAMSaslClient.ClassLoaderAwareIAMSaslClientFactory()
.createSaslClient(new String[] { AWS_MSK_IAM }, "AUTH_ID", "PROTOCOL", VALID_HOSTNAME,
emptyMap(),
handlerSupplier.get());
}
private String getMechanismName() {
return AWS_MSK_IAM + "." + getClass().getClassLoader().hashCode();
}
}
| 8,982 |
0 |
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/SignedPayloadValidatorUtils.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import com.amazonaws.auth.internal.SignerConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public final class SignedPayloadValidatorUtils {
private static final String VERSION = "version";
private static final String HOST = "host";
private static final String[] requiredKeys = {VERSION,
HOST,
SignerConstants.X_AMZ_CREDENTIAL.toLowerCase(),
SignerConstants.X_AMZ_DATE.toLowerCase(),
SignerConstants.X_AMZ_SIGNED_HEADER.toLowerCase(),
SignerConstants.X_AMZ_EXPIRES.toLowerCase(),
SignerConstants.X_AMZ_SIGNATURE.toLowerCase(),
SignerConstants.X_AMZ_ALGORITHM.toLowerCase()};
private static final String ACTION = "action";
private static final String[] optionalKeys = {
"x-amz-security-token",
ACTION,
};
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMDD\'T\'HHMMSS\'Z\'");
private SignedPayloadValidatorUtils() {
}
public static void validatePayload(byte[] payload, AuthenticationRequestParams params)
throws IOException, ParseException {
ObjectMapper mapper = new ObjectMapper();
Map<String, String> propertyMap = (Map<String, String>) mapper.readValue(payload, Map.class);
assertEquals(10, propertyMap.size());
//check if all required keys are present and non-empty
List<String> missingRequiredKeys = Arrays.stream(requiredKeys)
.filter(k -> propertyMap.get(k) == null || propertyMap.get(k).isEmpty())
.collect(Collectors.toList());
assertTrue(missingRequiredKeys.isEmpty());
// check values for some keys
assertEquals("2020_10_22", propertyMap.get(VERSION));
assertEquals(params.getHost(), propertyMap.get(HOST));
assertEquals("kafka-cluster:Connect", propertyMap.get(ACTION));
assertEquals("host", propertyMap.get(SignerConstants.X_AMZ_SIGNED_HEADER.toLowerCase()));
assertEquals(SignerConstants.AWS4_SIGNING_ALGORITHM,
propertyMap.get(SignerConstants.X_AMZ_ALGORITHM.toLowerCase()));
assertTrue(dateFormat.parse(propertyMap.get(SignerConstants.X_AMZ_DATE.toLowerCase())).toInstant()
.isBefore(Instant.now()));
assertTrue(Integer.parseInt(propertyMap.get(SignerConstants.X_AMZ_EXPIRES.toLowerCase())) <= 900);
String credential = propertyMap.get(SignerConstants.X_AMZ_CREDENTIAL.toLowerCase());
assertNotNull(credential);
String[] credentialArray = credential.split("/");
assertEquals(5, credentialArray.length);
assertEquals(params.getAwsCredentials().getAWSAccessKeyId(), credentialArray[0]);
String userAgent = propertyMap.get("user-agent");
assertNotNull(userAgent);
assertTrue(userAgent.startsWith("aws-msk-iam-auth"));
}
}
| 8,983 |
0 |
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/MSKCredentialProviderTest.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import com.amazonaws.SdkBaseException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSCredentialsProviderChain;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.auth.EC2ContainerCredentialsProviderWrapper;
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
import com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider;
import com.amazonaws.auth.SystemPropertiesCredentialsProvider;
import com.amazonaws.auth.WebIdentityTokenCredentialsProvider;
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
import com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest;
import com.amazonaws.services.securitytoken.model.GetCallerIdentityResult;
import software.amazon.awssdk.profiles.ProfileFile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static software.amazon.msk.auth.iam.internals.SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials;
import static software.amazon.msk.auth.iam.internals.SystemPropertyCredentialsUtils.runTestWithSystemPropertyProfile;
public class MSKCredentialProviderTest {
private static final String ACCESS_KEY_VALUE = "ACCESS_KEY_VALUE";
private static final String SECRET_KEY_VALUE = "SECRET_KEY_VALUE";
private static final String ACCESS_KEY_VALUE_TWO = "ACCESS_KEY_VALUE_TWO";
private static final String SECRET_KEY_VALUE_TWO = "SECRET_KEY_VALUE_TWO";
private static final String TEST_PROFILE_NAME = "test_profile";
private static final String PROFILE_ACCESS_KEY_VALUE = "PROFILE_ACCESS_KEY";
private static final String PROFILE_SECRET_KEY_VALUE = "PROFILE_SECRET_KEY";
private static final String TEST_ROLE_ARN = "TEST_ROLE_ARN";
private static final String TEST_ROLE_EXTERNAL_ID = "TEST_EXTERNAL_ID";
private static final String TEST_ROLE_SESSION_NAME = "TEST_ROLE_SESSION_NAME";
private static final String SESSION_TOKEN = "SESSION_TOKEN";
private static final String AWS_ROLE_ARN = "awsRoleArn";
private static final String AWS_ROLE_EXTERNAL_ID = "awsRoleExternalId";
private static final String AWS_ROLE_ACCESS_KEY_ID = "awsRoleAccessKeyId";
private static final String AWS_ROLE_SECRET_ACCESS_KEY = "awsRoleSecretAccessKey";
private static final String AWS_PROFILE_NAME = "awsProfileName";
private static final String AWS_DEBUG_CREDS_NAME = "awsDebugCreds";
/**
* If no options are passed in it should use the default credentials provider
* which should pick up the java system properties.
*/
@Test
public void testNoOptions() {
runDefaultTest();
}
private void runDefaultTest() {
runTestWithSystemPropertyCredentials(() -> {
MSKCredentialProvider provider = new MSKCredentialProvider(Collections.emptyMap());
assertFalse(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
assertEquals(ACCESS_KEY_VALUE, credentials.getAWSAccessKeyId());
assertEquals(SECRET_KEY_VALUE, credentials.getAWSSecretKey());
}, ACCESS_KEY_VALUE, SECRET_KEY_VALUE);
}
/**
* If a profile name is passed in but there is no profile by that name
* it should still use the default credential provider.
*/
@Test
public void testMissingProfileName() {
runTestWithSystemPropertyCredentials(() -> {
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_PROFILE_NAME, "MISSING_PROFILE");
MSKCredentialProvider provider = new MSKCredentialProvider(optionsMap);
AWSCredentials credentials = provider.getCredentials();
assertEquals(ACCESS_KEY_VALUE, credentials.getAWSAccessKeyId());
assertEquals(SECRET_KEY_VALUE, credentials.getAWSSecretKey());
}, ACCESS_KEY_VALUE, SECRET_KEY_VALUE);
}
/**
* If the credentials available to the default credential provider change,
* the new credentials should be picked up.
*
* @throws IOException
*/
@Test
public void testChangingCredentials() throws IOException {
runDefaultTest();
runTestWithSystemPropertyProfile(() -> {
ProfileFile profileFile = getProfileFile();
MSKCredentialProvider provider = new MSKCredentialProvider(Collections.emptyMap()) {
protected AWSCredentialsProviderChain getDefaultProvider() {
return new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider(),
new SystemPropertiesCredentialsProvider(),
WebIdentityTokenCredentialsProvider.create(),
new EnhancedProfileCredentialsProvider(profileFile, null),
new EC2ContainerCredentialsProviderWrapper());
}
};
AWSCredentials credentials = provider.getCredentials();
assertEquals(PROFILE_ACCESS_KEY_VALUE, credentials.getAWSAccessKeyId());
assertEquals(PROFILE_SECRET_KEY_VALUE, credentials.getAWSSecretKey());
}, TEST_PROFILE_NAME);
}
@Test
public void testProfileName() {
ProfileFile profileFile = getProfileFile();
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_PROFILE_NAME, "test_profile");
MSKCredentialProvider.ProviderBuilder providerBuilder = new MSKCredentialProvider.ProviderBuilder(optionsMap) {
EnhancedProfileCredentialsProvider createEnhancedProfileCredentialsProvider(String profileName) {
assertEquals(TEST_PROFILE_NAME, profileName);
return new EnhancedProfileCredentialsProvider(profileFile, TEST_PROFILE_NAME);
}
};
MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder);
assertFalse(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
assertEquals(PROFILE_ACCESS_KEY_VALUE, credentials.getAWSAccessKeyId());
assertEquals(PROFILE_SECRET_KEY_VALUE, credentials.getAWSSecretKey());
}
@Test
public void testAwsRoleArn() {
STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito
.mock(STSAssumeRoleSessionCredentialsProvider.class);
Mockito.when(mockStsRoleProvider.getCredentials())
.thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN));
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN);
MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilder(mockStsRoleProvider, optionsMap,
"aws-msk-iam-auth");
MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder);
assertFalse(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
validateBasicSessionCredentials(credentials);
provider.close();
Mockito.verify(mockStsRoleProvider, times(1)).close();
}
@Test
public void testAwsRoleArnWithAccessKey() {
STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito
.mock(STSAssumeRoleSessionCredentialsProvider.class);
Mockito.when(mockStsRoleProvider.getCredentials())
.thenAnswer(invocation -> new BasicSessionCredentials(ACCESS_KEY_VALUE_TWO, SECRET_KEY_VALUE_TWO, SESSION_TOKEN));
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN);
optionsMap.put(AWS_ROLE_ACCESS_KEY_ID, ACCESS_KEY_VALUE_TWO);
optionsMap.put(AWS_ROLE_SECRET_ACCESS_KEY, SECRET_KEY_VALUE_TWO);
MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilderWithCredentials(mockStsRoleProvider, optionsMap,
"aws-msk-iam-auth");
MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder);
assertFalse(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
validateBasicSessionCredentialsTwo(credentials);
provider.close();
Mockito.verify(mockStsRoleProvider, times(1)).close();
}
@Test
public void testAwsRoleArnWithDebugCreds() {
STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito
.mock(STSAssumeRoleSessionCredentialsProvider.class);
Mockito.when(mockStsRoleProvider.getCredentials())
.thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN));
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN);
optionsMap.put(AWS_DEBUG_CREDS_NAME, "true");
MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilder(mockStsRoleProvider, optionsMap,
"aws-msk-iam-auth");
AWSSecurityTokenService mockSts = Mockito.mock(AWSSecurityTokenService.class);
Mockito.when(mockSts.getCallerIdentity(Mockito.any(GetCallerIdentityRequest.class))).thenReturn(new GetCallerIdentityResult().withUserId("TEST_USER_ID").withAccount("TEST_ACCOUNT").withArn("TEST_ARN"));
MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder) {
AWSSecurityTokenService getStsClientForDebuggingCreds(AWSCredentials credentials) {
return mockSts;
}
};
assertTrue(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
validateBasicSessionCredentials(credentials);
provider.close();
Mockito.verify(mockStsRoleProvider, times(1)).close();
Mockito.verify(mockSts, times(1)).getCallerIdentity(any(GetCallerIdentityRequest.class));
}
@Test
public void testEc2CredsWithDebugCredsNoAccessToSts_Succeed() {
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_DEBUG_CREDS_NAME, "true");
EC2ContainerCredentialsProviderWrapper mockEc2CredsProvider = Mockito.mock(EC2ContainerCredentialsProviderWrapper.class);
Mockito.when(mockEc2CredsProvider.getCredentials())
.thenReturn(new BasicAWSCredentials(ACCESS_KEY_VALUE_TWO, SECRET_KEY_VALUE_TWO));
AWSSecurityTokenService mockSts = Mockito.mock(AWSSecurityTokenService.class);
Mockito.when(mockSts.getCallerIdentity(Mockito.any(GetCallerIdentityRequest.class)))
.thenThrow(new SdkClientException("TEST TEST"));
MSKCredentialProvider provider = new MSKCredentialProvider(optionsMap) {
protected AWSCredentialsProviderChain getDefaultProvider() {
return new AWSCredentialsProviderChain(mockEc2CredsProvider);
}
AWSSecurityTokenService getStsClientForDebuggingCreds(AWSCredentials credentials) {
return mockSts;
}
};
assertTrue(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
validateBasicCredentialsTwo(credentials);
provider.close();
Mockito.verify(mockSts, times(1)).getCallerIdentity(Mockito.any());
Mockito.verify(mockEc2CredsProvider, times(1)).getCredentials();
Mockito.verifyNoMoreInteractions(mockEc2CredsProvider);
}
@Test
public void testAwsRoleArnAndSessionName() {
STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito
.mock(STSAssumeRoleSessionCredentialsProvider.class);
Mockito.when(mockStsRoleProvider.getCredentials())
.thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN));
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN);
optionsMap.put("awsRoleSessionName", TEST_ROLE_SESSION_NAME);
MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilder(mockStsRoleProvider, optionsMap,
TEST_ROLE_SESSION_NAME);
MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder);
assertFalse(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
validateBasicSessionCredentials(credentials);
provider.close();
Mockito.verify(mockStsRoleProvider, times(1)).close();
}
@Test
public void testAwsRoleArnSessionNameAndStsRegion() {
STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito
.mock(STSAssumeRoleSessionCredentialsProvider.class);
Mockito.when(mockStsRoleProvider.getCredentials())
.thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN));
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN);
optionsMap.put("awsRoleSessionName", TEST_ROLE_SESSION_NAME);
optionsMap.put("awsStsRegion", "eu-west-1");
MSKCredentialProvider.ProviderBuilder providerBuilder = new MSKCredentialProvider.ProviderBuilder(optionsMap) {
STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn,
String sessionName, String stsRegion) {
assertEquals(TEST_ROLE_ARN, roleArn);
assertEquals(TEST_ROLE_SESSION_NAME, sessionName);
assertEquals("eu-west-1", stsRegion);
return mockStsRoleProvider;
}
};
MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder);
assertFalse(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
validateBasicSessionCredentials(credentials);
provider.close();
Mockito.verify(mockStsRoleProvider, times(1)).close();
}
@Test
public void testAwsRoleArnSessionNameStsRegionAndExternalId() {
STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito
.mock(STSAssumeRoleSessionCredentialsProvider.class);
Mockito.when(mockStsRoleProvider.getCredentials())
.thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN));
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN);
optionsMap.put(AWS_ROLE_EXTERNAL_ID, TEST_ROLE_EXTERNAL_ID);
optionsMap.put("awsRoleSessionName", TEST_ROLE_SESSION_NAME);
optionsMap.put("awsStsRegion", "eu-west-1");
MSKCredentialProvider.ProviderBuilder providerBuilder = new MSKCredentialProvider.ProviderBuilder(optionsMap) {
STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn,
String externalId,
String sessionName,
String stsRegion) {
assertEquals(TEST_ROLE_ARN, roleArn);
assertEquals(TEST_ROLE_EXTERNAL_ID, externalId);
assertEquals(TEST_ROLE_SESSION_NAME, sessionName);
assertEquals("eu-west-1", stsRegion);
return mockStsRoleProvider;
}
};
MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder);
assertFalse(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
validateBasicSessionCredentials(credentials);
provider.close();
Mockito.verify(mockStsRoleProvider, times(1)).close();
}
@Test
public void testProfileNameAndRoleArn() {
ProfileFile profileFile = getProfileFile();
STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito
.mock(STSAssumeRoleSessionCredentialsProvider.class);
Mockito.when(mockStsRoleProvider.getCredentials())
.thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE_TWO, SECRET_KEY_VALUE_TWO, SESSION_TOKEN));
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_PROFILE_NAME, "test_profile");
optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN);
MSKCredentialProvider.ProviderBuilder providerBuilder = new MSKCredentialProvider.ProviderBuilder(optionsMap) {
EnhancedProfileCredentialsProvider createEnhancedProfileCredentialsProvider(String profileName) {
assertEquals(TEST_PROFILE_NAME, profileName);
return new EnhancedProfileCredentialsProvider(profileFile, TEST_PROFILE_NAME);
}
STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn,
String sessionName, String stsRegion) {
assertEquals(TEST_ROLE_ARN, roleArn);
assertEquals("aws-msk-iam-auth", sessionName);
return mockStsRoleProvider;
}
};
MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder);
assertFalse(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
provider.close();
assertEquals(PROFILE_ACCESS_KEY_VALUE, credentials.getAWSAccessKeyId());
assertEquals(PROFILE_SECRET_KEY_VALUE, credentials.getAWSSecretKey());
Mockito.verify(mockStsRoleProvider, times(0)).getCredentials();
Mockito.verify(mockStsRoleProvider, times(1)).close();
}
@Test
public void testRoleCredsWithTwoRetriableErrors() {
testRoleCredsWithRetriableErrors(2);
}
@Test
public void testRoleCredsWithThreeRetriableErrors() {
testRoleCredsWithRetriableErrors(3);
}
@Test
public void testRoleCredsWithFourRetriableErrors_ThrowsException() {
int numExceptions = 4;
STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = setupMockStsRoleCredentialsProviderWithRetriableExceptions(numExceptions);
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN);
MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilder(mockStsRoleProvider, optionsMap,
"aws-msk-iam-auth");
MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder) {
protected AWSCredentialsProviderChain getDefaultProvider() {
return new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider());
}
};
assertFalse(provider.getShouldDebugCreds());
assertThrows(SdkClientException.class, () -> provider.getCredentials());
Mockito.verify(mockStsRoleProvider, times(numExceptions)).getCredentials();
Mockito.verifyNoMoreInteractions(mockStsRoleProvider);
}
@Test
public void testEc2CredsWithTwoRetriableErrorsCustomRetry() {
testEc2CredsWithRetriableErrorsCustomRetry(2);
}
@Test
public void testEc2CredsWithFiveRetriableErrorsCustomRetry() {
testEc2CredsWithRetriableErrorsCustomRetry(5);
}
@Test
public void testEc2CredsWithSixRetriableErrorsCustomRetry_ThrowsException() {
int numExceptions = 6;
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put("awsMaxRetries", "5");
AWSCredentialsProvider mockEc2CredsProvider = setupMockDefaultProviderWithRetriableExceptions(numExceptions);
MSKCredentialProvider provider = new MSKCredentialProvider(optionsMap) {
protected AWSCredentialsProviderChain getDefaultProvider() {
return new AWSCredentialsProviderChain(mockEc2CredsProvider);
}
};
assertFalse(provider.getShouldDebugCreds());
assertThrows(SdkClientException.class, () -> provider.getCredentials());
Mockito.verify(mockEc2CredsProvider, times(numExceptions)).getCredentials();
Mockito.verifyNoMoreInteractions(mockEc2CredsProvider);
}
@Test
public void testEc2CredsWithOnrRetriableErrorsCustomZeroRetry_ThrowsException() {
int numExceptions = 1;
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put("awsMaxRetries", "0");
AWSCredentialsProvider mockEc2CredsProvider = setupMockDefaultProviderWithRetriableExceptions(numExceptions);
MSKCredentialProvider provider = new MSKCredentialProvider(optionsMap) {
protected AWSCredentialsProviderChain getDefaultProvider() {
return new AWSCredentialsProviderChain(mockEc2CredsProvider);
}
};
assertFalse(provider.getShouldDebugCreds());
assertThrows(SdkClientException.class, () -> provider.getCredentials());
Mockito.verify(mockEc2CredsProvider, times(numExceptions)).getCredentials();
Mockito.verifyNoMoreInteractions(mockEc2CredsProvider);
}
private void testEc2CredsWithRetriableErrorsCustomRetry(int numExceptions) {
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put("awsMaxRetries", "5");
AWSCredentialsProvider mockEc2CredsProvider = setupMockDefaultProviderWithRetriableExceptions(numExceptions);
MSKCredentialProvider provider = new MSKCredentialProvider(optionsMap) {
protected AWSCredentialsProviderChain getDefaultProvider() {
return new AWSCredentialsProviderChain(mockEc2CredsProvider);
}
};
assertFalse(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
validateBasicCredentialsTwo(credentials);
provider.close();
Mockito.verify(mockEc2CredsProvider, times(numExceptions + 1)).getCredentials();
Mockito.verifyNoMoreInteractions(mockEc2CredsProvider);
}
private void testRoleCredsWithRetriableErrors(int numExceptions) {
STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = setupMockStsRoleCredentialsProviderWithRetriableExceptions(
numExceptions);
Map<String, String> optionsMap = new HashMap<>();
optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN);
MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilder(mockStsRoleProvider, optionsMap,
"aws-msk-iam-auth");
MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder) {
protected AWSCredentialsProviderChain getDefaultProvider() {
return new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider());
}
};
assertFalse(provider.getShouldDebugCreds());
AWSCredentials credentials = provider.getCredentials();
validateBasicSessionCredentials(credentials);
provider.close();
Mockito.verify(mockStsRoleProvider, times(numExceptions + 1)).getCredentials();
Mockito.verify(mockStsRoleProvider, times(1)).close();
Mockito.verifyNoMoreInteractions(mockStsRoleProvider);
}
private MSKCredentialProvider.ProviderBuilder getProviderBuilder(STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider,
Map<String, String> optionsMap, String s) {
return new MSKCredentialProvider.ProviderBuilder(optionsMap) {
STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn,
String sessionName, String stsRegion) {
assertEquals(TEST_ROLE_ARN, roleArn);
assertEquals(s, sessionName);
return mockStsRoleProvider;
}
};
}
private MSKCredentialProvider.ProviderBuilder getProviderBuilderWithCredentials(STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider,
Map<String, String> optionsMap, String s) {
return new MSKCredentialProvider.ProviderBuilder(optionsMap) {
STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn,
String sessionName, String stsRegion,
AWSCredentialsProvider credentials) {
assertEquals(TEST_ROLE_ARN, roleArn);
assertEquals(s, sessionName);
return mockStsRoleProvider;
}
};
}
private void validateBasicSessionCredentials(AWSCredentials credentials) {
assertTrue(credentials instanceof BasicSessionCredentials);
BasicSessionCredentials sessionCredentials = (BasicSessionCredentials) credentials;
assertEquals(ACCESS_KEY_VALUE, sessionCredentials.getAWSAccessKeyId());
assertEquals(SECRET_KEY_VALUE, sessionCredentials.getAWSSecretKey());
assertEquals(SESSION_TOKEN, sessionCredentials.getSessionToken());
}
private void validateBasicSessionCredentialsTwo(AWSCredentials credentials) {
assertTrue(credentials instanceof BasicSessionCredentials);
BasicSessionCredentials sessionCredentials = (BasicSessionCredentials) credentials;
assertEquals(ACCESS_KEY_VALUE_TWO, sessionCredentials.getAWSAccessKeyId());
assertEquals(SECRET_KEY_VALUE_TWO, sessionCredentials.getAWSSecretKey());
assertEquals(SESSION_TOKEN, sessionCredentials.getSessionToken());
}
private void validateBasicCredentialsTwo(AWSCredentials credentials) {
assertTrue(credentials instanceof BasicAWSCredentials);
assertEquals(ACCESS_KEY_VALUE_TWO, credentials.getAWSAccessKeyId());
assertEquals(SECRET_KEY_VALUE_TWO, credentials.getAWSSecretKey());
}
private STSAssumeRoleSessionCredentialsProvider setupMockStsRoleCredentialsProviderWithRetriableExceptions(int numErrors) {
SdkBaseException[] exceptionsToThrow = getSdkBaseExceptions(numErrors);
STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito
.mock(STSAssumeRoleSessionCredentialsProvider.class);
Mockito.when(mockStsRoleProvider.getCredentials())
.thenThrow(exceptionsToThrow)
.thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN));
return mockStsRoleProvider;
}
private SdkBaseException[] getSdkBaseExceptions(int numErrors) {
final SdkBaseException exceptionFromProvider = new SdkClientException("TEST TEST TEST");
return IntStream.range(0, numErrors).mapToObj(i -> exceptionFromProvider)
.collect(Collectors.toList()).toArray(new SdkBaseException[numErrors]);
}
private AWSCredentialsProvider setupMockDefaultProviderWithRetriableExceptions(int numErrors) {
SdkBaseException[] exceptionsToThrow = getSdkBaseExceptions(numErrors);
EC2ContainerCredentialsProviderWrapper mockEc2Provider = Mockito.mock(EC2ContainerCredentialsProviderWrapper.class);
Mockito.when(mockEc2Provider.getCredentials())
.thenThrow(exceptionsToThrow)
.thenReturn(new BasicAWSCredentials(ACCESS_KEY_VALUE_TWO, SECRET_KEY_VALUE_TWO));
return mockEc2Provider;
}
private ProfileFile getProfileFile() {
return ProfileFile.builder().content(new File(getProfileResourceURL().getFile()).toPath()).type(
ProfileFile.Type.CREDENTIALS).build();
}
private URL getProfileResourceURL() {
return getClass().getClassLoader().getResource("profile_config_file");
}
}
| 8,984 |
0 |
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/AuthenticateRequestParamsTest.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class AuthenticateRequestParamsTest {
private static final String VALID_HOSTNAME = "b-3.unit-test.abcdef.kafka.us-west-2.amazonaws.com";
private static final String HOSTNAME_NO_REGION = "abcd.efgh.com";
private AWSCredentials credentials;
private static final String ACCESS_KEY = "ACCESS_KEY";
private static final String SECRET_KEY = "SECRET_KEY";
private static final String USER_AGENT = "USER_AGENT";
private static final Region TEST_EC2_REGION = Region.getRegion(Regions.US_WEST_1);
@BeforeEach
public void setup() {
credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
}
@Test
public void testAllProperties() {
AuthenticationRequestParams params = AuthenticationRequestParams
.create(VALID_HOSTNAME, credentials, USER_AGENT);
assertEquals("us-west-2", params.getRegion().getName());
assertEquals("kafka-cluster", params.getServiceScope());
assertEquals(USER_AGENT, params.getUserAgent());
assertEquals(VALID_HOSTNAME, params.getHost());
assertEquals(ACCESS_KEY, params.getAwsCredentials().getAWSAccessKeyId());
assertEquals(SECRET_KEY, params.getAwsCredentials().getAWSSecretKey());
}
@Test
public void testInvalidHost() {
try (MockedStatic<Regions> regionsMockedStatic = Mockito.mockStatic(Regions.class)) {
regionsMockedStatic.when(Regions::getCurrentRegion).thenReturn(null);
assertThrows(IllegalArgumentException.class,
() -> AuthenticationRequestParams.create(HOSTNAME_NO_REGION, credentials, USER_AGENT));
}
}
@Test
public void testInvalidHostInEC2() {
try (MockedStatic<Regions> regionsMockedStatic = Mockito.mockStatic(Regions.class)) {
regionsMockedStatic.when(Regions::getCurrentRegion).thenReturn(TEST_EC2_REGION);
AuthenticationRequestParams params = AuthenticationRequestParams.create(HOSTNAME_NO_REGION, credentials, USER_AGENT);
assertEquals(TEST_EC2_REGION, params.getRegion());
}
}
}
| 8,985 |
0 |
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/SystemPropertyCredentialsUtils.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
public final class SystemPropertyCredentialsUtils {
private static final String ACCESS_KEY_PROPERTY = "aws.accessKeyId";
private static final String SECRET_KEY_PROPERTY = "aws.secretKey";
private static final String AWS_PROFILE_SYSTEM_PROPERTY = "aws.profile";
private SystemPropertyCredentialsUtils() {
}
public static void runTestWithSystemPropertyCredentials(Runnable test,
String accessKeyValue,
String secretKeyValue) {
String initialAccessKey = System.getProperty(ACCESS_KEY_PROPERTY);
String initialSecretKey = System.getProperty(SECRET_KEY_PROPERTY);
try {
//Setup test system properties
System.setProperty(ACCESS_KEY_PROPERTY, accessKeyValue);
System.setProperty(SECRET_KEY_PROPERTY, secretKeyValue);
test.run();
} finally {
if (initialAccessKey != null) {
System.setProperty(ACCESS_KEY_PROPERTY, initialAccessKey);
}
if (initialSecretKey != null) {
System.setProperty(SECRET_KEY_PROPERTY, initialSecretKey);
}
}
}
public static void runTestWithSystemPropertyProfile(Runnable test,
String profileName) {
String initialProfileName = System.getProperty(AWS_PROFILE_SYSTEM_PROPERTY);
try {
//Setup test system properties
System.setProperty(AWS_PROFILE_SYSTEM_PROPERTY, profileName);
runTestWithSystemPropertyCredentials( test, "", "");
} finally {
if (initialProfileName != null) {
System.setProperty(AWS_PROFILE_SYSTEM_PROPERTY, initialProfileName);
}
}
}
}
| 8,986 |
0 |
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/AWS4SignedPayloadGeneratorTest.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.text.ParseException;
public class AWS4SignedPayloadGeneratorTest {
private static final String VALID_HOSTNAME = "b-3.unit-test.abcdef.kafka.us-west-2.amazonaws.com";
private static final String ACCESS_KEY = "ACCESS_KEY";
private static final String SECRET_KEY = "SECRET_KEY";
private static final String USER_AGENT = "USER_AGENT";
private AWSCredentials credentials;
@BeforeEach
public void setup() {
credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
}
@Test
public void testSigning() throws IOException, ParseException {
AuthenticationRequestParams params = AuthenticationRequestParams
.create(VALID_HOSTNAME, credentials, UserAgentUtils.getUserAgentValue());
AWS4SignedPayloadGenerator generator = new AWS4SignedPayloadGenerator();
byte[] signedPayload = generator.signedPayload(params);
assertNotNull(signedPayload);
SignedPayloadValidatorUtils.validatePayload(signedPayload, params);
}
}
| 8,987 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/IAMOAuthBearerLoginCallbackHandler.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.AppConfigurationEntry;
import org.apache.kafka.common.security.auth.AuthenticateCallbackHandler;
import org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule;
import org.apache.kafka.common.security.oauthbearer.OAuthBearerToken;
import org.apache.kafka.common.security.oauthbearer.OAuthBearerTokenCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.DefaultRequest;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import lombok.NonNull;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.providers.AwsRegionProvider;
import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain;
import software.amazon.msk.auth.iam.internals.AWS4SignedPayloadGenerator;
import software.amazon.msk.auth.iam.internals.AuthenticationRequestParams;
import software.amazon.msk.auth.iam.internals.MSKCredentialProvider;
import software.amazon.msk.auth.iam.internals.UserAgentUtils;
/**
* This login callback handler is used to extract base64 encoded signed url as an auth token.
* The credentials are based on JaasConfig options passed to {@link OAuthBearerLoginModule}.
* If config options are provided the {@link MSKCredentialProvider} is used.
* If no config options are provided it uses the DefaultAWSCredentialsProviderChain.
*/
public class IAMOAuthBearerLoginCallbackHandler implements AuthenticateCallbackHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(IAMOAuthBearerLoginCallbackHandler.class);
private static final String PROTOCOL = "https";
private static final String USER_AGENT_KEY = "User-Agent";
private final AWS4SignedPayloadGenerator aws4Signer = new AWS4SignedPayloadGenerator();
private AWSCredentialsProvider credentialsProvider;
private AwsRegionProvider awsRegionProvider;
private boolean configured = false;
/**
* Return true if this instance has been configured, otherwise false.
*/
public boolean configured() {
return configured;
}
@Override
public void configure(Map<String, ?> configs,
@NonNull String saslMechanism,
@NonNull List<AppConfigurationEntry> jaasConfigEntries) {
if (!OAuthBearerLoginModule.OAUTHBEARER_MECHANISM.equals(saslMechanism)) {
throw new IllegalArgumentException(String.format("Unexpected SASL mechanism: %s", saslMechanism));
}
final Optional<AppConfigurationEntry> configEntry = jaasConfigEntries.stream()
.filter(j -> OAuthBearerLoginModule.class.getCanonicalName()
.equals(j.getLoginModuleName()))
.findFirst();
credentialsProvider = configEntry.map(c -> (AWSCredentialsProvider) new MSKCredentialProvider(c.getOptions()))
.orElse(DefaultAWSCredentialsProviderChain.getInstance());
awsRegionProvider = new DefaultAwsRegionProviderChain();
configured = true;
}
@Override
public void close() {
try {
if (credentialsProvider instanceof AutoCloseable) {
((AutoCloseable) credentialsProvider).close();
}
} catch (Exception e) {
LOGGER.warn("Error closing provider", e);
}
}
@Override
public void handle(@NonNull Callback[] callbacks) throws IOException, UnsupportedCallbackException {
if (!configured()) {
throw new IllegalStateException("Callback handler not configured");
}
for (Callback callback : callbacks) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Type information for callback: " + debugClassString(callback.getClass()) + " from "
+ debugClassString(this.getClass()));
}
if (callback instanceof OAuthBearerTokenCallback) {
try {
handleCallback((OAuthBearerTokenCallback) callback);
} catch (ParseException | URISyntaxException e) {
throw new MalformedURLException(e.getMessage());
}
} else {
String message = "Unsupported callback type: " + debugClassString(callback.getClass()) + " from "
+ debugClassString(this.getClass());
throw new UnsupportedCallbackException(callback, message);
}
}
}
private void handleCallback(OAuthBearerTokenCallback callback) throws IOException, URISyntaxException, ParseException {
if (callback.token() != null) {
throw new IllegalArgumentException("Callback had a token already");
}
AWSCredentials awsCredentials = credentialsProvider.getCredentials();
// Generate token value i.e. Base64 encoded pre-signed URL string
String tokenValue = generateTokenValue(awsCredentials, getCurrentRegion());
// Set OAuth token
callback.token(getOAuthBearerToken(tokenValue));
}
/**
* Generates base64 encoded signed url based on IAM credentials provided
*
* @param awsCredentials aws credentials object
* @param region aws region
* @return a base64 encoded token string
*/
private String generateTokenValue(@NonNull final AWSCredentials awsCredentials, @NonNull final Region region) {
final String userAgentValue = UserAgentUtils.getUserAgentValue();
final AuthenticationRequestParams authenticationRequestParams = AuthenticationRequestParams
.create(getHostName(region), awsCredentials, userAgentValue);
final DefaultRequest request = aws4Signer.presignRequest(authenticationRequestParams);
request.addParameter(USER_AGENT_KEY, userAgentValue);
final SdkHttpFullRequest fullRequest = convertToSdkHttpFullRequest(request);
String signedUrl = fullRequest.getUri()
.toString();
return Base64.getUrlEncoder()
.withoutPadding()
.encodeToString(signedUrl.getBytes(StandardCharsets.UTF_8));
}
/**
* Builds hostname string
*
* @param region aws region
* @return hostname
*/
private String getHostName(final Region region) {
return String.format("kafka.%s.amazonaws.com", region.toString());
}
/**
* Gets current aws region from metadata
*
* @return aws region object
* @throws IOException
*/
private Region getCurrentRegion() throws IOException {
try {
return awsRegionProvider.getRegion();
} catch (SdkClientException exception) {
throw new IOException("AWS region could not be resolved.");
}
}
/**
* Constructs OAuthBearerToken object as required by OAuthModule
*
* @param token base64 encoded token
* @return
*/
private OAuthBearerToken getOAuthBearerToken(final String token) throws URISyntaxException, ParseException {
return new IAMOAuthBearerToken(token);
}
static String debugClassString(Class<?> clazz) {
return "class: " + clazz.getName() + " classloader: " + clazz.getClassLoader().toString();
}
/**
* Converts the DefaultRequest object to a http request object from aws sdk.
*
* @param defaultRequest pre-signed request object
* @return
*/
private SdkHttpFullRequest convertToSdkHttpFullRequest(DefaultRequest<? extends AmazonWebServiceRequest> defaultRequest) {
final SdkHttpMethod httpMethod = SdkHttpMethod.valueOf(defaultRequest.getHttpMethod().name());
String endpoint = defaultRequest.getEndpoint().toString();
final SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder()
.method(httpMethod)
.protocol(PROTOCOL) // Replace Protocol with 'https://' since 'kafka://' fails for not being recognized as a valid scheme by builder
.encodedPath(defaultRequest.getResourcePath())
.host(endpoint.substring(endpoint.indexOf("://") + 3)); // Extract hostname e.g. 'kafka://kafka.us-west-1.amazonaws.com' => 'kafka.us-west-1.amazonaws.com'
defaultRequest.getHeaders()
.forEach((key, value) -> requestBuilder.appendHeader(key, value));
defaultRequest.getParameters()
.forEach((key, value) -> requestBuilder.appendRawQueryParameter(key, value.get(0)));
return requestBuilder.build();
}
}
| 8,988 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/IAMLoginModule.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam;
import software.amazon.msk.auth.iam.internals.ClassLoaderAwareIAMSaslClientProvider;
import software.amazon.msk.auth.iam.internals.IAMSaslClientProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import java.util.Map;
/**
* This Login Module is used to register the {@link IAMSaslClientProvider}.
* The module is a no-op for other purposes.
*/
public class IAMLoginModule implements LoginModule {
public static final String MECHANISM = "AWS_MSK_IAM";
private static final Logger log = LoggerFactory.getLogger(IAMLoginModule.class);
static {
ClassLoaderAwareIAMSaslClientProvider.initialize();
IAMSaslClientProvider.initialize();
}
@Override
public void initialize(Subject subject,
CallbackHandler callbackHandler,
Map<String, ?> sharedState,
Map<String, ?> options) {
if (log.isDebugEnabled()) {
log.debug("IAMLoginModule initialized");
}
}
@Override
public boolean login() throws LoginException {
return true;
}
@Override
public boolean commit() throws LoginException {
return true;
}
@Override
public boolean abort() throws LoginException {
return false;
}
@Override
public boolean logout() throws LoginException {
return true;
}
}
| 8,989 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/IAMClientCallbackHandler.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import software.amazon.msk.auth.iam.internals.AWSCredentialsCallback;
import software.amazon.msk.auth.iam.internals.MSKCredentialProvider;
import lombok.NonNull;
import org.apache.kafka.common.security.auth.AuthenticateCallbackHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.AppConfigurationEntry;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* This client callback handler is used to extract AWSCredentials.
* The credentials are based on JaasConfig options passed to {@link IAMLoginModule}.
* If config options are provided the {@link MSKCredentialProvider} is used.
* If no config options are provided it uses the DefaultAWSCredentialsProviderChain.
*/
public class IAMClientCallbackHandler implements AuthenticateCallbackHandler {
private static final Logger log = LoggerFactory.getLogger(IAMClientCallbackHandler.class);
private AWSCredentialsProvider provider;
@Override
public void configure(Map<String, ?> configs,
@NonNull String saslMechanism,
@NonNull List<AppConfigurationEntry> jaasConfigEntries) {
if (!IAMLoginModule.MECHANISM.equals(saslMechanism)) {
throw new IllegalArgumentException("Unexpected SASL mechanism: " + saslMechanism);
}
final Optional<AppConfigurationEntry> configEntry = jaasConfigEntries.stream()
.filter(j -> IAMLoginModule.class.getCanonicalName().equals(j.getLoginModuleName())).findFirst();
provider = configEntry.map(c -> (AWSCredentialsProvider) new MSKCredentialProvider(c.getOptions()))
.orElse(DefaultAWSCredentialsProviderChain.getInstance());
}
@Override
public void close() {
try {
if (provider instanceof AutoCloseable) {
((AutoCloseable) provider).close();
}
} catch (Exception e) {
log.warn("Error closing provider", e);
}
}
@Override
public void handle(@NonNull Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (log.isDebugEnabled()) {
log.debug("Type information for callback: " + debugClassString(callback.getClass()) + " from "
+ debugClassString(this.getClass()));
}
if (callback instanceof AWSCredentialsCallback) {
handleCallback((AWSCredentialsCallback) callback);
} else {
String message = "Unsupported callback type: " + debugClassString(callback.getClass()) + " from "
+ debugClassString(this.getClass());
//We are breaking good practice and logging as well as throwing since this is where client side
//integrations might have trouble. Depending on the client framework either logging or throwing might
//surface the error more easily to the user.
log.error(message);
throw new UnsupportedCallbackException(callback, message);
}
}
}
protected static String debugClassString(Class<?> clazz) {
return "class: " + clazz.getName() + " classloader: " + clazz.getClassLoader().toString();
}
protected void handleCallback(AWSCredentialsCallback callback) throws IOException {
if (log.isDebugEnabled()) {
log.debug("Selecting provider {} to load credentials", provider.getClass().getName());
}
try {
provider.refresh();
callback.setAwsCredentials(provider.getCredentials());
} catch (Exception e) {
callback.setLoadingException(e);
}
}
}
| 8,990 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/IAMOAuthBearerToken.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.kafka.common.security.oauthbearer.OAuthBearerToken;
import com.amazonaws.auth.internal.SignerConstants;
import software.amazon.awssdk.utils.StringUtils;
/**
* Implements the contract provided by OAuthBearerToken interface
*/
public class IAMOAuthBearerToken implements OAuthBearerToken {
private static final String SIGNING_NAME = "kafka-cluster";
private final String value;
private final long lifetimeMs;
private final long startTimeMs;
// Used for testing
IAMOAuthBearerToken(String token, long lifeTimeSeconds) {
this.value = token;
this.startTimeMs = System.currentTimeMillis();
this.lifetimeMs = this.startTimeMs + (lifeTimeSeconds * 1000);
}
public IAMOAuthBearerToken(String token) throws URISyntaxException {
if(StringUtils.isEmpty(token)) {
throw new IllegalArgumentException("Token can not be empty");
}
this.value = token;
byte[] tokenBytes = token.getBytes(StandardCharsets.UTF_8);
byte[] decodedBytes = Base64.getUrlDecoder().decode(tokenBytes);
final String decodedPresignedUrl = new String(decodedBytes, StandardCharsets.UTF_8);
final URI uri = new URI(decodedPresignedUrl);
List<NameValuePair> params = URLEncodedUtils.parse(uri, StandardCharsets.UTF_8);
Map<String, String> paramMap = params.stream()
.collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));
int lifeTimeSeconds = Integer.parseInt(paramMap.get(SignerConstants.X_AMZ_EXPIRES));
final DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'");
final LocalDateTime signedDate = LocalDateTime.parse(paramMap.get(SignerConstants.X_AMZ_DATE), dateFormat);
long signedDateEpochMillis = signedDate.toInstant(ZoneOffset.UTC)
.toEpochMilli();
this.startTimeMs = signedDateEpochMillis;
this.lifetimeMs = this.startTimeMs + (lifeTimeSeconds * 1000L);
}
@Override
public String value() {
return this.value;
}
@Override
public Set<String> scope() {
return Collections.emptySet();
}
@Override
public long lifetimeMs() {
return this.lifetimeMs;
}
@Override
public String principalName() {
return SIGNING_NAME;
}
@Override
public Long startTimeMs() {
return this.startTimeMs;
}
}
| 8,991 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/MSKCredentialProvider.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import com.amazonaws.SdkBaseException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSCredentialsProviderChain;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.auth.EC2ContainerCredentialsProviderWrapper;
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
import com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider;
import com.amazonaws.auth.SystemPropertiesCredentialsProvider;
import com.amazonaws.auth.WebIdentityTokenCredentialsProvider;
import com.amazonaws.retry.PredefinedBackoffStrategies;
import com.amazonaws.retry.v2.AndRetryCondition;
import com.amazonaws.retry.v2.MaxNumberOfRetriesCondition;
import com.amazonaws.retry.v2.RetryOnExceptionsCondition;
import com.amazonaws.retry.v2.RetryPolicy;
import com.amazonaws.retry.v2.RetryPolicyContext;
import com.amazonaws.retry.v2.SimpleRetryPolicy;
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder;
import com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest;
import com.amazonaws.services.securitytoken.model.GetCallerIdentityResult;
import lombok.AccessLevel;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* This AWS Credential Provider is used to load up AWS Credentials based on options provided on the Jaas config line.
* As as an example
* sasl.jaas.config = IAMLoginModule required awsProfileName={profile name};
* The currently supported options are:
* 1. A particular AWS Credential profile: awsProfileName={profile name}
* 2. A particular AWS IAM Role, with optional access key id, secret key and session token OR optional external id,
* and optionally AWS IAM role session name and AWS region for the STS endpoint:
* awsRoleArn={IAM Role ARN}, awsRoleAccessKeyId={access key id}, awsRoleSecretAccessKey={secret access key},
* awsRoleSessionToken={session token}, awsRoleSessionName={session name}, awsStsRegion={region name}
* 3. Optional arguments to configure retries when we fail to load credentials:
* awsMaxRetries={Maximum number of retries}, awsMaxBackOffTimeMs={Maximum back off time between retries in ms}
* 4. Optional argument to help debug credentials used to establish connections:
* awsDebugCreds={true|false}
* 5. If no options is provided, the DefaultAWSCredentialsProviderChain is used.
* The DefaultAWSCredentialProviderChain can be pointed to credentials in many different ways:
* <a href="https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html">Working with AWS Credentials</a>
*/
public class MSKCredentialProvider implements AWSCredentialsProvider, AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(MSKCredentialProvider.class);
private static final String AWS_PROFILE_NAME_KEY = "awsProfileName";
private static final String AWS_ROLE_ARN_KEY = "awsRoleArn";
private static final String AWS_ROLE_EXTERNAL_ID = "awsRoleExternalId";
private static final String AWS_ROLE_ACCESS_KEY_ID = "awsRoleAccessKeyId";
private static final String AWS_ROLE_SECRET_ACCESS_KEY = "awsRoleSecretAccessKey";
private static final String AWS_ROLE_SESSION_KEY = "awsRoleSessionName";
private static final String AWS_ROLE_SESSION_TOKEN = "awsRoleSessionToken";
private static final String AWS_STS_REGION = "awsStsRegion";
private static final String AWS_DEBUG_CREDS_KEY = "awsDebugCreds";
private static final String AWS_MAX_RETRIES = "awsMaxRetries";
private static final String AWS_MAX_BACK_OFF_TIME_MS = "awsMaxBackOffTimeMs";
private static final int DEFAULT_MAX_RETRIES = 3;
private static final int DEFAULT_MAX_BACK_OFF_TIME_MS = 5000;
private static final int BASE_DELAY = 500;
private final List<AutoCloseable> closeableProviders;
private final AWSCredentialsProvider compositeDelegate;
@Getter(AccessLevel.PACKAGE)
private final Boolean shouldDebugCreds;
private final String stsRegion;
private final RetryPolicy retryPolicy;
public MSKCredentialProvider(Map<String, ?> options) {
this(new ProviderBuilder(options));
}
MSKCredentialProvider(ProviderBuilder builder) {
this(builder.getProviders(), builder.shouldDebugCreds(), builder.getStsRegion(), builder.getMaxRetries(),
builder.getMaxBackOffTimeMs());
}
MSKCredentialProvider(List<AWSCredentialsProvider> providers,
Boolean shouldDebugCreds,
String stsRegion,
int maxRetries,
int maxBackOffTimeMs) {
List<AWSCredentialsProvider> delegateList = new ArrayList<>(providers);
delegateList.add(getDefaultProvider());
compositeDelegate = new AWSCredentialsProviderChain(delegateList);
closeableProviders = providers.stream().filter(p -> p instanceof AutoCloseable).map(p -> (AutoCloseable) p)
.collect(Collectors.toList());
this.shouldDebugCreds = shouldDebugCreds;
this.stsRegion = stsRegion;
if (maxRetries > 0) {
this.retryPolicy = new SimpleRetryPolicy(
new AndRetryCondition(new RetryOnExceptionsCondition(Collections.singletonList(
SdkClientException.class)), new MaxNumberOfRetriesCondition(maxRetries)),
new PredefinedBackoffStrategies.FullJitterBackoffStrategy(BASE_DELAY, maxBackOffTimeMs));
} else {
this.retryPolicy = new SimpleRetryPolicy((c) -> false,
new PredefinedBackoffStrategies.FullJitterBackoffStrategy(BASE_DELAY, maxBackOffTimeMs));
}
}
//We want to override the ProfileCredentialsProvider with the EnhancedProfileCredentialsProvider
protected AWSCredentialsProviderChain getDefaultProvider() {
return new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider(),
new SystemPropertiesCredentialsProvider(),
WebIdentityTokenCredentialsProvider.create(),
new EnhancedProfileCredentialsProvider(),
new EC2ContainerCredentialsProviderWrapper());
}
@Override
public AWSCredentials getCredentials() {
AWSCredentials credentials = loadCredentialsWithRetry();
if (credentials != null && shouldDebugCreds && log.isDebugEnabled()) {
logCallerIdentity(credentials);
}
return credentials;
}
private AWSCredentials loadCredentialsWithRetry() {
RetryPolicyContext retryPolicyContext = RetryPolicyContext.builder().build();
boolean shouldTry = true;
try {
while (shouldTry) {
try {
AWSCredentials credentials = compositeDelegate.getCredentials();
if (credentials == null) {
throw new SdkClientException("Composite delegate returned empty credentials.");
}
return credentials;
} catch (SdkBaseException se) {
log.warn("Exception loading credentials. Retry Attempts: {}",
retryPolicyContext.retriesAttempted(), se);
retryPolicyContext = createRetryPolicyContext(se, retryPolicyContext.retriesAttempted());
shouldTry = retryPolicy.shouldRetry(retryPolicyContext);
if (shouldTry) {
Thread.sleep(retryPolicy.computeDelayBeforeNextRetry(retryPolicyContext));
retryPolicyContext = createRetryPolicyContext(retryPolicyContext.exception(),
retryPolicyContext.retriesAttempted() + 1);
} else {
throw se;
}
}
}
throw new SdkClientException(
"loadCredentialsWithRetry in unexpected location " + retryPolicyContext.totalRequests(),
retryPolicyContext.exception());
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while waiting for credentials.", ie);
}
}
private RetryPolicyContext createRetryPolicyContext(SdkBaseException sdkException, int retriesAttempted) {
return RetryPolicyContext.builder().exception(sdkException)
.retriesAttempted(retriesAttempted).build();
}
private void logCallerIdentity(AWSCredentials credentials) {
try {
AWSSecurityTokenService stsClient = getStsClientForDebuggingCreds(credentials);
GetCallerIdentityResult response = stsClient.getCallerIdentity(new GetCallerIdentityRequest());
log.debug("The identity of the credentials is {}", response.toString());
} catch (Exception e) {
//If we run into an exception logging the caller identity, we should log the exception but
//continue running.
log.warn("Error identifying caller identity. If this is not transient, does this application have"
+ "access to AWS STS?", e);
}
}
AWSSecurityTokenService getStsClientForDebuggingCreds(AWSCredentials credentials) {
return AWSSecurityTokenServiceClientBuilder.standard()
.withRegion(stsRegion)
.withCredentials(new AWSCredentialsProvider() {
@Override
public AWSCredentials getCredentials() {
return credentials;
}
@Override
public void refresh() {
}
})
.build();
}
@Override
public void refresh() {
compositeDelegate.refresh();
}
@Override
public void close() {
closeableProviders.stream().forEach(p -> {
try {
p.close();
} catch (Exception e) {
log.warn("Error closing credential provider", e);
}
});
}
public static class ProviderBuilder {
private final Map<String, ?> optionsMap;
public ProviderBuilder(Map<String, ?> optionsMap) {
this.optionsMap = optionsMap;
if (log.isDebugEnabled()) {
log.debug("Number of options to configure credential provider {}", optionsMap.size());
}
}
public List<AWSCredentialsProvider> getProviders() {
List<AWSCredentialsProvider> providers = new ArrayList<>();
getProfileProvider().ifPresent(providers::add);
getStsRoleProvider().ifPresent(providers::add);
return providers;
}
public Boolean shouldDebugCreds() {
return Optional.ofNullable(optionsMap.get(AWS_DEBUG_CREDS_KEY)).map(d -> d.equals("true")).orElse(false);
}
public String getStsRegion() {
return Optional.ofNullable((String) optionsMap.get(AWS_STS_REGION))
.orElse("aws-global");
}
public int getMaxRetries() {
return Optional.ofNullable(optionsMap.get(AWS_MAX_RETRIES)).map(p -> (String) p).map(Integer::parseInt)
.orElse(DEFAULT_MAX_RETRIES);
}
public int getMaxBackOffTimeMs() {
return Optional.ofNullable(optionsMap.get(AWS_MAX_BACK_OFF_TIME_MS)).map(p -> (String) p)
.map(Integer::parseInt)
.orElse(DEFAULT_MAX_BACK_OFF_TIME_MS);
}
private Optional<EnhancedProfileCredentialsProvider> getProfileProvider() {
return Optional.ofNullable(optionsMap.get(AWS_PROFILE_NAME_KEY)).map(p -> {
if (log.isDebugEnabled()) {
log.debug("Profile name {}", p);
}
return createEnhancedProfileCredentialsProvider((String) p);
});
}
EnhancedProfileCredentialsProvider createEnhancedProfileCredentialsProvider(String p) {
return new EnhancedProfileCredentialsProvider(p);
}
private Optional<STSAssumeRoleSessionCredentialsProvider> getStsRoleProvider() {
return Optional.ofNullable(optionsMap.get(AWS_ROLE_ARN_KEY)).map(p -> {
if (log.isDebugEnabled()) {
log.debug("Role ARN {}", p);
}
String sessionName = Optional.ofNullable((String) optionsMap.get(AWS_ROLE_SESSION_KEY))
.orElse("aws-msk-iam-auth");
String stsRegion = getStsRegion();
String accessKey = (String) optionsMap.getOrDefault(AWS_ROLE_ACCESS_KEY_ID, null);
String secretKey = (String) optionsMap.getOrDefault(AWS_ROLE_SECRET_ACCESS_KEY, null);
String sessionToken = (String) optionsMap.getOrDefault(AWS_ROLE_SESSION_TOKEN, null);
String externalId = (String) optionsMap.getOrDefault(AWS_ROLE_EXTERNAL_ID, null);
if (accessKey != null && secretKey != null) {
AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(
sessionToken != null
? new BasicSessionCredentials(accessKey, secretKey, sessionToken)
: new BasicAWSCredentials(accessKey, secretKey));
return createSTSRoleCredentialProvider((String) p, sessionName, stsRegion, credentials);
}
else if (externalId != null) {
return createSTSRoleCredentialProvider((String) p, externalId, sessionName, stsRegion);
}
return createSTSRoleCredentialProvider((String) p, sessionName, stsRegion);
});
}
STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn,
String sessionName, String stsRegion) {
AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
.withRegion(stsRegion)
.build();
return new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName)
.withStsClient(stsClient)
.build();
}
STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn,
String sessionName, String stsRegion,
AWSCredentialsProvider credentials) {
AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
.withRegion(stsRegion)
.withCredentials(credentials)
.build();
return new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName)
.withStsClient(stsClient)
.build();
}
STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn,
String externalId,
String sessionName,
String stsRegion) {
AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
.withRegion(stsRegion)
.build();
return new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName)
.withStsClient(stsClient)
.withExternalId(externalId)
.build();
}
}
}
| 8,992 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/ClassLoaderAwareIAMSaslClientProvider.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import software.amazon.msk.auth.iam.IAMLoginModule;
import software.amazon.msk.auth.iam.internals.IAMSaslClient.ClassLoaderAwareIAMSaslClientFactory;
import java.security.Provider;
import java.security.Security;
public class ClassLoaderAwareIAMSaslClientProvider extends Provider {
/**
* Constructs an IAM Sasl Client provider that installs a {@link ClassLoaderAwareIAMSaslClientFactory}.
*/
protected ClassLoaderAwareIAMSaslClientProvider() {
super("ClassLoader Aware SASL/IAM Client Provider", 1.0, "SASL/IAM Client Provider for Kafka");
put("SaslClientFactory." + IAMLoginModule.MECHANISM, ClassLoaderAwareIAMSaslClientFactory.class.getName());
}
public static void initialize() {
Security.addProvider(new ClassLoaderAwareIAMSaslClientProvider());
}
}
| 8,993 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/IAMSaslClientProvider.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import software.amazon.msk.auth.iam.internals.IAMSaslClient.IAMSaslClientFactory;
import java.security.Provider;
import java.security.Security;
import static software.amazon.msk.auth.iam.internals.IAMSaslClient.getMechanismNameForClassLoader;
public class IAMSaslClientProvider extends Provider {
/**
* Constructs a IAM Sasl Client provider with a fixed name, version number,
* and information.
*/
protected IAMSaslClientProvider() {
super("SASL/IAM Client Provider (" +
IAMSaslClientProvider.class.getClassLoader().hashCode(), 1.0,
") SASL/IAM Client Provider for Kafka");
put("SaslClientFactory." + getMechanismNameForClassLoader(getClass().getClassLoader()), IAMSaslClientFactory.class.getName());
}
public static void initialize() {
Security.addProvider(new IAMSaslClientProvider());
}
}
| 8,994 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/IAMSaslClient.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import software.amazon.msk.auth.iam.IAMClientCallbackHandler;
import software.amazon.msk.auth.iam.IAMLoginModule;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.NonNull;
import org.apache.kafka.common.errors.IllegalSaslStateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslClientFactory;
import javax.security.sasl.SaslException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
/**
* The IAMSaslClient is used to provide SASL integration with AWS IAM.
* It has an initial response, so it starts out in the state SEND_CLIENT_FIRST_MESSAGE.
* The initial response sent to the server contains an authentication payload.
* The authentication payload consists of a json object that includes a signature signed by the client's credentials.
* The exact details of the authentication payload can be seen in {@link AWS4SignedPayloadGenerator}.
* The credentials used to sign the payload are fetched by invoking the
* {@link IAMClientCallbackHandler}.
* After sending the authentication payload, the client transitions to state RECEIVE_SENDER_RESPONSE.
* Once it receives a successful response from the server, the client transitions to the state completed.
* A failure at any intermediate step transitions the client to a FAILED state.
*/
public class IAMSaslClient implements SaslClient {
private static final Logger log = LoggerFactory.getLogger(IAMSaslClient.class);
enum State {
SEND_CLIENT_FIRST_MESSAGE, RECEIVE_SERVER_RESPONSE, COMPLETE, FAILED
}
private final String mechanism;
private final CallbackHandler cbh;
private final String serverName;
private final SignedPayloadGenerator payloadGenerator;
private State state;
private String responseRequestId;
public IAMSaslClient(@NonNull String mechanism,
@NonNull CallbackHandler cbh,
@NonNull String serverName,
@NonNull SignedPayloadGenerator payloadGenerator) {
this.mechanism = mechanism;
this.cbh = cbh;
this.serverName = serverName;
this.payloadGenerator = payloadGenerator;
setState(State.SEND_CLIENT_FIRST_MESSAGE);
}
@Override
public String getMechanismName() {
return mechanism;
}
@Override
public boolean hasInitialResponse() {
return true;
}
@Override
public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
if (log.isDebugEnabled()) {
log.debug("State {} at start of evaluating challenge", state);
}
try {
switch (state) {
case SEND_CLIENT_FIRST_MESSAGE:
//For the initial response, the challenge should be empty.
if (!isChallengeEmpty(challenge)) {
throw new SaslException("Expects an empty challenge in state " + state);
}
return generateClientMessage();
case RECEIVE_SERVER_RESPONSE:
//we expect the successful server response to contain a non-empty challenge.
if (isChallengeEmpty(challenge)) {
throw new SaslException("Expects a non-empty authentication response in state " + state);
}
handleServerResponse(challenge);
//At this point, the authentication is complete.
setState(State.COMPLETE);
return null;
default:
throw new IllegalSaslStateException("Challenge received in unexpected state " + state);
}
} catch (SaslException se) {
setState(State.FAILED);
throw se;
} catch (IOException | IllegalArgumentException | UnsupportedCallbackException e) {
setState(State.FAILED);
throw new SaslException("Exception while evaluating challenge", e);
} finally {
if (log.isDebugEnabled()) {
log.debug("State {} at end of evaluating challenge", state);
}
}
}
private void handleServerResponse(byte[] challenge) throws IOException {
//If we got a non-empty server challenge, then the authentication succeeded on the server.
//Deserialize and log the server response as necessary.
ObjectMapper mapper = new ObjectMapper();
AuthenticationResponse response = mapper.readValue(challenge, AuthenticationResponse.class);
if (response == null) {
throw new SaslException("Invalid response from server ");
}
responseRequestId = response.getRequestId();
if (log.isDebugEnabled()) {
log.debug("Response from server: " + response.toString());
}
}
private byte[] generateClientMessage() throws IOException, UnsupportedCallbackException {
//Invoke the callback handler to fetch the credentials.
final AWSCredentialsCallback callback = new AWSCredentialsCallback();
cbh.handle(new Callback[] { callback });
if (callback.isSuccessful()) {
//Generate the signed payload
final byte[] response = payloadGenerator.signedPayload(
AuthenticationRequestParams
.create(serverName, callback.getAwsCredentials(), UserAgentUtils.getUserAgentValue()));
//transition to the state waiting to receive server response.
setState(State.RECEIVE_SERVER_RESPONSE);
return response;
} else {
throw new SaslException("Failed to find AWS IAM Credentials", callback.getLoadingException());
}
}
@Override
public boolean isComplete() {
return State.COMPLETE.equals(state);
}
@Override
public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException {
if (!isComplete()) {
throw new IllegalStateException("Authentication exchange has not completed");
}
return Arrays.copyOfRange(incoming, offset, offset + len);
}
@Override
public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException {
if (!isComplete()) {
throw new IllegalStateException("Authentication exchange has not completed");
}
return Arrays.copyOfRange(outgoing, offset, offset + len);
}
@Override
public Object getNegotiatedProperty(String propName) {
if (!isComplete()) {
throw new IllegalStateException("Authentication exchange has not completed");
}
return null;
}
@Override
public void dispose() throws SaslException {
}
public String getResponseRequestId() {
if (!isComplete()) {
throw new IllegalStateException("Authentication exchange has not completed");
}
return responseRequestId;
}
private void setState(State state) {
if (log.isDebugEnabled()) {
log.debug("Setting SASL/{} client state to {}", mechanism, state);
}
this.state = state;
}
private static boolean isChallengeEmpty(byte[] challenge) {
if (challenge != null && challenge.length > 0) {
return false;
}
return true;
}
public static class ClassLoaderAwareIAMSaslClientFactory implements SaslClientFactory {
@Override
public SaslClient createSaslClient(String[] mechanisms,
String authorizationId,
String protocol,
String serverName,
Map<String, ?> props,
CallbackHandler cbh) throws SaslException {
String mechanismName = getMechanismNameForClassLoader(cbh.getClass().getClassLoader());
// Create a client by delegating to the SaslClientFactory for the classloader of the CallbackHandler
return Sasl.createSaslClient(
new String[] { mechanismName },
authorizationId, protocol, serverName, props, cbh);
}
@Override
public String[] getMechanismNames(Map<String, ?> props) {
return new String[] { IAMLoginModule.MECHANISM };
}
}
public static class IAMSaslClientFactory implements SaslClientFactory {
@Override
public SaslClient createSaslClient(String[] mechanisms,
String authorizationId,
String protocol,
String serverName,
Map<String, ?> props,
CallbackHandler cbh) throws SaslException {
String mechanismName = getMechanismNameForClassLoader(getClass().getClassLoader());
for (String mechanism : mechanisms) {
if (mechanismName.equals(mechanism)) {
return new IAMSaslClient(mechanism, cbh, serverName, new AWS4SignedPayloadGenerator());
}
}
throw new SaslException(
"Requested mechanisms " + Arrays.asList(mechanisms) + " not supported. " +
"The supported mechanism is " + mechanismName);
}
@Override
public String[] getMechanismNames(Map<String, ?> props) {
return new String[] { getMechanismNameForClassLoader(getClass().getClassLoader()) };
}
}
public static String getMechanismNameForClassLoader(ClassLoader classLoader) {
return IAMLoginModule.MECHANISM + "." + classLoader.hashCode();
}
}
| 8,995 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/EnhancedProfileCredentialsProvider.java
|
package software.amazon.msk.auth.iam.internals;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.BasicSessionCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.profiles.ProfileFile;
/**
* This credential provider delegates to the v2 ProfileCredentialProvider so that users
* are able to use Single Sign On credentials and also get more standard credential loading
* behavior.
* See https://github.com/aws/aws-sdk-java/issues/803#issuecomment-593530484
*/
public class EnhancedProfileCredentialsProvider implements AWSCredentialsProvider {
private final ProfileCredentialsProvider delegate;
public EnhancedProfileCredentialsProvider() {
delegate = ProfileCredentialsProvider.create();
}
public EnhancedProfileCredentialsProvider(String profileName) {
delegate = ProfileCredentialsProvider.create(profileName);
}
public EnhancedProfileCredentialsProvider(ProfileFile profileFile, String profileName) {
delegate = ProfileCredentialsProvider.builder().profileFile(profileFile).profileName(profileName).build();
}
@Override
public AWSCredentials getCredentials() {
software.amazon.awssdk.auth.credentials.AwsCredentials credentialsV2 = delegate.resolveCredentials();
if (credentialsV2 instanceof AwsSessionCredentials) {
AwsSessionCredentials sessionCredentialsV2 = (AwsSessionCredentials) credentialsV2;
return new BasicSessionCredentials(sessionCredentialsV2.accessKeyId(),
sessionCredentialsV2.secretAccessKey(), sessionCredentialsV2.sessionToken());
}
return new BasicAWSCredentials(credentialsV2.accessKeyId(), credentialsV2.secretAccessKey());
}
@Override
public void refresh() {
}
}
| 8,996 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/AuthenticationResponse.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.NonNull;
import lombok.ToString;
/**
* This class is used to model the authentication response sent by the broker.
*/
@Getter(onMethod = @__(@JsonIgnore))
@ToString
public class AuthenticationResponse {
private static final String VERSION_1 = "2020_10_22";
private static final String VERSION_FIELD_NAME = "version";
private static final String REQUEST_ID_FIELD_NAME = "request-id";
@NonNull
@JsonProperty(VERSION_FIELD_NAME)
private final String version;
@JsonProperty(REQUEST_ID_FIELD_NAME)
@NonNull
private final String requestId;
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public AuthenticationResponse(@JsonProperty(VERSION_FIELD_NAME) String version,
@JsonProperty(REQUEST_ID_FIELD_NAME) String requestId) {
if (!VERSION_1.equals(version)) {
throw new IllegalArgumentException("Invalid version " + version);
}
this.version = version;
this.requestId = requestId;
}
}
| 8,997 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/AWS4SignedPayloadGenerator.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import com.amazonaws.DefaultRequest;
import com.amazonaws.auth.AWS4Signer;
import com.amazonaws.auth.internal.SignerConstants;
import com.amazonaws.http.HttpMethodName;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.NonNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Date;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
/**
* This class is used to generate the AWS Sigv4 signed authentication payload sent by the IAMSaslClient to the broker.
* It configures a AWSSigner based on the authentication request parameters. It generates a request with the endpoint
* set to the kafka broker (kafka:// as prefix), action set to kafka-cluster:Connect and the Http method as GET.
* It then pre-signs the request using the credentials in the authentication request parameters and a expiration period
* of 15 minutes. Afterwards, the signed request is converted into a key value map with headers and query parameters
* acting as keys. Then the key value map is serialized as a JSON object and returned as bytes.
*/
public class AWS4SignedPayloadGenerator implements SignedPayloadGenerator {
private static final Logger log = LoggerFactory.getLogger(AWS4SignedPayloadGenerator.class);
private static final String ACTION_KEY = "Action";
private static final String ACTION_VALUE = "kafka-cluster:Connect";
private static final String VERSION_KEY = "version";
private static final String USER_AGENT_KEY = "user-agent";
private static final int EXPIRY_DURATION_MINUTES = 15;
@Override
public byte[] signedPayload(@NonNull AuthenticationRequestParams params) throws PayloadGenerationException {
final DefaultRequest request = presignRequest(params);
try {
return toPayloadBytes(request, params);
} catch (IOException e) {
throw new PayloadGenerationException("Failure to create authentication payload ", e);
}
}
/**
* Presigns the request with AWS sigv4
*
* @param params authentication request parameters
* @return DefaultRequest object
*/
public DefaultRequest presignRequest(@NonNull AuthenticationRequestParams params) {
final AWS4Signer signer = getConfiguredSigner(params);
final DefaultRequest request = createRequestForSigning(params);
signer.presignRequest(request, params.getAwsCredentials(), getExpiryDate());
return request;
}
private DefaultRequest createRequestForSigning(AuthenticationRequestParams params) {
final DefaultRequest request = new DefaultRequest(params.getServiceScope());
request.setHttpMethod(HttpMethodName.GET);
try {
request.setEndpoint(new URI("kafka://" + params.getHost()));
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Failed to parse host URI", e);
}
request.addParameter(ACTION_KEY, ACTION_VALUE);
return request;
}
private java.util.Date getExpiryDate() {
return Date.from(Instant.ofEpochMilli(Instant.now().toEpochMilli() + TimeUnit.MINUTES.toMillis(
EXPIRY_DURATION_MINUTES)));
}
private AWS4Signer getConfiguredSigner(AuthenticationRequestParams params) {
final AWS4Signer aws4Signer = new AWS4Signer();
aws4Signer.setServiceName(params.getServiceScope());
aws4Signer.setRegionName(params.getRegion().getName());
if (log.isDebugEnabled()) {
log.debug("Signer configured for {} service and {} region", aws4Signer.getServiceName(),
aws4Signer.getRegionName());
}
return aws4Signer;
}
private byte[] toPayloadBytes(DefaultRequest request, AuthenticationRequestParams params) throws IOException {
final Map<String, String> keyValueMap = toKeyValueMap(request, params);
final ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsBytes(keyValueMap);
}
/**
* Convert the signed request into the map of key value strings that will be used to create the signed payload.
* It adds all the query parameters and headers in the request object as entries in the map of key value strings.
* It also adds the version of the AuthenticationRequestParams into the map of key value strings.
*
* @param request The signed request that contains the information to be converted into a key value map.
* @param params The authentication request parameters used to generate the signed request.
* @return A key value map containing the query parameters and headers from the signed request.
*/
private Map<String, String> toKeyValueMap(DefaultRequest request,
AuthenticationRequestParams params) {
final Map<String, String> keyValueMap = new HashMap<>();
final Set<Map.Entry<String, List<String>>> parameterEntries = request.getParameters().entrySet();
parameterEntries.stream().forEach(
e -> keyValueMap.put(e.getKey().toLowerCase(), generateParameterValue(e.getKey(), e.getValue())));
keyValueMap.put(VERSION_KEY, params.getVersion());
keyValueMap.put(USER_AGENT_KEY, params.getUserAgent());
//Add the headers.
final Set<Map.Entry<String, String>> headerEntries = request.getHeaders().entrySet();
headerEntries.stream().forEach(e -> keyValueMap.put(e.getKey().toLowerCase(), e.getValue()));
return keyValueMap;
}
/**
* Convert a query parameter value which is a list of strings into a single string.
* The values of all query parameters other than signed headers are expected to be a list of length 1 or 0.
* If the parameter value is of length 0, return an empty string.
* If the parameter value is of length 1, return the sole element.
* if the parameter value is longer than 1, join the list of string into a single string, separate by ";".
*
* @param key The name of the query parameter.
* @param value The list of strings that is the value of the query parameter.
* @return A single joined string.
*/
private String generateParameterValue(String key, List<String> value) {
if (value.isEmpty()) {
return "";
}
if (value.size() > 1) {
if (!SignerConstants.X_AMZ_SIGNED_HEADER.equals(key)) {
throw new IllegalArgumentException(
"Unexpected number of arguments " + value.size() + " for query parameter " + key);
}
final StringJoiner joiner = new StringJoiner(";");
value.stream().forEach(joiner::add);
return joiner.toString();
}
return value.get(0);
}
}
| 8,998 |
0 |
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
|
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/AWSCredentialsCallback.java
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 software.amazon.msk.auth.iam.internals;
import com.amazonaws.auth.AWSCredentials;
import lombok.Getter;
import lombok.NonNull;
import software.amazon.msk.auth.iam.IAMClientCallbackHandler;
import javax.security.auth.callback.Callback;
/**
* This class is used to pass AWSCredentials to the {@link IAMSaslClient}.
* It is processed by the {@link IAMClientCallbackHandler}.
* If the callback handler succeeds, it sets the AWSCredentials. If the callback handler fails to load the credentials,
* it sets the loading exception.
*/
public class AWSCredentialsCallback implements Callback {
@Getter
private AWSCredentials awsCredentials = null;
@Getter
private Exception loadingException = null;
public void setAwsCredentials(@NonNull AWSCredentials awsCredentials) {
this.awsCredentials = awsCredentials;
this.loadingException = null;
}
public void setLoadingException(@NonNull Exception loadingException) {
this.loadingException = loadingException;
this.awsCredentials = null;
}
public boolean isSuccessful() {
return awsCredentials != null;
}
}
| 8,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.