index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/DefaultAccountMonitor.java
/* * Copyright 2010-2014 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.accounts; import java.util.HashSet; import java.util.Set; import com.amazonaws.eclipse.core.preferences.AbstractPreferencePropertyMonitor; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; /** * Responsible for monitoring for changes on default accounts. * This includes either changing to another global/regional default account, * or enable/disable a regional default account. */ public class DefaultAccountMonitor extends AbstractPreferencePropertyMonitor{ private static final Set<String> watchedProperties = new HashSet<>(); static { watchedProperties.add(PreferenceConstants.P_GLOBAL_CURRENT_DEFAULT_ACCOUNT); watchedProperties.add(PreferenceConstants.P_REGIONS_WITH_DEFAULT_ACCOUNTS); for (Region region : RegionUtils.getRegions()) { watchedProperties.add(PreferenceConstants.P_REGION_CURRENT_DEFAULT_ACCOUNT(region)); watchedProperties.add(PreferenceConstants.P_REGION_DEFAULT_ACCOUNT_ENABLED(region)); } } public DefaultAccountMonitor() { super(0); // no delay } @Override protected boolean watchPreferenceProperty(String preferenceKey) { return watchedProperties.contains(preferenceKey); } }
7,700
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/AccountInfoChangeListener.java
/* * Copyright 2010-2014 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.accounts; /** * The interface for handling events when the account info are reloaded. */ public interface AccountInfoChangeListener { /** * This method will be called whenever the AccountInfoProvider reloads the * accounts. */ public void onAccountInfoChange(); }
7,701
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/preferences/PreferenceValueEncodingUtil.java
/* * Copyright 2008-2014 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.accounts.preferences; import java.io.UnsupportedEncodingException; import org.apache.commons.codec.binary.Base64; public class PreferenceValueEncodingUtil { public static String decodeString(String s) { try { return new String(Base64.decodeBase64(s.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Failed to decode the String", e); } } public static String encodeString(String s) { try { return new String(Base64.encodeBase64(s.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Failed to encode the String", e); } } }
7,702
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/preferences/PluginPreferenceStoreAccountCredentialsConfiguration.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.accounts.preferences; import org.eclipse.jface.preference.IPreferenceStore; import com.amazonaws.eclipse.core.accounts.AccountCredentialsConfiguration; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; /** * Concrete implementation of AccountCredentialsConfiguration, which uses the * preference store instance to persist the credentials configurations. */ public class PluginPreferenceStoreAccountCredentialsConfiguration extends AccountCredentialsConfiguration { private final IPreferenceStore prefStore; /** The names of the preference properties relating to this account */ private final String accountNamePreferenceName; private final String accessKeyPreferenceName; private final String secretKeyPreferenceName; /** The property values set in memory */ private String accountNameInMemory; private String accessKeyInMemory; private String secretKeyInMemory; @SuppressWarnings("deprecation") public PluginPreferenceStoreAccountCredentialsConfiguration( IPreferenceStore prefStore, String accountId) { if (prefStore == null) throw new IllegalAccessError("prefStore must not be null."); if (accountId == null) throw new IllegalAccessError("accountId must not be null."); this.prefStore = prefStore; this.accountNamePreferenceName = String.format("%s:%s", accountId, PreferenceConstants.P_ACCOUNT_NAME); this.accessKeyPreferenceName = String.format("%s:%s", accountId, PreferenceConstants.P_ACCESS_KEY); this.secretKeyPreferenceName = String.format("%s:%s", accountId, PreferenceConstants.P_SECRET_KEY); } /* All credential-related information are B64-encoded */ @Override public String getAccountName() { return this.accountNameInMemory != null ? this.accountNameInMemory : PreferenceValueEncodingUtil.decodeString( prefStore.getString(accountNamePreferenceName)); } @Override public void setAccountName(String accountName) { this.accountNameInMemory = accountName; } @Override public String getAccessKey() { return this.accessKeyInMemory != null ? this.accessKeyInMemory : PreferenceValueEncodingUtil.decodeString( prefStore.getString(accessKeyPreferenceName)); } @Override public void setAccessKey(String accessKey) { this.accessKeyInMemory = accessKey; } @Override public String getSecretKey() { return this.secretKeyInMemory != null ? this.secretKeyInMemory : PreferenceValueEncodingUtil.decodeString( prefStore.getString(secretKeyPreferenceName)); } @Override public void setSecretKey(String secretKey) { this.secretKeyInMemory = secretKey; } /** * Session token is not supported when the preference store is in use as the * data source; this method always return false. */ @Override public boolean isUseSessionToken() { return false; } /** * Session token is not supported when the preference store is in use as the * data source; this method doesn't have any effect */ @Override public void setUseSessionToken(boolean useSessionToken) { } /** * Session token is not supported when the preference store is in use as the * data source; this method always return null. */ @Override public String getSessionToken() { return null; } /** * Session token is not supported when the preference store is in use as the * data source; this method doesn't have any effect */ @Override public void setSessionToken(String sessionToken) { } /** * Persist all the in-memory property values in the preference store. */ @Override public void save() { if (accountNameInMemory != null) { String newAccountName = accountNameInMemory.trim(); prefStore.setValue(accountNamePreferenceName, PreferenceValueEncodingUtil.encodeString(newAccountName)); } if (accessKeyInMemory != null) { String newAccessKey = accessKeyInMemory.trim(); prefStore.setValue(accessKeyPreferenceName, PreferenceValueEncodingUtil.encodeString(newAccessKey)); } if (secretKeyInMemory != null) { String newSecretKey = secretKeyInMemory.trim(); prefStore.setValue(secretKeyPreferenceName, PreferenceValueEncodingUtil.encodeString(newSecretKey)); } clearInMemoryValue(); } /** * Remove all the preference properties relating to this account's * credential information */ @Override public void delete() { prefStore.setToDefault(accountNamePreferenceName); prefStore.setToDefault(accessKeyPreferenceName); prefStore.setToDefault(secretKeyPreferenceName); clearInMemoryValue(); } @Override public boolean isDirty() { // For performance reason, we only check whether there exists in-memory // property values (no matter it differs from the source value or not.) return accountNameInMemory != null || accessKeyInMemory != null || secretKeyInMemory != null; } private void clearInMemoryValue() { accountNameInMemory = null; accessKeyInMemory = null; secretKeyInMemory = null; } }
7,703
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/preferences/PluginPreferenceStoreAccountOptionalConfiguration.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.accounts.preferences; import org.eclipse.jface.preference.IPreferenceStore; import com.amazonaws.eclipse.core.accounts.AccountOptionalConfiguration; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; /** * Concrete implementation of AccountOptionalConfiguration, which uses the * preference store instance to persist the account optional configurations. */ public class PluginPreferenceStoreAccountOptionalConfiguration extends AccountOptionalConfiguration { private final IPreferenceStore prefStore; /** The names of the preference properties relating to this account */ private final String userIdPreferenceName; private final String ec2PrivateKeyFilePreferenceName; private final String ec2CertificateFilePreferenceName; /** The property values set in memory */ private String userIdInMemory; private String ec2PrivateKeyFileInMemory; private String ec2CertificateFileInMemory; /** * @param preferenceNamePrefix * The prefix of the preference names for the optional * configurations. Legacy accounts use the internal accountId as * the prefix, while the profile-based accounts use the profile * name as the prefix. The reason for such difference is because * the profile accounts might be assigned with a new accountId * after the credentials file is reloaded for multiple times. We * want to always associate the optional configuration to the * same profile account no matter what the current accountId it * is assigned to. */ public PluginPreferenceStoreAccountOptionalConfiguration( IPreferenceStore prefStore, String preferenceNamePrefix) { if (prefStore == null) throw new IllegalAccessError("prefStore must not be null."); if (preferenceNamePrefix == null) throw new IllegalAccessError("preferenceNamePrefix must not be null."); this.prefStore = prefStore; this.userIdPreferenceName = String.format("%s:%s", preferenceNamePrefix, PreferenceConstants.P_USER_ID); this.ec2PrivateKeyFilePreferenceName = String.format("%s:%s", preferenceNamePrefix, PreferenceConstants.P_PRIVATE_KEY_FILE); this.ec2CertificateFilePreferenceName = String.format("%s:%s", preferenceNamePrefix, PreferenceConstants.P_CERTIFICATE_FILE); } @Override public String getUserId() { // User-id is stored in B64-encoded format return this.userIdInMemory != null ? this.userIdInMemory : PreferenceValueEncodingUtil.decodeString( prefStore.getString(userIdPreferenceName)); } @Override public void setUserId(String userId) { this.userIdInMemory = userId; } @Override public String getEc2PrivateKeyFile() { return this.ec2PrivateKeyFileInMemory != null ? this.ec2PrivateKeyFileInMemory : prefStore.getString(ec2PrivateKeyFilePreferenceName); } @Override public void setEc2PrivateKeyFile(String ec2PrivateKeyFile) { this.ec2PrivateKeyFileInMemory = ec2PrivateKeyFile; } @Override public String getEc2CertificateFile() { return this.ec2CertificateFileInMemory != null ? this.ec2CertificateFileInMemory : prefStore.getString(ec2CertificateFilePreferenceName); } @Override public void setEc2CertificateFile(String ec2CertificateFile) { this.ec2CertificateFileInMemory = ec2CertificateFile; } /** * Persist all the in-memory property values in the preference store. */ @Override public void save() { // Clean up the AWS User-id and store it in B64-encoded format if (userIdInMemory != null) { String newUserId = userIdInMemory.replace("-", ""); newUserId = newUserId.replace(" ", ""); prefStore.setValue(userIdPreferenceName, PreferenceValueEncodingUtil.encodeString(newUserId)); } if (ec2PrivateKeyFileInMemory != null) { prefStore.setValue(ec2PrivateKeyFilePreferenceName, ec2PrivateKeyFileInMemory); } if (ec2CertificateFileInMemory != null) { prefStore.setValue(ec2CertificateFilePreferenceName, ec2CertificateFileInMemory); } clearInMemoryValue(); } /** * Remove all the preference properties relating to this account's * optional configurations */ @Override public void delete() { prefStore.setToDefault(userIdPreferenceName); prefStore.setToDefault(ec2PrivateKeyFilePreferenceName); prefStore.setToDefault(ec2CertificateFilePreferenceName); clearInMemoryValue(); } @Override public boolean isDirty() { // For performance reason, we only check whether there exists in-memory // property values (no matter it differs from the source value or not.) return userIdInMemory != null || ec2PrivateKeyFileInMemory != null || ec2CertificateFileInMemory != null; } private void clearInMemoryValue() { userIdInMemory = null; ec2PrivateKeyFileInMemory = null; ec2CertificateFileInMemory = null; } }
7,704
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/preferences/PluginPreferenceStoreAccountInfoMonitor.java
/* * Copyright 2010-2014 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.accounts.preferences; import java.util.HashSet; import java.util.Set; import com.amazonaws.eclipse.core.preferences.AbstractPreferencePropertyMonitor; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; /** * Responsible for monitoring for account info (access/secret keys, etc) changes * and notifying listeners. */ @SuppressWarnings("deprecation") public final class PluginPreferenceStoreAccountInfoMonitor extends AbstractPreferencePropertyMonitor { private static final long NOTIFICATION_DELAY = 1000L; private static final Set<String> watchedProperties = new HashSet<>(); static { watchedProperties.add(PreferenceConstants.P_ACCESS_KEY); watchedProperties.add(PreferenceConstants.P_ACCOUNT_IDS); watchedProperties.add(PreferenceConstants.P_CERTIFICATE_FILE); watchedProperties.add(PreferenceConstants.P_CURRENT_ACCOUNT); watchedProperties.add(PreferenceConstants.P_PRIVATE_KEY_FILE); watchedProperties.add(PreferenceConstants.P_SECRET_KEY); watchedProperties.add(PreferenceConstants.P_USER_ID); } public PluginPreferenceStoreAccountInfoMonitor() { super(NOTIFICATION_DELAY); } @Override protected boolean watchPreferenceProperty(String preferenceKey) { String bareProperty = preferenceKey.substring(preferenceKey.indexOf(":") + 1); return watchedProperties.contains(bareProperty); } }
7,705
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/profiles/SdkProfilesCredentialsConfiguration.java
/* * Copyright 2008-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.accounts.profiles; import java.io.File; import java.io.IOException; import org.eclipse.jface.preference.IPreferenceStore; import com.amazonaws.auth.profile.ProfilesConfigFileWriter; import com.amazonaws.auth.profile.internal.BasicProfile; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.accounts.AccountCredentialsConfiguration; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; import com.amazonaws.util.StringUtils; /** * Concrete implementation of AccountCredentialsConfiguration, which uses the * credential profiles file to persist the credential configurations. */ public class SdkProfilesCredentialsConfiguration extends AccountCredentialsConfiguration { /** * Use this preference store to save the mapping from an accountId to a * profile name. */ private final IPreferenceStore prefStore; /** * The profile instance loaded from the credentials file. */ private BasicProfile profile; /** * The name of the preference property that maps an internal account id to * the name of the credential profile associated with the account. */ private final String profileNamePreferenceName; /** The property values set in memory */ private String profileNameInMemory; private String accessKeyInMemory; private String secretKeyInMemory; private Boolean useSessionToken; private String sessionTokenInMemory; public SdkProfilesCredentialsConfiguration( IPreferenceStore prefStore, String accountId, BasicProfile profile) { if (prefStore == null) throw new IllegalAccessError("prefStore must not be null."); if (accountId == null) throw new IllegalAccessError("accountId must not be null."); if (profile == null) throw new IllegalAccessError("profile must not be null."); this.prefStore = prefStore; this.profile = profile; this.profileNamePreferenceName = String.format("%s:%s", accountId, PreferenceConstants.P_CREDENTIAL_PROFILE_NAME); } /* All credential-related information are B64-encoded */ /** * Use the profile name as the account name shown in the toolkit UI. */ @Override public String getAccountName() { return this.profileNameInMemory != null ? this.profileNameInMemory : profile.getProfileName(); } @Override public void setAccountName(String accountName) { this.profileNameInMemory = accountName; } @Override public String getAccessKey() { return this.accessKeyInMemory != null ? this.accessKeyInMemory : profile.getAwsAccessIdKey(); } @Override public void setAccessKey(String accessKey) { this.accessKeyInMemory = accessKey; } @Override public String getSecretKey() { return this.secretKeyInMemory != null ? this.secretKeyInMemory : profile.getAwsSecretAccessKey(); } @Override public void setSecretKey(String secretKey) { this.secretKeyInMemory = secretKey; } @Override public boolean isUseSessionToken() { if (useSessionToken != null) { return useSessionToken; } return !StringUtils.isNullOrEmpty(profile.getAwsSessionToken()); } @Override public void setUseSessionToken(boolean useSessionToken) { this.useSessionToken = useSessionToken; } @Override public String getSessionToken() { if (sessionTokenInMemory != null) { return sessionTokenInMemory; } return profile.getAwsSessionToken(); } @Override public void setSessionToken(String sessionToken) { this.sessionTokenInMemory = sessionToken; } /** * Write all the in-memory property values in the credentials file. */ @Override public void save() { if (isDirty()) { // Clean up the properties before saving it if (profileNameInMemory != null) { profileNameInMemory = profileNameInMemory.trim(); } if (accessKeyInMemory != null) { accessKeyInMemory = accessKeyInMemory.trim(); } if (secretKeyInMemory != null) { secretKeyInMemory = secretKeyInMemory.trim(); } if (sessionTokenInMemory != null) { sessionTokenInMemory = sessionTokenInMemory.trim(); } BasicProfile newBasicProfile = SdkProfilesFactory.newBasicProfile( getAccountName(), getAccessKey(), getSecretKey(), isUseSessionToken() ? getSessionToken() : null); // Output the new profile to the credentials file File credentialsFile = new File( prefStore.getString( PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION)); // Create the file if it doesn't exist yet // TODO: ideally this should be handled by ProfilesConfigFileWriter if ( !credentialsFile.exists() ) { try { if (credentialsFile.getParentFile() != null) { credentialsFile.getParentFile().mkdirs(); } credentialsFile.createNewFile(); } catch (IOException ioe) { AwsToolkitCore.getDefault().reportException("Failed to create credentials file at " + credentialsFile.getAbsolutePath(), ioe); } } String prevProfileName = profile.getProfileName(); ProfilesConfigFileWriter.modifyOneProfile(credentialsFile, prevProfileName, SdkProfilesFactory.convert(newBasicProfile)); // Persist the profile metadata in the preference store: // accountId:credentialProfileName=profileName prefStore.setValue( profileNamePreferenceName, newBasicProfile.getProfileName()); this.profile = newBasicProfile; clearInMemoryValue(); } } /** * Deletes the profile name property associated with this account in the * preferece store instance. Also remove the profile from the credentials * file. */ @Override public void delete() { prefStore.setToDefault(profileNamePreferenceName); File credentialsFile = new File( prefStore.getString( PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION)); String prevProfileName = profile.getProfileName(); ProfilesConfigFileWriter.deleteProfiles(credentialsFile, prevProfileName); clearInMemoryValue(); } @Override public boolean isDirty() { return (hasPropertyChanged(profile.getProfileName(), profileNameInMemory) || hasPropertyChanged(profile.getAwsAccessIdKey(), accessKeyInMemory) || hasPropertyChanged(profile.getAwsSecretAccessKey(), secretKeyInMemory) || hasPropertyChanged(!StringUtils.isNullOrEmpty(profile.getAwsSessionToken()), useSessionToken) || hasPropertyChanged(profile.getAwsSessionToken(), sessionTokenInMemory)); } /** * @return True if the new value of the property is non null and differs * from the original, false otherwise */ private boolean hasPropertyChanged(Object originalValue, Object newValue) { return newValue != null && !newValue.equals(originalValue); } private void clearInMemoryValue() { profileNameInMemory = null; accessKeyInMemory = null; secretKeyInMemory = null; useSessionToken = null; sessionTokenInMemory = null; } }
7,706
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/profiles/SdkCredentialsFileMonitor.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.accounts.profiles; import java.io.File; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; /** * A preference store property change listener that tracks the latest * configuration of the credentials file' location. It also manages a file * monitor that tracks any modification to the file's content. */ public class SdkCredentialsFileMonitor implements IPropertyChangeListener { /** * The preference store instance whose property change is being tracked by * this monitor. */ private IPreferenceStore prefStore; /** * The file monitor that tracks modification to the credentials file's * content */ private SdkCredentialsFileContentMonitor fileContentMonitor; /** * @param prefStore * the preference store where the credentials file's location is * configured. */ public void start(IPreferenceStore prefStore) { // Stop listening to preference property updates while configuring the // internals if (this.prefStore != null) { this.prefStore.removePropertyChangeListener(this); } // Spins up a new content monitor on the location that is currently // configured in the preference store. String location = prefStore.getString(PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION); resetFileContentMonitor(location); // Now we are done -- start listening to preference property changes prefStore.addPropertyChangeListener(this); } private void resetFileContentMonitor(String fileLocation) { // Stop the existing content monitor, if any if (fileContentMonitor != null) { fileContentMonitor.stop(); fileContentMonitor = null; } File file = new File(fileLocation); fileContentMonitor = new SdkCredentialsFileContentMonitor(file); fileContentMonitor.start(); } /** * When the credentials file location is changed in the preference store, * reset the content monitor to track the file at the new location. */ @Override public void propertyChange(PropertyChangeEvent event) { String propertyName = event.getProperty(); if ( !PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION.equals(propertyName) ) { return; } String newLocation = (String)event.getNewValue(); resetFileContentMonitor(newLocation); } }
7,707
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/profiles/SdkCredentialsFileContentMonitor.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.accounts.profiles; import java.io.File; import java.io.FileFilter; import java.util.concurrent.ThreadFactory; import org.apache.commons.io.monitor.FileAlterationListener; import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; import org.apache.commons.io.monitor.FileAlterationMonitor; import org.apache.commons.io.monitor.FileAlterationObserver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; /** * Used to monitor a specific credentials file and prompts the user to reload * the credentials whenever the file content is changed. */ public class SdkCredentialsFileContentMonitor { private static final Log debugLogger = LogFactory.getLog(SdkCredentialsFileContentMonitor.class); private final static long DEFAULT_POLLING_INTERVAL_MILLIS = 3 * 1000; private final File _target; private final FileAlterationObserver _observer; private final FileAlterationMonitor _monitor; private final FileAlterationListener _listener; private boolean debugMode = false; public SdkCredentialsFileContentMonitor(File target) { this(target, DEFAULT_POLLING_INTERVAL_MILLIS); } public SdkCredentialsFileContentMonitor(File target, long pollingIntervalInMs) { this(target, pollingIntervalInMs, new FileAlterationListenerAdaptor() { @Override public void onFileChange(final File changedFile) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (AwsToolkitCore.getDefault().getPreferenceStore() .getBoolean(PreferenceConstants.P_ALWAYS_RELOAD_WHEN_CREDNENTIAL_PROFILE_FILE_MODIFIED)) { AwsToolkitCore.getDefault().getAccountManager().reloadAccountInfo(); } else { showCredentialsReloadConfirmBox(changedFile); } } }); } }); } public SdkCredentialsFileContentMonitor( File target, long pollingIntervalInMillis, FileAlterationListener listener) { _target = target; // IllegalArgumentException is expected if target.getParentFile == null _observer = new FileAlterationObserver(target.getParentFile(), new FileFilter() { @Override public boolean accept(File file) { return file.equals(_target); } }); _monitor = new FileAlterationMonitor(pollingIntervalInMillis); _listener = listener; _observer.addListener(_listener); _monitor.addObserver(_observer); // Use daemon thread to avoid thread leakage _monitor.setThreadFactory(new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread t = new Thread(runnable); t.setDaemon(true); t.setName("aws-credentials-file-monitor-thread"); return t; } }); } public void start() { try { _monitor.start(); logInfo("Monitoring content of " + _target.getAbsolutePath()); } catch (Exception e) { logException("Unable to start file monitor on " + _target.getAbsolutePath(), e); } } public void stop() { try { _monitor.stop(); logInfo("Stopped monitoring content of " + _target.getAbsolutePath()); } catch (Exception e) { logException("Unable to stop the file monitor on " + _target.getAbsolutePath(), e); } } /** * Should only be invoked in the main thread */ private static void showCredentialsReloadConfirmBox(File credentialsFile) { String message = "The AWS credentials file '" + credentialsFile.getAbsolutePath() + "' has been changed in the file system. " + "Do you want to reload the credentials from the updated file content?"; MessageDialog dialog = new MessageDialog( null, // use the top-level shell "AWS Credentials File Changed", AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON), message, MessageDialog.CONFIRM, new String[] { "No", "Yes", "Always Reload" }, 1 // default to YES ); int result = dialog.open(); if (result == 2) { AwsToolkitCore.getDefault().getPreferenceStore() .setValue( PreferenceConstants.P_ALWAYS_RELOAD_WHEN_CREDNENTIAL_PROFILE_FILE_MODIFIED, true); } if (result == 1 || result == 2) { AwsToolkitCore.getDefault().getAccountManager().reloadAccountInfo(); } } /** * For testing purpose only. */ public void setDebugMode(boolean debug) { this.debugMode = debug; } private void logInfo(String info) { if (debugMode) { debugLogger.debug(info); } else { AwsToolkitCore.getDefault().logInfo(info); } } private void logException(String msg, Exception e) { if (debugMode) { debugLogger.debug(msg, e); } else { AwsToolkitCore.getDefault().logError(msg, e); } } }
7,708
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/profiles/SdkProfilesFactory.java
/* * Copyright 2016 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.accounts.profiles; import java.util.HashMap; import java.util.Map; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.auth.profile.internal.BasicProfile; import com.amazonaws.auth.profile.internal.Profile; import com.amazonaws.auth.profile.internal.ProfileKeyConstants; import com.amazonaws.internal.StaticCredentialsProvider; /** * Profile factory class to dispatch commonly used profiles. */ public class SdkProfilesFactory { /** * Dispatch a BasicProfile instance with the provided profileName, and empty access key and secret key. */ public static BasicProfile newEmptyBasicProfile(String profileName) { return newBasicProfile(profileName, "", "", null); } /** * Dispatch a BasicProfile instance with the provided parameters; */ public static BasicProfile newBasicProfile(String profileName, String accessKey, String secretKey, String sessionToken) { Map<String, String> properties = new HashMap<>(); properties.put(ProfileKeyConstants.AWS_ACCESS_KEY_ID, accessKey); properties.put(ProfileKeyConstants.AWS_SECRET_ACCESS_KEY, secretKey); if (sessionToken != null) { properties.put(ProfileKeyConstants.AWS_SESSION_TOKEN, sessionToken); } return new BasicProfile(profileName, properties); } /** * Convert a BasicProfile instance to the legacy Profile class. */ public static Profile convert(BasicProfile profile) { if (profile == null) return null; AWSCredentials credentials; if (profile.getAwsSessionToken() != null) { credentials = new BasicSessionCredentials( profile.getAwsAccessIdKey(), profile.getAwsSecretAccessKey(), profile.getAwsSessionToken()); } else { credentials = new BasicAWSCredentials( profile.getAwsAccessIdKey(), profile.getAwsSecretAccessKey()); } Profile legacyProfile = new Profile(profile.getProfileName(), profile.getProperties(), new StaticCredentialsProvider(credentials)); return legacyProfile; } }
7,709
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/MavenConfigurationDataModel.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; import com.amazonaws.eclipse.core.maven.MavenFactory; /** * Data model for Maven project configuration composite. */ public class MavenConfigurationDataModel extends AbstractAwsToolkitDataModel { public static final String P_GROUP_ID = "groupId"; public static final String P_ARTIFACT_ID = "artifactId"; public static final String P_PACKAGE_NAME = "packageName"; public static final String P_VERSION = "version"; private String groupId = "com.amazonaws"; private String artifactId = "samples"; private String version = "1.0.0"; private String packageName = MavenFactory.assumePackageName(groupId, artifactId); public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getArtifactId() { return artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public void setPackageName(String packageName) { this.setProperty(P_PACKAGE_NAME, packageName, this::getPackageName, (newValue) -> this.packageName = newValue); } public String getPackageName() { return packageName; } }
7,710
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/AwsResourceMetadata.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; import java.util.List; /** * Metadata for a specific AWS resource type. */ public interface AwsResourceMetadata<T, P extends AbstractAwsResourceScopeParam<P>> { // Fake resource items indicating the current loading status to be used in the Combo box. T getLoadingItem(); T getNotFoundItem(); T getErrorItem(); // Resource type e.g Bucket or Stack to be used in the information message. String getResourceType(); // Default resource name to be used when creating a new resource. String getDefaultResourceName(); // Load AWS resources given the provided parameters List<T> loadAwsResources(P param); // The preferred resource name denoting this resource. String getResourceName(T resource); default T findResourceByName(List<T> resources, String name) { if (resources == null || resources.isEmpty()) { return null; } return resources.stream() .filter(resource -> getResourceName(resource).equals(name)) .findAny().orElse(null); } }
7,711
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/AbstractAwsToolkitDataModel.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.function.Consumer; import java.util.function.Supplier; /** * Abstract data model with the property change support. */ public abstract class AbstractAwsToolkitDataModel { private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); protected <T> void setProperty(String propertyName, T newProperty, Supplier<T> getter, Consumer<T> setter) { T oldValue = getter.get(); setter.accept(newProperty); pcs.firePropertyChange(propertyName, oldValue, newProperty); } public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } }
7,712
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/MultipleSelectionListDataModel.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; import java.util.ArrayList; import java.util.List; /** * Data model for a widget of List with check box. The data model collects the checked items instead of * the selected items from the List. */ public class MultipleSelectionListDataModel<T> { private final List<T> selectedList = new ArrayList<>(); public List<T> getSelectedList() { return selectedList; } }
7,713
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/KeyValueSetDataModel.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; import java.util.List; public class KeyValueSetDataModel { private final int maxPairs; private final List<Pair> pairSet; /** * @param maxPairs - Maximum amount allowed for the PairSet. -1 indicates unlimited! * @param pairSet - The actually set of key-value pairs. */ public KeyValueSetDataModel(int maxPairs, List<Pair> pairSet) { this.maxPairs = maxPairs; this.pairSet = pairSet; } public int getMaxPairs() { return maxPairs; } public List<Pair> getPairSet() { return pairSet; } public boolean isUnlimitedPairs() { return maxPairs < 0; } public static class Pair { public static final String P_KEY = "key"; public static final String P_VALUE = "value"; private String key; private String value; public Pair(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
7,714
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/SelectOrCreateKmsKeyDataModel.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase; import com.amazonaws.eclipse.core.model.SelectOrCreateKmsKeyDataModel.KmsKey; import com.amazonaws.eclipse.core.util.KmsClientUtils; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.model.AliasListEntry; import com.amazonaws.services.kms.model.KeyListEntry; public class SelectOrCreateKmsKeyDataModel extends SelectOrCreateDataModel<KmsKey, AwsResourceScopeParamBase> { private static final KmsKey LOADING = new KmsKey("Loading..."); private static final KmsKey NOT_FOUND = new KmsKey("Not Found"); private static final KmsKey ERROR = new KmsKey("Error"); public static class KmsKey { public static final String KMS_KEY_ALIAS_PREFIX = "alias/"; private final String presentationText; private KeyListEntry key; private AliasListEntry alias; private KmsKey(String presentationText) { this.presentationText = presentationText; } public KmsKey(KeyListEntry key, AliasListEntry alias) { this.presentationText = null; this.key = key; this.alias = alias; } public KeyListEntry getKey() { return key; } public AliasListEntry getAlias() { return alias; } public String getPresentationText() { if (presentationText != null) { return presentationText; } return alias == null ? key.getKeyId() : alias.getAliasName().substring(KMS_KEY_ALIAS_PREFIX.length()); } } @Override public KmsKey getLoadingItem() { return LOADING; } @Override public KmsKey getNotFoundItem() { return NOT_FOUND; } @Override public KmsKey getErrorItem() { return ERROR; } @Override public String getResourceType() { return "Kms Key"; } @Override public String getDefaultResourceName() { return "lambda-function-kms-key"; } @Override public List<KmsKey> loadAwsResources(AwsResourceScopeParamBase param) { AWSKMS kmsClient = AwsToolkitCore.getClientFactory(param.getAccountId()) .getKmsClientByRegion(param.getRegionId()); List<KeyListEntry> keys = KmsClientUtils.listKeys(kmsClient); Map<String, AliasListEntry> aliasList = KmsClientUtils.listAliases(kmsClient); return keys.stream() .map(key -> new KmsKey(key, aliasList.get(key.getKeyId()))) .collect(Collectors.toList()); } @Override public String getResourceName(KmsKey resource) { return resource.getPresentationText(); } }
7,715
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/RegionDataModel.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; import com.amazonaws.eclipse.core.regions.Region; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; public class RegionDataModel { public static final String P_REGION = "region"; @JsonIgnore private Region region; public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } @JsonProperty public String getRegionId() { return region.getId(); } @JsonProperty public String getRegionName() { return region.getName(); } }
7,716
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/GitCredentialsDataModel.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.model; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.services.identitymanagement.AmazonIdentityManagement; public class GitCredentialsDataModel { public static final String P_USERNAME = "username"; public static final String P_PASSWORD = "password"; public static final String P_SHOW_PASSWORD = "showPassword"; private String username; private String password; private boolean showPassword; private String userAccount = AwsToolkitCore.getDefault().getCurrentAccountId(); private String regionId = RegionUtils.getCurrentRegion().getId(); public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isShowPassword() { return showPassword; } public void setShowPassword(boolean showPassword) { this.showPassword = showPassword; } public String getUserAccount() { return userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } public String getRegionId() { return regionId; } public void setRegionId(String regionId) { this.regionId = regionId; } public AmazonIdentityManagement getIamClient() { if (userAccount != null && regionId != null) { return AwsToolkitCore.getClientFactory(userAccount) .getIAMClientByRegion(regionId); } return null; } }
7,717
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/SelectOrCreateBucketDataModel.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; import java.util.List; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam.AwsResourceScopeParamBase; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.util.S3BucketUtil; import com.amazonaws.services.s3.model.Bucket; public class SelectOrCreateBucketDataModel extends SelectOrCreateDataModel<Bucket, AwsResourceScopeParamBase> { private static final String RESOURCE_TYPE = "Bucket"; private static final Bucket LOADING = new Bucket("Loading..."); private static final Bucket NONE_FOUND = new Bucket("None found"); private static final Bucket ERROR = new Bucket("Error Loading Buckets"); public String getBucketName() { return this.getExistingResource().getName(); } @Override public Bucket getLoadingItem() { return LOADING; } @Override public Bucket getNotFoundItem() { return NONE_FOUND; } @Override public Bucket getErrorItem() { return ERROR; } @Override public String getResourceType() { return RESOURCE_TYPE; } @Override public String getDefaultResourceName() { return "lambda-function-bucket-" + System.currentTimeMillis(); } @Override public List<Bucket> loadAwsResources(AwsResourceScopeParamBase param) { return S3BucketUtil.listBucketsInRegion( AwsToolkitCore.getClientFactory(param.getAccountId()).getS3ClientByRegion(param.getRegionId()), RegionUtils.getRegion(param.getRegionId())); } @Override public String getResourceName(Bucket resource) { return resource.getName(); } }
7,718
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/ImportFileDataModel.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; import com.amazonaws.eclipse.core.ui.ImportFileComposite; /** * Data model for {@link ImportFileComposite} composite. */ public class ImportFileDataModel { public static final String P_FILE_PATH = "filePath"; private String filePath; public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } }
7,719
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/ComboBoxItemData.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; /** * Data model to be bound with a ComboBox item. */ public interface ComboBoxItemData { // The name for this item to be shown in the ComboBox. String getComboBoxItemLabel(); }
7,720
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/AbstractAwsResourceScopeParam.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; /** * Parameters for targeting a specific type of AWS resources. */ public abstract class AbstractAwsResourceScopeParam<T extends AbstractAwsResourceScopeParam<T>> { protected final String accountId; protected final String regionId; public AbstractAwsResourceScopeParam(String accountId, String regionId) { this.accountId = accountId; this.regionId = regionId; } public abstract T copy(); public String getAccountId() { return accountId; } public String getRegionId() { return regionId; } public static class AwsResourceScopeParamBase extends AbstractAwsResourceScopeParam<AwsResourceScopeParamBase> { public AwsResourceScopeParamBase(String accountId, String regionId) { super(accountId, regionId); } @Override public AwsResourceScopeParamBase copy() { return new AwsResourceScopeParamBase(accountId, regionId); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((accountId == null) ? 0 : accountId.hashCode()); result = prime * result + ((regionId == null) ? 0 : regionId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AwsResourceScopeParamBase other = (AwsResourceScopeParamBase) obj; if (accountId == null) { if (other.accountId != null) return false; } else if (!accountId.equals(other.accountId)) return false; if (regionId == null) { if (other.regionId != null) return false; } else if (!regionId.equals(other.regionId)) return false; return true; } } }
7,721
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/SelectOrInputDataModel.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import com.amazonaws.eclipse.core.ui.SelectOrInputComposite; import com.fasterxml.jackson.annotation.JsonIgnore; /** * Data model for {@link SelectOrInputComposite} which is intended to be extended by a * subclass with a concrete type for the generic type T. */ public abstract class SelectOrInputDataModel<T, P extends AbstractAwsResourceScopeParam<P>> implements AwsResourceMetadata<T, P> { public static final String P_EXISTING_RESOURCE = "existingResource"; public static final String P_NEW_RESOURCE_NAME = "newResourceName"; public static final String P_SELECT_EXISTING_RESOURCE = "selectExistingResource"; public static final String P_CREATE_NEW_RESOURCE = "createNewResource"; @JsonIgnore private T existingResource; private String newResourceName; private boolean selectExistingResource = false; private boolean createNewResource = true; private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } public T getExistingResource() { return existingResource; } public void setExistingResource(T existingResource) { T oldValue = this.existingResource; this.existingResource = existingResource; this.pcs.firePropertyChange(P_EXISTING_RESOURCE, oldValue, existingResource); } public String getNewResourceName() { return newResourceName; } public void setNewResourceName(String newResourceName) { String oldValue = this.newResourceName; this.newResourceName = newResourceName; this.pcs.firePropertyChange(P_NEW_RESOURCE_NAME, oldValue, newResourceName); } public boolean isSelectExistingResource() { return selectExistingResource; } public void setSelectExistingResource(boolean selectExistingResource) { boolean oldValue = this.selectExistingResource; this.selectExistingResource = selectExistingResource; this.pcs.firePropertyChange(P_SELECT_EXISTING_RESOURCE, oldValue, selectExistingResource); } public boolean isCreateNewResource() { return createNewResource; } public void setCreateNewResource(boolean createNewResource) { boolean oldValue = this.createNewResource; this.createNewResource = createNewResource; this.pcs.firePropertyChange(P_CREATE_NEW_RESOURCE, oldValue, createNewResource); } }
7,722
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/package-info.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /** * Collection of sub-module data models such as Maven configuration data model. */ package com.amazonaws.eclipse.core.model;
7,723
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/SelectOrCreateDataModel.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import com.amazonaws.eclipse.core.ui.SelectOrCreateComposite; import com.fasterxml.jackson.annotation.JsonIgnore; /** * Data model for {@link SelectOrCreateComposite} which is intended to be extended by a * subclass with a concrete type for the generic type T. */ public abstract class SelectOrCreateDataModel<T, P extends AbstractAwsResourceScopeParam<P>> implements AwsResourceMetadata<T, P> { public static final String P_EXISTING_RESOURCE = "existingResource"; @JsonIgnore private T existingResource; private boolean createNewResource = false; private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } public T getExistingResource() { return existingResource; } public void setExistingResource(T existingResource) { T oldValue = this.existingResource; this.existingResource = existingResource; this.pcs.firePropertyChange(P_EXISTING_RESOURCE, oldValue, existingResource); } public boolean isCreateNewResource() { return createNewResource; } public void setCreateNewResource(boolean createNewResource) { this.createNewResource = createNewResource; } }
7,724
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/model/ProjectNameDataModel.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.model; /** * Project name pojo. */ public class ProjectNameDataModel { public static final String P_PROJECT_NAME = "projectName"; private String projectName; public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } }
7,725
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/RepositorySelection.java
/******************************************************************************* * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com> * Copyright (C) 2010, Mathias Kinzler <mathias.kinzler@sap.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package com.amazonaws.eclipse.core.egit; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.URIish; /** * Data class representing selection of remote repository made by user. * Selection is either a URI or a remote repository configuration. * <p> * Each immutable instance has at least one of two class fields (URI, remote * config) set to null. null value indicates that it has illegal value or this * form of repository selection is not selected. */ public class RepositorySelection { private URIish uri; private RemoteConfig config; static final RepositorySelection INVALID_SELECTION = new RepositorySelection( null, null); /** * @param uri * the new specified URI. null if the new URI is invalid or user * chosen to specify repository as remote config instead of URI. * @param config * the new remote config. null if user chosen to specify * repository as URI. */ public RepositorySelection(final URIish uri, final RemoteConfig config) { if (config != null && uri != null) throw new IllegalArgumentException( "URI and config cannot be set at the same time."); //$NON-NLS-1$ this.config = config; this.uri = uri; } /** * Return the selected URI. * <p> * If pushMode is <code>true</code> and a remote configuration was selected, * this will try to return a push URI from that configuration, otherwise a * URI; if no configuration was selected, the URI entered in the URI field * will be returned.<br> * If pushMode is <code>false</code> and a remote configuration was * selected, this will try to return a URI from that configuration, * otherwise <code>null</code> will be returned; if no configuration was * selected, the URI entered in the URI field will be returned * * @param pushMode * the push mode * @return the selected URI, or <code>null</code> if there is no valid * selection */ public URIish getURI(boolean pushMode) { if (isConfigSelected()) if (pushMode) { if (config.getPushURIs().size() > 0) return config.getPushURIs().get(0); else if (config.getURIs().size() > 0) return config.getURIs().get(0); else return null; } else { if (config.getURIs().size() > 0) return config.getURIs().get(0); else if (config.getPushURIs().size() > 0) return config.getPushURIs().get(0); else return null; } return uri; } /** * @return the selected URI, <code>null</code> if a configuration was * selected */ public URIish getURI() { if (isConfigSelected()) return null; return uri; } /** * @return list of all push URIs - either the one specified as custom URI or * all push URIs of the selected configuration; if not push URIs * were specified, the first URI is returned */ public List<URIish> getPushURIs() { if (isURISelected()) return Collections.singletonList(uri); if (isConfigSelected()) { List<URIish> pushUris = new ArrayList<>(); pushUris.addAll(config.getPushURIs()); if (pushUris.isEmpty()) pushUris.add(config.getURIs().get(0)); return pushUris; } return null; } /** * @return the selected remote configuration. null if user chosen to select * repository as URI. */ public RemoteConfig getConfig() { return config; } /** * @return selected remote configuration name or null if selection is not a * remote configuration. */ public String getConfigName() { if (isConfigSelected()) return config.getName(); return null; } /** * @return true if selection contains valid URI or remote config, false if * there is no valid selection. */ public boolean isValidSelection() { return uri != null || config != null; } /** * @return true if user selected valid URI, false if user selected invalid * URI or remote config. */ public boolean isURISelected() { return uri != null; } /** * @return true if user selected remote configuration, false if user * selected (invalid or valid) URI. */ public boolean isConfigSelected() { return config != null; } @Override public boolean equals(final Object obj) { if (obj == this) return true; if (obj instanceof RepositorySelection) { final RepositorySelection other = (RepositorySelection) obj; if (uri == null ^ other.uri == null) return false; if (uri != null && !uri.equals(other.uri)) return false; if (config != other.config) return false; return true; } else return false; } @Override public int hashCode() { if (uri != null) return uri.hashCode(); else if (config != null) return config.hashCode(); return 31; } }
7,726
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/EGitCredentialsProvider.java
/******************************************************************************* * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com> * Copyright (C) 2010, Edwin Kempin <edwin.kempin@sap.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package com.amazonaws.eclipse.core.egit; import java.io.IOException; import java.text.MessageFormat; import java.util.concurrent.atomic.AtomicReference; import org.eclipse.egit.core.Activator; import org.eclipse.egit.core.securestorage.UserPasswordCredentials; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.window.Window; import org.eclipse.jgit.errors.UnsupportedCredentialItem; import org.eclipse.jgit.transport.CredentialItem; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.URIish; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; /** * This class implements a {@link CredentialsProvider} for EGit. The provider * tries to retrieve the credentials (user, password) for a given URI from the * secure store. A login popup is shown if no credentials are available. */ @SuppressWarnings("restriction") public class EGitCredentialsProvider extends CredentialsProvider { private String user; private String password; /** * Default constructor */ public EGitCredentialsProvider() { // empty } /** * @param user * @param password */ public EGitCredentialsProvider(String user, String password) { this.user = user; this.password = password; } @Override public boolean isInteractive() { return true; } @Override public boolean supports(CredentialItem... items) { for (CredentialItem i : items) { if (i instanceof CredentialItem.StringType) continue; else if (i instanceof CredentialItem.CharArrayType) continue; else if (i instanceof CredentialItem.YesNoType) continue; else if (i instanceof CredentialItem.InformationalMessage) continue; else return false; } return true; } @Override public boolean get(final URIish uri, final CredentialItem... items) throws UnsupportedCredentialItem { if (items.length == 0) { return true; } CredentialItem.Username userItem = null; CredentialItem.Password passwordItem = null; boolean isSpecial = false; for (CredentialItem item : items) { if (item instanceof CredentialItem.Username) userItem = (CredentialItem.Username) item; else if (item instanceof CredentialItem.Password) passwordItem = (CredentialItem.Password) item; else isSpecial = true; } if (!isSpecial && (userItem != null || passwordItem != null)) { UserPasswordCredentials credentials = null; if ((user != null) && (password != null)) credentials = new UserPasswordCredentials(user, password); else credentials = SecureStoreUtils.getCredentialsQuietly(uri); if (credentials == null) { credentials = getCredentialsFromUser(uri); if (credentials == null) return false; } if (userItem != null) userItem.setValue(credentials.getUser()); if (passwordItem != null) passwordItem.setValue(credentials.getPassword().toCharArray()); return true; } // special handling for non-user,non-password type items final boolean[] result = new boolean[1]; PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); if (items.length == 1) { CredentialItem item = items[0]; result[0] = getSingleSpecial(shell, uri, item); } else { result[0] = getMultiSpecial(shell, uri, items); } } }); return result[0]; } @Override public void reset(URIish uri) { try { Activator.getDefault().getSecureStore().clearCredentials(uri); user = null; password = null; } catch (IOException e) { Activator.logError(MessageFormat.format( UIText.EGitCredentialsProvider_FailedToClearCredentials, uri), e); } } /** * Opens a dialog for a single non-user, non-password type item. * @param shell the shell to use * @param uri the uri of the get request * @param item the item to handle * @return <code>true</code> if the request was successful and values were supplied; * <code>false</code> if the user canceled the request and did not supply all requested values. */ private boolean getSingleSpecial(Shell shell, URIish uri, CredentialItem item) { if (item instanceof CredentialItem.InformationalMessage) { MessageDialog.openInformation(shell, UIText.EGitCredentialsProvider_information, item.getPromptText()); return true; } else if (item instanceof CredentialItem.YesNoType) { CredentialItem.YesNoType v = (CredentialItem.YesNoType) item; String[] labels = new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }; int[] resultIDs = new int[] { IDialogConstants.YES_ID, IDialogConstants.NO_ID, IDialogConstants.CANCEL_ID }; MessageDialog dialog = new MessageDialog( shell, UIText.EGitCredentialsProvider_question, null, item.getPromptText(), MessageDialog.QUESTION_WITH_CANCEL, labels, 0); dialog.setBlockOnOpen(true); int r = dialog.open(); if (r < 0) { return false; } switch (resultIDs[r]) { case IDialogConstants.YES_ID: { v.setValue(true); return true; } case IDialogConstants.NO_ID: { v.setValue(false); return true; } default: // abort return false; } } else { // generically handles all other types of items return getMultiSpecial(shell, uri, item); } } /** * Opens a generic dialog presenting all CredentialItems to the user. * @param shell the shell to use * @param uri the uri of the get request * @param items the items to handle * @return <code>true</code> if the request was successful and values were supplied; * <code>false</code> if the user canceled the request and did not supply all requested values. */ private boolean getMultiSpecial(Shell shell, URIish uri, CredentialItem... items) { CustomPromptDialog dialog = new CustomPromptDialog(shell, uri, UIText.EGitCredentialsProvider_information, items); dialog.setBlockOnOpen(true); int r = dialog.open(); if (r == Window.OK) { return true; } return false; } private UserPasswordCredentials getCredentialsFromUser(final URIish uri) { final AtomicReference<UserPasswordCredentials> aRef = new AtomicReference<>( null); PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); aRef.set(LoginService.login(shell, uri)); } }); return aRef.get(); } }
7,727
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/GitRepositoryInfo.java
/******************************************************************************* * Copyright (c) 2012 SAP AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Stefan Lay (SAP AG) - initial implementation *******************************************************************************/ package com.amazonaws.eclipse.core.egit; import java.util.ArrayList; import java.util.List; import org.eclipse.egit.core.securestorage.UserPasswordCredentials; /** * <p> * <strong>EXPERIMENTAL</strong>. This class or interface has been added as part * of a work in progress. There is no guarantee that this API will work or that * it will remain the same. Please do not use this API without consulting with * the egit team. * </p> * * Encapsulates info of a git repository */ @SuppressWarnings("restriction") public class GitRepositoryInfo { private final String cloneUri; private UserPasswordCredentials credentials; private boolean shouldSaveCredentialsInSecureStore; private String repositoryName; private final List<String> fetchRefSpecs = new ArrayList<>(); /** * Describes settings for git push */ public static class PushInfo { private String pushRefSpec; private String pushUri; /** * @param pushRefSpec * @param pushUri */ public PushInfo(String pushRefSpec, String pushUri) { this.pushRefSpec = pushRefSpec; this.pushUri = pushUri; } /** * @return the push ref spec */ public String getPushRefSpec() { return pushRefSpec; } /** * @return the push URI */ public String getPushUri() { return pushUri; } } private List<PushInfo> pushInfos = new ArrayList<>(); /** */ public static class RepositoryConfigProperty { private String section; private String subsection; private String name; private String value; /** * @param section the config section * @param subsection the config sub section * @param name the name of the config parameter * @param value the value of the config parameter */ public RepositoryConfigProperty(String section, String subsection, String name, String value) { this.section = section; this.subsection = subsection; this.name = name; this.value = value; } /** * @return the config section */ public String getSection() { return section; } /** * @return the config sub section */ public String getSubsection() { return subsection; } /** * @return the name of the config parameter */ public String getName() { return name; } /** * @return the value of the config parameter */ public String getValue() { return value; } } private final List<RepositoryConfigProperty> repositoryConfigProperties = new ArrayList<>(); /** * @param cloneUri * the URI where the repository can be cloned from */ public GitRepositoryInfo(String cloneUri) { this.cloneUri = cloneUri; } /** * @return the URI where the repository can be cloned from */ public String getCloneUri() { return cloneUri; } /** * @param user * @param password */ public void setCredentials(String user, String password) { credentials = new UserPasswordCredentials(user, password); } /** * @return the credentials needed to log in */ public UserPasswordCredentials getCredentials() { return credentials; } /** * @param shouldSaveCredentialsInSecureStore * whether the credentials should be saved after successful clone */ public void setShouldSaveCredentialsInSecureStore( boolean shouldSaveCredentialsInSecureStore) { this.shouldSaveCredentialsInSecureStore = shouldSaveCredentialsInSecureStore; } /** * @return whether the credentials should be saved after successful clone */ public boolean shouldSaveCredentialsInSecureStore() { return shouldSaveCredentialsInSecureStore; } /** * @param repositoryName * the name of the git repository */ public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } /** * @return the name of the git repository */ public String getRepositoryName() { return repositoryName; } /** * Adds a fetch specification to the cloned repository * @param fetchRefSpec the fetch ref spec which will be added */ public void addFetchRefSpec(String fetchRefSpec) { this.fetchRefSpecs.add(fetchRefSpec); } /** * @return the fetch ref specs */ public List<String> getFetchRefSpecs() { return fetchRefSpecs; } /** * Adds a push information to the cloned repository * @param pushRefSpec the push ref spec which will be added * @param pushUri the push uri which will be added */ public void addPushInfo(String pushRefSpec, String pushUri) { this.pushInfos.add(new PushInfo(pushRefSpec, pushUri)); } /** * @return the push information */ public List<PushInfo> getPushInfos() { return pushInfos; } /** * Add an entry in the configuration of the cloned repository * * @param section * @param subsection * @param name * @param value */ public void addRepositoryConfigProperty(String section, String subsection, String name, String value) { repositoryConfigProperties.add(new RepositoryConfigProperty(section, subsection, name, value)); } /** * @return the repository config property entries */ public List<RepositoryConfigProperty> getRepositoryConfigProperties() { return repositoryConfigProperties; } }
7,728
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/LoginDialog.java
/******************************************************************************* * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com> * Copyright (C) 2010, Edwin Kempin <edwin.kempin@sap.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package com.amazonaws.eclipse.core.egit; import org.eclipse.egit.core.securestorage.UserPasswordCredentials; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIPreferences; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jgit.transport.URIish; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * This class implements a login dialog asking for user and password for a given * URI. */ @SuppressWarnings("restriction") class LoginDialog extends Dialog { private Text user; private Text password; private Button storeCheckbox; private UserPasswordCredentials credentials; private boolean storeInSecureStore; private final URIish uri; private boolean isUserSet; private boolean changeCredentials = false; private String oldUser; LoginDialog(Shell shell, URIish uri) { super(shell); this.uri = uri; isUserSet = uri.getUser() != null && uri.getUser().length() > 0; } @Override protected Control createDialogArea(Composite parent) { final Composite composite = (Composite) super.createDialogArea(parent); composite.setLayout(new GridLayout(2, false)); getShell().setText( changeCredentials ? UIText.LoginDialog_changeCredentials : UIText.LoginDialog_login); Label uriLabel = new Label(composite, SWT.NONE); uriLabel.setText(UIText.LoginDialog_repository); Text uriText = new Text(composite, SWT.READ_ONLY); uriText.setText(uri.toString()); Label userLabel = new Label(composite, SWT.NONE); userLabel.setText(UIText.LoginDialog_user); if (isUserSet) { user = new Text(composite, SWT.BORDER | SWT.READ_ONLY); user.setText(uri.getUser()); } else { user = new Text(composite, SWT.BORDER); if (oldUser != null) user.setText(oldUser); } GridDataFactory.fillDefaults().grab(true, false).applyTo(user); Label passwordLabel = new Label(composite, SWT.NONE); passwordLabel.setText(UIText.LoginDialog_password); password = new Text(composite, SWT.PASSWORD | SWT.BORDER); GridDataFactory.fillDefaults().grab(true, false).applyTo(password); if(!changeCredentials) { Label storeLabel = new Label(composite, SWT.NONE); storeLabel.setText(UIText.LoginDialog_storeInSecureStore); storeCheckbox = new Button(composite, SWT.CHECK); storeCheckbox.setSelection(Activator.getDefault() .getPreferenceStore() .getBoolean(UIPreferences.CLONE_WIZARD_STORE_SECURESTORE)); } if (isUserSet) password.setFocus(); else user.setFocus(); return composite; } UserPasswordCredentials getCredentials() { return credentials; } boolean getStoreInSecureStore() { return storeInSecureStore; } @Override protected void okPressed() { if (user.getText().length() > 0) { credentials = new UserPasswordCredentials(user.getText(), password.getText()); if(!changeCredentials) storeInSecureStore = storeCheckbox.getSelection(); } super.okPressed(); } void setChangeCredentials(boolean changeCredentials) { this.changeCredentials = changeCredentials; } public void setOldUser(String oldUser) { this.oldUser = oldUser; } }
7,729
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/CustomPromptDialog.java
/******************************************************************************* * Copyright (c) 2011 GEBIT Solutions. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Carsten Pfeiffer(GEBIT Solutions) - initial implementation *******************************************************************************/ package com.amazonaws.eclipse.core.egit; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jgit.transport.CredentialItem; import org.eclipse.jgit.transport.CredentialItem.CharArrayType; import org.eclipse.jgit.transport.CredentialItem.StringType; import org.eclipse.jgit.transport.CredentialItem.YesNoType; import org.eclipse.jgit.transport.URIish; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * This dialog is used in order to display information about * authentication problems, and/or request authentication input * from the user. * * The {@link CredentialItem CredentialItems} passed in the constructor * are updated to reflect the user-specified values as soon as the dialog * is confirmed. */ public class CustomPromptDialog extends TrayDialog { private CredentialItem[] credentialItems; private List<Control> editingControls; private URIish uri; private String title; private static final String KEY_ITEM = "item"; //$NON-NLS-1$ /** * Creates an instance of the dialog that will present the given * CredentialItems and let the user supply values for them * @param shell the shell for this dialog * @param uri the uri for which the information shall be displayed * @param title an optional title for this dialog * @param items the items to display and edit */ public CustomPromptDialog(Shell shell, URIish uri, String title, CredentialItem... items) { super(shell); this.uri = uri; this.title = title; setShellStyle(getShellStyle() | SWT.SHELL_TRIM); credentialItems = items; } @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); if (title != null) { newShell.setText(title); } } /** * Returns the credential items that were passed into the constructor. * @return the credential items */ public CredentialItem[] getCredentialItems() { return credentialItems; } @Override protected Control createDialogArea(Composite parent) { editingControls = new ArrayList<>(credentialItems.length); Composite main = (Composite) super.createDialogArea(parent); GridLayout mainLayout = (GridLayout) main.getLayout(); mainLayout.numColumns = 2; Label infoLabel = new Label(main, SWT.NONE); GridDataFactory.defaultsFor(infoLabel).span(2, 1).applyTo(infoLabel); String tempInfoText = hasEditingItems() ? UIText.CustomPromptDialog_provide_information_for : UIText.CustomPromptDialog_information_about; infoLabel.setText(NLS.bind(tempInfoText, uri.toString())); for (CredentialItem item : credentialItems) { Label label = new Label(main, SWT.NONE); label.setText(item.getPromptText()); GridDataFactory.defaultsFor(label).applyTo(label); if (item instanceof CharArrayType || item instanceof StringType) { Text text = new Text(main, SWT.BORDER | (item.isValueSecure() ? SWT.PASSWORD : SWT.NONE)); GridDataFactory.defaultsFor(text).applyTo(text); text.setData(KEY_ITEM, item); editingControls.add(text); } else if (item instanceof YesNoType) { Button checkBox = new Button(main, SWT.CHECK); GridDataFactory.defaultsFor(checkBox).applyTo(checkBox); editingControls.add(checkBox); } else { // unknown type, not editable Label dummy = new Label(main, SWT.NONE); GridDataFactory.fillDefaults().applyTo(dummy); } } return main; } /** * Returns <code>true</code> if there's anything to edit for the user * @return <code>true</code> if the user needs to supply some data */ private boolean hasEditingItems() { for (CredentialItem item : credentialItems) { if (item instanceof StringType) { return true; } if (item instanceof CharArrayType) { return true; } if (item instanceof YesNoType) { return true; } } return false; } @Override protected void okPressed() { updateValues(); super.okPressed(); } /** * Updates all {@link CredentialItem CredentialItems} with the * user-supplied values. */ private void updateValues() { for (Control control : editingControls) { if (control instanceof Text) { Text textControl = (Text) control; CredentialItem itemToUpdate = (CredentialItem) textControl.getData(KEY_ITEM); String value = textControl.getText(); updateValue(itemToUpdate, value); } else if (control instanceof Button) { Button checkBoxControl = (Button) control; CredentialItem itemToUpdate = (CredentialItem) checkBoxControl.getData(KEY_ITEM); boolean value = checkBoxControl.getSelection(); updateValue(itemToUpdate, value); } } } /** * Updates the value of the given {@link CredentialItem}. * @param itemToUpdate the item to update * @param value the new value */ protected void updateValue(CredentialItem itemToUpdate, String value) { if (itemToUpdate instanceof CharArrayType) { ((CharArrayType) itemToUpdate).setValueNoCopy(value.toCharArray()); } else if (itemToUpdate instanceof StringType) { ((StringType) itemToUpdate).setValue(value); } else { throw new IllegalArgumentException("Cannot handle item of type " + itemToUpdate.getClass()); //$NON-NLS-1$ } } /** * Updates the value of the given {@link CredentialItem}. * @param itemToUpdate the item to update * @param value the new value */ protected void updateValue(CredentialItem itemToUpdate, boolean value) { if (itemToUpdate instanceof YesNoType) { ((YesNoType) itemToUpdate).setValue(value); } else { throw new IllegalArgumentException("Cannot handle item of type " + itemToUpdate.getClass()); //$NON-NLS-1$ } } }
7,730
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/SecureStoreUtils.java
/******************************************************************************* * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com> * Copyright (C) 2010, Philipp Thun <philipp.thun@sap.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package com.amazonaws.eclipse.core.egit; import java.io.IOException; import org.eclipse.egit.core.securestorage.UserPasswordCredentials; import org.eclipse.egit.ui.Activator; import org.eclipse.equinox.security.storage.StorageException; import org.eclipse.jgit.transport.URIish; /** * Utilities for EGit secure store */ @SuppressWarnings("restriction") public class SecureStoreUtils { /** * Store credentials for the given uri * * @param credentials * @param uri * @return true if successful */ public static boolean storeCredentials(UserPasswordCredentials credentials, URIish uri) { if (credentials != null && uri != null) { try { org.eclipse.egit.core.Activator.getDefault().getSecureStore() .putCredentials(uri, credentials); } catch (StorageException e) { Activator.handleError( UIText.SecureStoreUtils_writingCredentialsFailed, e, true); return false; } catch (IOException e) { Activator.handleError( UIText.SecureStoreUtils_writingCredentialsFailed, e, true); return false; } } return true; } /** * Gets credentials stored for the given uri. Logs but does not re-throw * {@code StorageException} if thrown by the secure store implementation * * @param uri * @return credentials stored in secure store for given uri */ public static UserPasswordCredentials getCredentialsQuietly( final URIish uri) { try { return org.eclipse.egit.core.Activator.getDefault() .getSecureStore().getCredentials(uri); } catch (StorageException e) { Activator.logError( UIText.EGitCredentialsProvider_errorReadingCredentials, e); } return null; } /** * Gets credentials stored for the given uri. Logs and re-throws * {@code StorageException} if thrown by the secure store implementation * * @param uri * @return credentials stored in secure store for given uri * @throws StorageException */ public static UserPasswordCredentials getCredentials( final URIish uri) throws StorageException { try { return org.eclipse.egit.core.Activator.getDefault() .getSecureStore().getCredentials(uri); } catch (StorageException e) { Activator.logError( UIText.EGitCredentialsProvider_errorReadingCredentials, e); throw e; } } }
7,731
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/UIText.java
/******************************************************************************* * Copyright (C) 2008, Roger C. Soares <rogersoares@intelinet.com.br> * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> * Copyright (C) 2010, 2013 Matthias Sohn <matthias.sohn@sap.com> * Copyright (C) 2011, Daniel Megert <daniel_megert@ch.ibm.com> * Copyright (C) 2012, Mathias Kinzler <mathias.kinzler@sap.com> * Copyright (C) 2012, Daniel Megert <daniel_megert@ch.ibm.com> * Copyright (C) 2012, 2013 Robin Stocker <robin@nibor.org> * Copyright (C) 2012, Laurent Goubet <laurent.goubet@obeo.fr> * Copyright (C) 2012, Gunnar Wagenknecht <gunnar@wagenknecht.org> * Copyright (C) 2013, Ben Hammen <hammenb@gmail.com> * Copyright (C) 2014, Marc Khouzam <marc.khouzam@ericsson.com> * Copyright (C) 2014, Red Hat Inc. * Copyright (C) 2014, Axel Richard <axel.richard@obeo.fr> * Copyright (C) 2015, SAP SE (Christian Georgi <christian.georgi@sap.com>) * Copyright (C) 2015, Jan-Ove Weichel <ovi.weichel@gmail.com> * Copyright (C) 2015, Laurent Delaigue <laurent.delaigue@obeo.fr> * Copyright (C) 2015, Denis Zygann <d.zygann@web.de> * Copyright (C) 2016, Lars Vogel <Lars.Vogel@vogella.com> * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package com.amazonaws.eclipse.core.egit; /** * Text resources for the plugin. Strings here can be i18n-ed simpler and avoid * duplicating strings. */ public class UIText { /** */ public static String SourceBranchPage_repoEmpty = "Source Git repository is empty"; /** */ public static String SourceBranchPage_title = "Branch Selection"; /** */ public static String SourceBranchPage_description = "Select branches to clone from remote repository. Remote tracking " + "branches will be created to track updates for these branches in the remote repository."; /** */ public static String SourceBranchPage_branchList = "Branches of {0}"; /** */ public static String SourceBranchPage_selectAll = "Select All"; /** */ public static String SourceBranchPage_selectNone = "Deselect All"; /** */ public static String SourceBranchPage_errorBranchRequired = "At least one branch must be selected."; /** */ public static String SourceBranchPage_remoteListingCancelled = "Operation canceled"; /** */ public static String SourceBranchPage_cannotCreateTemp = "Couldn't create temporary repository."; /** */ public static String SourceBranchPage_CompositeTransportErrorMessage = "{0}:\n{1}"; /** */ public static String SourceBranchPage_AuthFailMessage = "{0}:\nInvalid password or missing SSH key."; /** */ public static String CloneDestinationPage_title = "Local Destination"; /** */ public static String CloneDestinationPage_description = "Configure the local storage location for {0}."; /** */ public static String CloneDestinationPage_groupDestination = "Destination"; /** */ public static String CloneDestinationPage_groupConfiguration = "Configuration"; /** */ public static String CloneDestinationPage_groupProjects = "Projects"; /** */ public static String CloneDestinationPage_promptDirectory = "&Directory"; /** */ public static String CloneDestinationPage_promptInitialBranch = "Initial branc&h"; /** */ public static String CloneDestinationPage_promptRemoteName = "Remote na&me"; /** */ public static String CloneDestinationPage_browseButton = "Bro&wse"; /** */ public static String CloneDestinationPage_cloneSubmodulesButton = "Clone &submodules"; /** */ public static String CloneDestinationPage_DefaultRepoFolderTooltip = "You can change the default parent folder in the Git preferences"; /** */ public static String CloneDestinationPage_errorDirectoryRequired = "Directory is required"; /** */ public static String CloneDestinationPage_errorInitialBranchRequired = "Initial branch is required"; /** */ public static String CloneDestinationPage_errorInvalidRemoteName = "Invalid remote name ''{0}''"; /** */ public static String CloneDestinationPage_errorNotEmptyDir = "{0} is not an empty directory."; /** */ public static String CloneDestinationPage_errorRemoteNameRequired = "Remote name is required"; /** */ public static String CloneDestinationPage_importButton = "&Import all existing Eclipse projects after clone finishes"; /** */ public static String GitCreateProjectViaWizardWizard_AbortedMessage = "Action was aborted"; /** */ public static String GitImportWizard_errorParsingURI = "The URI of the repository to be cloned can't be parsed"; /** */ public static String CustomPromptDialog_provide_information_for = "Provide information for {0}"; /** */ public static String CustomPromptDialog_information_about = "Information about {0}"; public static String EGitCredentialsProvider_FailedToClearCredentials = "Failed to clear credentials for {0} stored in secure store"; public static String EGitCredentialsProvider_question = "Question"; public static String EGitCredentialsProvider_information = "Information"; public static String EGitCredentialsProvider_errorReadingCredentials = "Failed reading credentials from secure store"; public static String LoginDialog_changeCredentials = "Change stored credentials"; public static String LoginDialog_login = "Login"; public static String LoginDialog_password = "Password"; public static String LoginDialog_repository = "Repository"; public static String LoginDialog_storeInSecureStore = "Store in Secure Store"; public static String LoginDialog_user = "User"; public static String SecureStoreUtils_writingCredentialsFailed = "Writing to secure store failed"; public static String CloneFailureDialog_tile = "Transport Error"; public static String CloneFailureDialog_dontShowAgain = "Don't show this dialog again"; public static String CloneFailureDialog_checkList = "An error occurred when trying to contact {0}.\nSee the Error Log for more details\n\nPossible reasons:\nIncorrect URL\nNo network connection (e.g. wrong proxy settings)"; public static String CloneFailureDialog_checkList_git = "\n.git is missing at end of repository URL"; public static String CloneFailureDialog_checkList_ssh = "\nSSH is not configured correctly (see Eclipse preferences > Network Connections > SSH2)"; public static String CloneFailureDialog_checkList_https = "\nSSL host could not be verified (set http.sslVerify=false in Git configuration)"; public static String GitCloneWizard_failed = "Git repository clone failed."; public static String GitCloneWizard_jobName = "Cloning from {0}"; public static String GitCloneWizard_errorCannotCreate = "Cannot create directory {0}."; }
7,732
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/SourceBranchFailureDialog.java
/******************************************************************************* * Copyright (C) 2012, Dariusz Luksza <dariusz@luksza.org> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package com.amazonaws.eclipse.core.egit; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIPreferences; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jgit.transport.URIish; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.Bullet; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.GlyphMetrics; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; /** * Creates and shows custom error dialog for failed ls-remotes operation */ @SuppressWarnings("restriction") public class SourceBranchFailureDialog extends MessageDialog { /** * Creates and shows custom error dialog for failed ls-remotes operation * * @param parentShell * @param uri * the uri of the remote repository */ public static void show(Shell parentShell, URIish uri) { SourceBranchFailureDialog dialog = new SourceBranchFailureDialog( parentShell, uri); dialog.setShellStyle(dialog.getShellStyle() | SWT.SHEET | SWT.RESIZE); dialog.open(); } private Button toggleButton; private URIish uri; private SourceBranchFailureDialog(Shell parentShell, URIish uri) { super(parentShell, UIText.CloneFailureDialog_tile, null, null, MessageDialog.ERROR, new String[] { IDialogConstants.OK_LABEL }, 0); this.uri = uri; } @Override protected void buttonPressed(int buttonId) { if (toggleButton != null) Activator .getDefault() .getPreferenceStore() .setValue(UIPreferences.CLONE_WIZARD_SHOW_DETAILED_FAILURE_DIALOG, !toggleButton.getSelection()); super.buttonPressed(buttonId); } @Override protected Control createMessageArea(Composite composite) { Composite main = new Composite(composite, SWT.NONE); main.setLayout(new GridLayout(2, false)); GridDataFactory.fillDefaults().indent(0, 0).grab(true, true) .applyTo(main); // add error image super.createMessageArea(main); StyledText text = new StyledText(main, SWT.FULL_SELECTION | SWT.WRAP); text.setEnabled(false); text.setBackground(main.getBackground()); String messageText = NLS.bind(UIText.CloneFailureDialog_checkList, uri.toString()); int bullets = 2; if (!uri.getPath().endsWith(".git")) { //$NON-NLS-1$ messageText = messageText + UIText.CloneFailureDialog_checkList_git; bullets += 1; } if ("ssh".equals(uri.getScheme())) { //$NON-NLS-1$ messageText = messageText + UIText.CloneFailureDialog_checkList_ssh; bullets += 1; } else if ("https".equals(uri.getScheme())) { //$NON-NLS-1$ messageText = messageText + UIText.CloneFailureDialog_checkList_https; bullets += 1; } int newLinesCount = messageText.split("\n").length; //$NON-NLS-1$ Bullet bullet = createBullet(main); text.setText(messageText); text.setLineBullet(newLinesCount - bullets, bullets, bullet); return main; } private Bullet createBullet(Composite main) { StyleRange style = new StyleRange(); style.metrics = new GlyphMetrics(0, 0, 40); style.foreground = main.getDisplay().getSystemColor(SWT.COLOR_BLACK); Bullet bullet = new Bullet(style); return bullet; } @Override protected Control createCustomArea(Composite parent) { toggleButton = new Button(parent, SWT.CHECK | SWT.LEFT); toggleButton.setText(UIText.CloneFailureDialog_dontShowAgain); return null; } }
7,733
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/LoginService.java
/******************************************************************************* * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package com.amazonaws.eclipse.core.egit; import org.eclipse.egit.core.securestorage.UserPasswordCredentials; import org.eclipse.jface.window.Window; import org.eclipse.jgit.transport.URIish; import org.eclipse.swt.widgets.Shell; /** * This class implements services for interactive login and changing stored * credentials. */ @SuppressWarnings("restriction") public class LoginService { /** * The method shows a login dialog for a given URI. The user field is taken * from the URI if a user is present in the URI. In this case the user is * not editable. * * @param parent * @param uri * @return credentials, <code>null</code> if the user canceled the dialog. */ public static UserPasswordCredentials login(Shell parent, URIish uri) { LoginDialog dialog = new LoginDialog(parent, uri); if (dialog.open() == Window.OK) { UserPasswordCredentials credentials = dialog.getCredentials(); if (credentials != null && dialog.getStoreInSecureStore()) SecureStoreUtils.storeCredentials(credentials, uri); return credentials; } return null; } /** * The method shows a change credentials dialog for a given URI. The user * field is taken from the URI if a user is present in the URI. In this case * the user is not editable. * * @param parent * @param uri * @return credentials, <code>null</code> if the user canceled the dialog. */ public static UserPasswordCredentials changeCredentials(Shell parent, URIish uri) { LoginDialog dialog = new LoginDialog(parent, uri); dialog.setChangeCredentials(true); UserPasswordCredentials oldCredentials = SecureStoreUtils .getCredentialsQuietly(uri); if (oldCredentials != null) dialog.setOldUser(oldCredentials.getUser()); if (dialog.open() == Window.OK) { UserPasswordCredentials credentials = dialog.getCredentials(); if (credentials != null) SecureStoreUtils.storeCredentials(credentials, uri); return credentials; } return null; } }
7,734
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/ui/CachedCheckboxTreeViewer.java
/******************************************************************************* * Copyright (c) 2010 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Chris Aniszczyk <caniszczyk@gmail.com> - initial implementation *******************************************************************************/ package com.amazonaws.eclipse.core.egit.ui; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTreeViewer; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.dialogs.ContainerCheckedTreeViewer; /** * Copy of ContainerCheckedTreeViewer which is specialized for use * with {@link FilteredCheckboxTree}. This container caches * the check state of leaf nodes in the tree. When a filter * is applied the cache stores which nodes are checked. When * a filter is removed the viewer can be told to restore check * state from the cache. This viewer updates the check state of * parent items the same way as {@link CachedCheckboxTreeViewer} * <p> * Note: If duplicate items are added to the tree the cache will treat them * as a single entry. * </p> */ public class CachedCheckboxTreeViewer extends ContainerCheckedTreeViewer { private final Set<Object> checkState = new HashSet<>(); /** * Constructor for ContainerCheckedTreeViewer. * @see CheckboxTreeViewer#CheckboxTreeViewer(Tree) */ protected CachedCheckboxTreeViewer(Tree tree) { super(tree); addCheckStateListener(new ICheckStateListener() { @Override public void checkStateChanged(CheckStateChangedEvent event) { updateCheckState(event.getElement(), event.getChecked()); } }); setUseHashlookup(true); } /** * @param element * @param state */ protected void updateCheckState(final Object element, final boolean state) { if (state) { // Add the item (or its children) to the cache ITreeContentProvider contentProvider = null; if (getContentProvider() instanceof ITreeContentProvider) { contentProvider = (ITreeContentProvider) getContentProvider(); } if (contentProvider != null) { Object[] children = contentProvider.getChildren(element); if (children != null && children.length > 0) { for (int i = 0; i < children.length; i++) { updateCheckState(children[i], state); } } else { checkState.add(element); } } else { checkState.add(element); } } else if (checkState != null) { // Remove the item (or its children) from the cache ITreeContentProvider contentProvider = null; if (getContentProvider() instanceof ITreeContentProvider) { contentProvider = (ITreeContentProvider) getContentProvider(); } if (contentProvider != null) { Object[] children = contentProvider.getChildren(element); if (children !=null && children.length > 0) { for (int i = 0; i < children.length; i++) { updateCheckState(children[i], state); } } } checkState.remove(element); } } /** * Restores the checked state of items based on the cached check state. This * will only check leaf nodes, but parent items will be updated by the container * viewer. No events will be fired. */ public void restoreLeafCheckState() { if (checkState == null) return; getTree().setRedraw(false); // Call the super class so we don't mess up the cache super.setCheckedElements(new Object[0]); setGrayedElements(new Object[0]); // Now we are only going to set the check state of the leaf nodes // and rely on our container checked code to update the parents properly. Iterator iter = checkState.iterator(); Object element = null; if (iter.hasNext()) expandAll(); while (iter.hasNext()) { element = iter.next(); // Call the super class as there is no need to update the check state super.setChecked(element, true); } getTree().setRedraw(true); } /** * Returns the contents of the cached check state. The contents will be all * checked leaf nodes ignoring any filters. * * @return checked leaf elements */ public Object[] getCheckedLeafElements() { if (checkState == null) { return new Object[0]; } return checkState.toArray(new Object[checkState.size()]); } /** * Returns the number of leaf nodes checked. This method uses its internal check * state cache to determine what has been checked, not what is visible in the viewer. * The cache does not count duplicate items in the tree. * * @return number of leaf nodes checked according to the cached check state */ public int getCheckedLeafCount() { if (checkState == null) { return 0; } return checkState.size(); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ICheckable#setChecked(java.lang.Object, boolean) */ @Override public boolean setChecked(Object element, boolean state) { updateCheckState(element, state); return super.setChecked(element, state); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.CheckboxTreeViewer#setCheckedElements(java.lang.Object[]) */ @Override public void setCheckedElements(Object[] elements) { super.setCheckedElements(elements); checkState.clear(); ITreeContentProvider contentProvider = null; if (getContentProvider() instanceof ITreeContentProvider) { contentProvider = (ITreeContentProvider) getContentProvider(); } for (int i = 0; i < elements.length; i++) { Object[] children = contentProvider != null ? contentProvider.getChildren(elements[i]) : null; if (!getGrayed(elements[i]) && (children == null || children.length == 0)) { if (!checkState.contains(elements[i])) { checkState.add(elements[i]); } } } } /* (non-Javadoc) * @see org.eclipse.jface.viewers.CheckboxTreeViewer#setAllChecked(boolean) */ @Override public void setAllChecked(boolean state) { for (TreeItem item: super.getTree().getItems()) item.setChecked(state); if (state) { // Find all visible children, add only the visible leaf nodes to the check state cache Object[] visible = getFilteredChildren(getRoot()); ITreeContentProvider contentProvider = null; if (getContentProvider() instanceof ITreeContentProvider) { contentProvider = (ITreeContentProvider) getContentProvider(); } if (contentProvider == null) { for (int i = 0; i < visible.length; i++) { checkState.add(visible[i]); } } else { Set<Object> toCheck = new HashSet<>(); for (int i = 0; i < visible.length; i++) { addFilteredChildren(visible[i], contentProvider, toCheck); } checkState.addAll(toCheck); } } else { // Remove any item in the check state that is visible (passes the filters) if (checkState != null) { Object[] visible = filter(checkState.toArray()); for (int i = 0; i < visible.length; i++) { checkState.remove(visible[i]); } } } } /** * If the element is a leaf node, it is added to the result collection. If the element has * children, this method will recursively look at the children and add any visible leaf nodes * to the collection. * * @param element element to check * @param contentProvider tree content provider to check for children * @param result collection to collect leaf nodes in */ private void addFilteredChildren(Object element, ITreeContentProvider contentProvider, Collection<Object> result) { if (!contentProvider.hasChildren(element)) { result.add(element); } else { Object[] visibleChildren = getFilteredChildren(element); for (int i = 0; i < visibleChildren.length; i++) { addFilteredChildren(visibleChildren[i], contentProvider, result); } } } /* (non-Javadoc) * @see org.eclipse.jface.viewers.AbstractTreeViewer#remove(java.lang.Object[]) */ @Override public void remove(Object[] elementsOrTreePaths) { for (int i = 0; i < elementsOrTreePaths.length; i++) { updateCheckState(elementsOrTreePaths[i], false); } super.remove(elementsOrTreePaths); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.AbstractTreeViewer#remove(java.lang.Object) */ @Override public void remove(Object elementsOrTreePaths) { updateCheckState(elementsOrTreePaths, false); super.remove(elementsOrTreePaths); } }
7,735
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/ui/FilteredCheckboxTree.java
/******************************************************************************* * Copyright (c) 2010 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Chris Aniszczyk <caniszczyk@gmail.com> - initial implementation *******************************************************************************/ package com.amazonaws.eclipse.core.egit.ui; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.ui.dialogs.FilteredTree; import org.eclipse.ui.dialogs.PatternFilter; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.progress.WorkbenchJob; /** * A FilteredCheckboxTree implementation to be used internally in EGit code. This tree stores * all the tree elements internally, and keeps the check state in sync. This way, even if an * element is filtered, the caller can get and set the checked state. */ public class FilteredCheckboxTree extends FilteredTree { private static final long FILTER_DELAY = 400; FormToolkit fToolkit; CachedCheckboxTreeViewer checkboxViewer; /** * Constructor that creates a tree with preset style bits and a CachedContainerCheckedTreeViewer for the tree. * * @param parent parent composite * @param toolkit optional toolkit to create UI elements with, required if the tree is being created in a form editor */ public FilteredCheckboxTree(Composite parent, FormToolkit toolkit) { this(parent, toolkit, SWT.NONE); } /** * Constructor that creates a tree with preset style bits and a CachedContainerCheckedTreeViewer for the tree. * * @param parent parent composite * @param toolkit optional toolkit to create UI elements with, required if the tree is being created in a form editor * @param treeStyle */ public FilteredCheckboxTree(Composite parent, FormToolkit toolkit, int treeStyle) { this(parent, toolkit, treeStyle, new PatternFilter()); } /** * Constructor that creates a tree with preset style bits and a CachedContainerCheckedTreeViewer for the tree. * * @param parent parent composite * @param toolkit optional toolkit to create UI elements with, required if the tree is being created in a form editor * @param treeStyle * @param filter pattern filter to use in the filter control */ public FilteredCheckboxTree(Composite parent, FormToolkit toolkit, int treeStyle, PatternFilter filter) { super(parent, treeStyle, filter, true); fToolkit = toolkit; } /* (non-Javadoc) * @see org.eclipse.ui.dialogs.FilteredTree#doCreateTreeViewer(org.eclipse.swt.widgets.Composite, int) */ @Override protected TreeViewer doCreateTreeViewer(Composite actParent, int style) { int treeStyle = style | SWT.CHECK | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER; Tree tree = null; if (fToolkit != null) { tree = fToolkit.createTree(actParent, treeStyle); } else { tree = new Tree(actParent, treeStyle); } checkboxViewer = new CachedCheckboxTreeViewer(tree); return checkboxViewer; } /* * Overridden to hook a listener on the job and set the deferred content provider * to synchronous mode before a filter is done. * @see org.eclipse.ui.dialogs.FilteredTree#doCreateRefreshJob() */ @Override protected WorkbenchJob doCreateRefreshJob() { WorkbenchJob filterJob = super.doCreateRefreshJob(); filterJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { if (event.getResult().isOK()) { getDisplay().asyncExec(new Runnable() { @Override public void run() { if (checkboxViewer.getTree().isDisposed()) return; checkboxViewer.restoreLeafCheckState(); } }); } } }); return filterJob; } /* (non-Javadoc) * @see org.eclipse.ui.dialogs.FilteredTree#doCreateFilterText(org.eclipse.swt.widgets.Composite) */ @Override protected Text doCreateFilterText(Composite actParent) { // Overridden so the text gets create using the toolkit if we have one Text parentText = super.doCreateFilterText(actParent); if (fToolkit != null) { int style = parentText.getStyle(); parentText.dispose(); return fToolkit.createText(actParent, null, style); } return parentText; } /** * Clears the filter */ public void clearFilter() { getPatternFilter().setPattern(null); setFilterText(getInitialText()); textChanged(); } /** * @return The checkbox treeviewer */ public CachedCheckboxTreeViewer getCheckboxTreeViewer() { return checkboxViewer; } @Override protected long getRefreshJobDelay() { return FILTER_DELAY; } }
7,736
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/ui/CloneDestinationPage.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.egit.ui; import java.io.File; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.core.variables.IStringVariableManager; import org.eclipse.core.variables.VariablesPlugin; import org.eclipse.egit.ui.Activator; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.util.FS; import org.eclipse.jgit.util.StringUtils; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import com.amazonaws.eclipse.core.egit.RepositorySelection; import com.amazonaws.eclipse.core.egit.UIText; /** * Wizard page that allows the user entering the location of a repository to be * cloned. */ @SuppressWarnings("restriction") public class CloneDestinationPage extends WizardPage { private final List<Ref> availableRefs = new ArrayList<>(); private RepositorySelection validatedRepoSelection; private List<Ref> validatedSelectedBranches; private Ref validatedHEAD; private ComboViewer initialBranch; private Text directoryText; private Text remoteText; private Button cloneSubmodulesButton; private String helpContext = null; private File clonedDestination; private Ref clonedInitialBranch; private String clonedRemote; public CloneDestinationPage() { super(CloneDestinationPage.class.getName()); setTitle(UIText.CloneDestinationPage_title); } @Override public void createControl(final Composite parent) { final Composite panel = new Composite(parent, SWT.NULL); final GridLayout layout = new GridLayout(); layout.numColumns = 1; panel.setLayout(layout); createDestinationGroup(panel); createConfigGroup(panel); Dialog.applyDialogFont(panel); setControl(panel); checkPage(); } @Override public void setVisible(final boolean visible) { if (visible) if (this.availableRefs.isEmpty()) initialBranch.getCombo().setEnabled(false); super.setVisible(visible); if (visible) directoryText.setFocus(); } public void setSelection(RepositorySelection repositorySelection, List<Ref> availableRefs, List<Ref> branches, Ref head){ this.availableRefs.clear(); this.availableRefs.addAll(availableRefs); checkPreviousPagesSelections(repositorySelection, branches, head); revalidate(repositorySelection,branches, head); } private void checkPreviousPagesSelections( RepositorySelection repositorySelection, List<Ref> branches, Ref head) { if (!repositorySelection.equals(validatedRepoSelection) || !branches.equals(validatedSelectedBranches) || !head.equals(validatedHEAD)) setPageComplete(false); else checkPage(); } private void createDestinationGroup(final Composite parent) { final Group g = createGroup(parent, UIText.CloneDestinationPage_groupDestination); Label dirLabel = new Label(g, SWT.NONE); dirLabel.setText(UIText.CloneDestinationPage_promptDirectory + ":"); //$NON-NLS-1$ dirLabel.setToolTipText(UIText.CloneDestinationPage_DefaultRepoFolderTooltip); final Composite p = new Composite(g, SWT.NONE); final GridLayout grid = new GridLayout(); grid.numColumns = 2; p.setLayout(grid); p.setLayoutData(createFieldGridData()); directoryText = new Text(p, SWT.BORDER); directoryText.setLayoutData(createFieldGridData()); directoryText.addModifyListener(new ModifyListener() { @Override public void modifyText(final ModifyEvent e) { checkPage(); } }); final Button b = new Button(p, SWT.PUSH); b.setText(UIText.CloneDestinationPage_browseButton); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { final FileDialog d; d = new FileDialog(getShell(), SWT.APPLICATION_MODAL | SWT.SAVE); if (directoryText.getText().length() > 0) { final File file = new File(directoryText.getText()) .getAbsoluteFile(); d.setFilterPath(file.getParent()); d.setFileName(file.getName()); } final String r = d.open(); if (r != null) directoryText.setText(r); } }); newLabel(g, UIText.CloneDestinationPage_promptInitialBranch + ":"); //$NON-NLS-1$ initialBranch = new ComboViewer(g, SWT.DROP_DOWN | SWT.READ_ONLY); initialBranch.getCombo().setLayoutData(createFieldGridData()); initialBranch.getCombo().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { checkPage(); } }); initialBranch.setContentProvider(ArrayContentProvider.getInstance()); initialBranch.setLabelProvider(new LabelProvider(){ @Override public String getText(Object element) { if (((Ref)element).getName().startsWith(Constants.R_HEADS)) return ((Ref)element).getName().substring(Constants.R_HEADS.length()); return ((Ref)element).getName(); } }); cloneSubmodulesButton = new Button(g, SWT.CHECK); cloneSubmodulesButton .setText(UIText.CloneDestinationPage_cloneSubmodulesButton); GridDataFactory.swtDefaults().span(2, 1).applyTo(cloneSubmodulesButton); } private void createConfigGroup(final Composite parent) { final Group g = createGroup(parent, UIText.CloneDestinationPage_groupConfiguration); newLabel(g, UIText.CloneDestinationPage_promptRemoteName + ":"); //$NON-NLS-1$ remoteText = new Text(g, SWT.BORDER); remoteText.setText(Constants.DEFAULT_REMOTE_NAME); remoteText.setLayoutData(createFieldGridData()); remoteText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { checkPage(); } }); } private static Group createGroup(final Composite parent, final String text) { final Group g = new Group(parent, SWT.NONE); final GridLayout layout = new GridLayout(); layout.numColumns = 2; g.setLayout(layout); g.setText(text); final GridData gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalAlignment = SWT.FILL; g.setLayoutData(gd); return g; } private static void newLabel(final Group g, final String text) { new Label(g, SWT.NULL).setText(text); } private static GridData createFieldGridData() { return new GridData(SWT.FILL, SWT.DEFAULT, true, false); } /** * @return true to clone submodules, false otherwise */ public boolean isCloneSubmodules() { return cloneSubmodulesButton != null && cloneSubmodulesButton.getSelection(); } /** * @return location the user wants to store this repository. */ public File getDestinationFile() { return new File(directoryText.getText()); } /** * @return initial branch selected (includes refs/heads prefix). */ public Ref getInitialBranch() { IStructuredSelection selection = (IStructuredSelection)initialBranch.getSelection(); return (Ref)selection.getFirstElement(); } /** * @return remote name */ public String getRemote() { return remoteText.getText().trim(); } /** * Set the ID for context sensitive help * * @param id * help context */ public void setHelpContext(String id) { helpContext = id; } @Override public void performHelp() { PlatformUI.getWorkbench().getHelpSystem().displayHelp(helpContext); } /** * Check internal state for page completion status. */ private void checkPage() { if (!cloneSettingsChanged()) { setErrorMessage(null); setPageComplete(true); return; } final String dstpath = directoryText.getText(); if (dstpath.length() == 0) { setErrorMessage(UIText.CloneDestinationPage_errorDirectoryRequired); setPageComplete(false); return; } final File absoluteFile = new File(dstpath).getAbsoluteFile(); if (!isEmptyDir(absoluteFile)) { setErrorMessage(NLS.bind( UIText.CloneDestinationPage_errorNotEmptyDir, absoluteFile .getPath())); setPageComplete(false); return; } if (!canCreateSubdir(absoluteFile.getParentFile())) { setErrorMessage(NLS.bind(UIText.GitCloneWizard_errorCannotCreate, absoluteFile.getPath())); setPageComplete(false); return; } if (!availableRefs.isEmpty() && initialBranch.getCombo().getSelectionIndex() < 0) { setErrorMessage(UIText.CloneDestinationPage_errorInitialBranchRequired); setPageComplete(false); return; } String remoteName = getRemote(); if (remoteName.length() == 0) { setErrorMessage(UIText.CloneDestinationPage_errorRemoteNameRequired); setPageComplete(false); return; } if (!Repository.isValidRefName(Constants.R_REMOTES + remoteName)) { setErrorMessage(NLS.bind( UIText.CloneDestinationPage_errorInvalidRemoteName, remoteName)); setPageComplete(false); return; } setErrorMessage(null); setPageComplete(true); } public void saveSettingsForClonedRepo() { clonedDestination = getDestinationFile(); clonedInitialBranch = getInitialBranch(); clonedRemote = getRemote(); } public boolean cloneSettingsChanged() { boolean cloneSettingsChanged = false; if (clonedDestination == null || !clonedDestination.equals(getDestinationFile()) || clonedInitialBranch == null || !clonedInitialBranch.equals(getInitialBranch()) || clonedRemote == null || !clonedRemote.equals(getRemote())) cloneSettingsChanged = true; return cloneSettingsChanged; } private static boolean isEmptyDir(final File dir) { if (!dir.exists()) return true; if (!dir.isDirectory()) return false; return dir.listFiles().length == 0; } // this is actually just an optimistic heuristic - should be named // isThereHopeThatCanCreateSubdir() as probably there is no 100% reliable // way to check that in Java for Windows private static boolean canCreateSubdir(final File parent) { if (parent == null) return true; if (parent.exists()) return parent.isDirectory() && parent.canWrite(); return canCreateSubdir(parent.getParentFile()); } private void revalidate(RepositorySelection repoSelection, List<Ref> branches, Ref head) { if (repoSelection.equals(validatedRepoSelection) && branches.equals(validatedSelectedBranches) && head.equals(validatedHEAD)) { checkPage(); return; } if (!repoSelection.equals(validatedRepoSelection)) { validatedRepoSelection = repoSelection; // update repo-related selection only if it changed final String n = validatedRepoSelection.getURI().getHumanishName(); setDescription(NLS.bind(UIText.CloneDestinationPage_description, n)); String defaultRepoDir = getDefaultRepositoryDir(); File parentDir; if (defaultRepoDir.length() > 0) parentDir = new File(defaultRepoDir); else parentDir = ResourcesPlugin.getWorkspace().getRoot() .getRawLocation().toFile(); directoryText.setText(new File(parentDir, n).getAbsolutePath()); } validatedSelectedBranches = branches; validatedHEAD = head; initialBranch.setInput(branches); if (head != null && branches.contains(head)) initialBranch.setSelection(new StructuredSelection(head)); else if (branches.size() > 0) initialBranch .setSelection(new StructuredSelection(branches.get(0))); checkPage(); } /** * @return The default repository directory as configured in the preferences, with variables * substituted. Root directory of current workspace if there was an error during substitution. */ public static String getDefaultRepositoryDir() { // If the EGit version is prior to 4.1, return the setting from the legacy code path. String dir = Activator.getDefault().getPreferenceStore().getString("default_repository_dir"); if (StringUtils.isEmptyOrNull(dir)) { // If the EGit version is after 4.1, read the preference setting from Core plugin. IEclipsePreferences p = InstanceScope.INSTANCE.getNode(org.eclipse.egit.core.Activator.getPluginId()); dir = p.get("core_defaultRepositoryDir", new File(FS.DETECTED.userHome(), "git").getPath()); } IStringVariableManager manager = VariablesPlugin.getDefault().getStringVariableManager(); try { return manager.performStringSubstitution(dir); } catch (CoreException e) { return ResourcesPlugin.getWorkspace().getRoot().getRawLocation().toOSString(); } } }
7,737
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/ui/SourceBranchPage.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.egit.ui; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.egit.core.op.ListRemoteOperation; import org.eclipse.egit.core.securestorage.UserPasswordCredentials; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIPreferences; import org.eclipse.egit.ui.internal.repository.tree.RepositoryTreeNodeType; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.jgit.api.errors.TransportException; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.transport.URIish; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.PatternFilter; import org.eclipse.ui.progress.WorkbenchJob; import com.amazonaws.eclipse.core.egit.EGitCredentialsProvider; import com.amazonaws.eclipse.core.egit.RepositorySelection; import com.amazonaws.eclipse.core.egit.SourceBranchFailureDialog; import com.amazonaws.eclipse.core.egit.UIText; @SuppressWarnings("restriction") public class SourceBranchPage extends WizardPage { private RepositorySelection validatedRepoSelection; private Ref head; private final List<Ref> availableRefs = new ArrayList<>(); private Label label; private String transportError; private Button selectB; private Button unselectB; private CachedCheckboxTreeViewer refsViewer; private UserPasswordCredentials credentials; private String helpContext = null; public SourceBranchPage() { super(SourceBranchPage.class.getName()); setTitle(UIText.SourceBranchPage_title); setDescription(UIText.SourceBranchPage_description); } public List<Ref> getSelectedBranches() { Object[] checkedElements = refsViewer.getCheckedElements(); Ref[] checkedRefs = new Ref[checkedElements.length]; System.arraycopy(checkedElements, 0, checkedRefs, 0, checkedElements.length); return Arrays.asList(checkedRefs); } public List<Ref> getAvailableBranches() { return availableRefs; } public Ref getHEAD() { return head; } public boolean isSourceRepoEmpty() { return availableRefs.isEmpty(); } public boolean isAllSelected() { return availableRefs.size() == refsViewer.getCheckedElements().length; } @Override public void createControl(final Composite parent) { final Composite panel = new Composite(parent, SWT.NULL); final GridLayout layout = new GridLayout(); layout.numColumns = 1; panel.setLayout(layout); label = new Label(panel, SWT.NONE); label.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); FilteredCheckboxTree fTree = new FilteredCheckboxTree(panel, null, SWT.NONE, new PatternFilter()) { /* * Overridden to check page when refreshing is done. */ @Override protected WorkbenchJob doCreateRefreshJob() { WorkbenchJob refreshJob = super.doCreateRefreshJob(); refreshJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { if (event.getResult().isOK()) { getDisplay().asyncExec(new Runnable() { @Override public void run() { checkPage(); } }); } } }); return refreshJob; } }; refsViewer = fTree.getCheckboxTreeViewer(); ITreeContentProvider provider = new ITreeContentProvider() { @Override public void inputChanged(Viewer arg0, Object arg1, Object arg2) { // nothing } @Override public void dispose() { // nothing } @Override public Object[] getElements(Object input) { return ((List) input).toArray(); } @Override public boolean hasChildren(Object element) { return false; } @Override public Object getParent(Object element) { return null; } @Override public Object[] getChildren(Object parentElement) { return null; } }; refsViewer.setContentProvider(provider); refsViewer.setLabelProvider(new LabelProvider() { @Override public String getText(Object element) { if (((Ref)element).getName().startsWith(Constants.R_HEADS)) return ((Ref)element).getName().substring(Constants.R_HEADS.length()); return ((Ref)element).getName(); } // FIX_WHEN_MIN_IS_20203 In older versions, get icon returns a Icon but in newer // it return an icon descriptor. Differentiate using reflection (ew) @Override public Image getImage(Object element) { final Object icon = RepositoryTreeNodeType.REF.getIcon(); Method method = null; try { method = icon.getClass().getMethod("createImage"); } catch (NoSuchMethodException e) { if (icon instanceof Image) { return (Image) icon; } else { return null; } } try { Object resolvedIcon = method.invoke(icon); if (resolvedIcon instanceof Image) { return (Image) resolvedIcon; } else { return null; } } catch (Exception e) { return null; } } }); refsViewer.addCheckStateListener(new ICheckStateListener() { @Override public void checkStateChanged(CheckStateChangedEvent event) { checkPage(); } }); final Composite bPanel = new Composite(panel, SWT.NONE); bPanel.setLayout(new RowLayout()); selectB = new Button(bPanel, SWT.PUSH); selectB.setText(UIText.SourceBranchPage_selectAll); selectB.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { refsViewer.setAllChecked(true); checkPage(); } }); unselectB = new Button(bPanel, SWT.PUSH); unselectB.setText(UIText.SourceBranchPage_selectNone); unselectB.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { refsViewer.setAllChecked(false); checkPage(); } }); bPanel.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); Dialog.applyDialogFont(panel); setControl(panel); checkPage(); } public void setSelection(RepositorySelection selection){ revalidate(selection); } public void setCredentials(UserPasswordCredentials credentials) { this.credentials = credentials; } /** * Set the ID for context sensitive help * * @param id * help context */ public void setHelpContext(String id) { helpContext = id; } @Override public void performHelp() { PlatformUI.getWorkbench().getHelpSystem().displayHelp(helpContext); } /** * Check internal state for page completion status. This method should be * called only when all necessary data from previous form is available. */ private void checkPage() { setMessage(null); int checkedElementCount = refsViewer.getCheckedElements().length; selectB.setEnabled(checkedElementCount != availableRefs.size()); unselectB.setEnabled(checkedElementCount != 0); if (transportError != null) { setErrorMessage(transportError); setPageComplete(false); return; } if (getSelectedBranches().isEmpty()) { setErrorMessage(UIText.SourceBranchPage_errorBranchRequired); setPageComplete(false); return; } setErrorMessage(null); setPageComplete(true); } private void checkForEmptyRepo() { if (isSourceRepoEmpty()) { setErrorMessage(null); setMessage(UIText.SourceBranchPage_repoEmpty, IMessageProvider.WARNING); setPageComplete(true); } } private void revalidate(final RepositorySelection newRepoSelection) { if (newRepoSelection.equals(validatedRepoSelection)) { // URI hasn't changed, no need to refill the page with new data checkPage(); return; } label.setText(NLS.bind(UIText.SourceBranchPage_branchList, newRepoSelection.getURI().toString())); label.getParent().layout(); validatedRepoSelection = null; transportError = null; head = null; availableRefs.clear(); refsViewer.setInput(null); setPageComplete(false); setErrorMessage(null); setMessage(null); label.getDisplay().asyncExec(new Runnable() { @Override public void run() { revalidateImpl(newRepoSelection); } }); } private void revalidateImpl(final RepositorySelection newRepoSelection) { if (label.isDisposed() || !isCurrentPage()) return; final ListRemoteOperation listRemoteOp; final URIish uri = newRepoSelection.getURI(); try { final Repository db = FileRepositoryBuilder .create(new File("/tmp")); //$NON-NLS-1$ int timeout = Activator.getDefault().getPreferenceStore().getInt( UIPreferences.REMOTE_CONNECTION_TIMEOUT); listRemoteOp = new ListRemoteOperation(db, uri, timeout); if (credentials != null) listRemoteOp .setCredentialsProvider(new EGitCredentialsProvider( credentials.getUser(), credentials .getPassword())); getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { listRemoteOp.run(monitor); } }); } catch (InvocationTargetException e) { Throwable why = e.getCause(); transportError(why); if (showDetailedFailureDialog()) SourceBranchFailureDialog.show(getShell(), uri); return; } catch (IOException e) { transportError(UIText.SourceBranchPage_cannotCreateTemp); return; } catch (InterruptedException e) { transportError(UIText.SourceBranchPage_remoteListingCancelled); return; } final Ref idHEAD = listRemoteOp.getRemoteRef(Constants.HEAD); head = null; boolean headIsMaster = false; final String masterBranchRef = Constants.R_HEADS + Constants.MASTER; for (final Ref r : listRemoteOp.getRemoteRefs()) { final String n = r.getName(); if (!n.startsWith(Constants.R_HEADS)) continue; availableRefs.add(r); if (idHEAD == null || headIsMaster) continue; if (r.getObjectId().equals(idHEAD.getObjectId())) { headIsMaster = masterBranchRef.equals(r.getName()); if (head == null || headIsMaster) head = r; } } Collections.sort(availableRefs, new Comparator<Ref>() { @Override public int compare(final Ref o1, final Ref o2) { return o1.getName().compareTo(o2.getName()); } }); if (idHEAD != null && head == null) { head = idHEAD; availableRefs.add(0, idHEAD); } validatedRepoSelection = newRepoSelection; refsViewer.setInput(availableRefs); refsViewer.setAllChecked(true); checkPage(); checkForEmptyRepo(); } private void transportError(final Throwable why) { Activator.logError(why.getMessage(), why); Throwable cause = why.getCause(); if (why instanceof TransportException && cause != null) transportError(NLS.bind(getMessage(why), why.getMessage(), cause.getMessage())); else transportError(why.getMessage()); } private String getMessage(final Throwable why) { if (why.getMessage().endsWith("Auth fail")) //$NON-NLS-1$ return UIText.SourceBranchPage_AuthFailMessage; else return UIText.SourceBranchPage_CompositeTransportErrorMessage; } private void transportError(final String msg) { transportError = msg; checkPage(); } private boolean showDetailedFailureDialog() { return Activator .getDefault() .getPreferenceStore() .getBoolean(UIPreferences.CLONE_WIZARD_SHOW_DETAILED_FAILURE_DIALOG); } }
7,738
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/jobs/ImportProjectJob.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.egit.jobs; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.egit.core.op.ConnectProviderOperation; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.Repository; import org.eclipse.m2e.core.MavenPlugin; import org.eclipse.m2e.core.internal.IMavenConstants; import org.eclipse.m2e.core.project.IProjectConfigurationManager; import org.eclipse.m2e.core.project.ResolverConfiguration; import org.eclipse.ui.PlatformUI; import com.amazonaws.eclipse.core.AwsToolkitCore; /** * A Job that imports a Git repository to the workbench. If it is Maven structured, import as a Maven project. */ @SuppressWarnings("restriction") public class ImportProjectJob { private final String projectName; private final File destinationFile; private final Repository repository; public ImportProjectJob(String projectName, File destinationFile) { this.projectName = projectName; this.destinationFile = destinationFile; this.repository = getTargetRepository(); } public IFile execute(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { importAsGeneralProject(monitor); IProject project = ResourcesPlugin.getWorkspace() .getRoot().getProject(projectName); if (pomFileExists(project)) { convertToMavenProject(project); return project.getFile(IMavenConstants.POM_FILE_NAME); } else { return null; } } private void importAsGeneralProject(IProgressMonitor monitor) throws InvocationTargetException { final String[] projectName = new String[1]; final boolean[] defaultLocation = new boolean[1]; final String[] path = new String[1]; final File[] repoDir = new File[1]; // get the data from the page in the UI thread PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { projectName[0] = ImportProjectJob.this.projectName; defaultLocation[0] = true; path[0] = repository.getWorkTree().getPath(); repoDir[0] = repository.getDirectory(); } }); try { IWorkspaceRunnable wsr = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor actMonitor) throws CoreException { final IProjectDescription desc = ResourcesPlugin .getWorkspace().newProjectDescription( projectName[0]); desc.setLocation(new Path(path[0])); IProject prj = ResourcesPlugin.getWorkspace().getRoot() .getProject(desc.getName()); prj.create(desc, actMonitor); prj.open(actMonitor); ConnectProviderOperation cpo = new ConnectProviderOperation(prj, repoDir[0]); cpo.execute(new NullProgressMonitor()); ResourcesPlugin.getWorkspace().getRoot() .refreshLocal(IResource.DEPTH_ONE, actMonitor); } }; ResourcesPlugin.getWorkspace().run(wsr, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } private Repository getTargetRepository() { try { return org.eclipse.egit.core.Activator .getDefault() .getRepositoryCache() .lookupRepository( new File(destinationFile, Constants.DOT_GIT)); } catch (IOException e) { AwsToolkitCore.getDefault().reportException( "Error looking up repository at " + destinationFile, e); return null; } } private boolean pomFileExists(IProject project) { return project.getFile(IMavenConstants.POM_FILE_NAME).exists(); } private void convertToMavenProject(final IProject project) throws InterruptedException { Job job = new Job("Enable Maven nature.") { @Override protected IStatus run(IProgressMonitor monitor) { try { ResolverConfiguration configuration = new ResolverConfiguration(); configuration.setResolveWorkspaceProjects(true); configuration.setSelectedProfiles(""); //$NON-NLS-1$ final boolean hasMavenNature = project .hasNature(IMavenConstants.NATURE_ID); IProjectConfigurationManager configurationManager = MavenPlugin .getProjectConfigurationManager(); configurationManager.enableMavenNature(project, configuration, monitor); if (!hasMavenNature) { configurationManager.updateProjectConfiguration( project, monitor); } } catch (CoreException ex) { AwsToolkitCore.getDefault().reportException(ex.getMessage(), ex); } return Status.OK_STATUS; } }; job.schedule(); job.join(); } }
7,739
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/egit/jobs/CloneGitRepositoryJob.java
/* * Copyright 2011-2017 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.egit.jobs; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.net.URISyntaxException; import java.util.Collection; import java.util.Collections; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.egit.core.RepositoryUtil; import org.eclipse.egit.core.op.CloneOperation; import org.eclipse.egit.core.op.ConfigureFetchAfterCloneTask; import org.eclipse.egit.core.op.ConfigurePushAfterCloneTask; import org.eclipse.egit.core.op.SetRepositoryConfigPropertyTask; import org.eclipse.egit.core.securestorage.UserPasswordCredentials; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIPreferences; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.wizard.Wizard; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.transport.URIish; import org.eclipse.osgi.util.NLS; import org.eclipse.ui.PlatformUI; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.egit.EGitCredentialsProvider; import com.amazonaws.eclipse.core.egit.GitRepositoryInfo; import com.amazonaws.eclipse.core.egit.SecureStoreUtils; import com.amazonaws.eclipse.core.egit.UIText; import com.amazonaws.eclipse.core.egit.GitRepositoryInfo.PushInfo; import com.amazonaws.eclipse.core.egit.GitRepositoryInfo.RepositoryConfigProperty; import com.amazonaws.eclipse.core.egit.ui.CloneDestinationPage; import com.amazonaws.eclipse.core.egit.ui.SourceBranchPage; import com.amazonaws.eclipse.core.exceptions.AwsActionException; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; /** * A UI sync job that manages cloning a remote Git repository to local. */ @SuppressWarnings("restriction") public class CloneGitRepositoryJob { private final Wizard wizard; private final SourceBranchPage sourceBranchPage; private final CloneDestinationPage cloneDestinationPage; private final GitRepositoryInfo gitRepositoryInfo; public CloneGitRepositoryJob(Wizard wizard, SourceBranchPage sourceBranchPage, CloneDestinationPage cloneDestinationPage, GitRepositoryInfo gitRepositoryInfo) { this.wizard = wizard; this.sourceBranchPage = sourceBranchPage; this.cloneDestinationPage = cloneDestinationPage; this.gitRepositoryInfo = gitRepositoryInfo; } public void execute(IProgressMonitor monitor) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { try { final CloneOperation cloneOperation = generateCloneOperation(); wizard.getContainer().run(true, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { executeCloneOperation(cloneOperation, monitor); } }); cloneDestinationPage.saveSettingsForClonedRepo(); } catch (Exception e) { AwsToolkitCore.getDefault() .reportException("Failed to clone git repository.", new AwsActionException(AwsToolkitMetricType.EXPLORER_CODECOMMIT_CLONE_REPO.getName(), e.getMessage(), e)); } } }); } /** * Do the clone using data which were collected on the pages * {@code validSource} and {@code cloneDestination} * * @param gitRepositoryInfo * @return if clone was successful * @throws URISyntaxException */ private CloneOperation generateCloneOperation() throws URISyntaxException { final boolean allSelected; final Collection<Ref> selectedBranches; if (sourceBranchPage.isSourceRepoEmpty()) { // fetch all branches of empty repo allSelected = true; selectedBranches = Collections.emptyList(); } else { allSelected = sourceBranchPage.isAllSelected(); selectedBranches = sourceBranchPage.getSelectedBranches(); } final File workdir = cloneDestinationPage.getDestinationFile(); boolean created = workdir.exists(); if (!created) created = workdir.mkdirs(); if (!created || !workdir.isDirectory()) { final String errorMessage = NLS.bind( UIText.GitCloneWizard_errorCannotCreate, workdir.getPath()); ErrorDialog.openError(wizard.getShell(), wizard.getWindowTitle(), UIText.GitCloneWizard_failed, new Status(IStatus.ERROR, Activator.getPluginId(), 0, errorMessage, null)); // let's give user a chance to fix this minor problem return null; } return createCloneOperation(allSelected, selectedBranches, workdir, cloneDestinationPage.getInitialBranch(), cloneDestinationPage.getRemote(), cloneDestinationPage.isCloneSubmodules()); } private CloneOperation createCloneOperation( final boolean allSelected, final Collection<Ref> selectedBranches, final File workdir, final Ref ref, final String remoteName, final boolean isCloneSubmodules) throws URISyntaxException { URIish uri = new URIish(gitRepositoryInfo.getCloneUri()); UserPasswordCredentials credentials = gitRepositoryInfo.getCredentials(); int timeout = Activator.getDefault().getPreferenceStore() .getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT); wizard.setWindowTitle(NLS.bind(UIText.GitCloneWizard_jobName, uri.toString())); final CloneOperation op = new CloneOperation(uri, allSelected, selectedBranches, workdir, ref != null ? ref.getName() : null, remoteName, timeout); if (credentials != null) op.setCredentialsProvider(new EGitCredentialsProvider(credentials .getUser(), credentials.getPassword())); else op.setCredentialsProvider(new EGitCredentialsProvider()); op.setCloneSubmodules(isCloneSubmodules); configureFetchSpec(op, remoteName); configurePush(op, remoteName); configureRepositoryConfig(op); return op; } private void configureFetchSpec(CloneOperation op, String remoteName) { for (String fetchRefSpec : gitRepositoryInfo.getFetchRefSpecs()) op.addPostCloneTask(new ConfigureFetchAfterCloneTask(remoteName, fetchRefSpec)); } private void configurePush(CloneOperation op, String remoteName) { for (PushInfo pushInfo : gitRepositoryInfo.getPushInfos()) try { URIish uri = pushInfo.getPushUri() != null ? new URIish( pushInfo.getPushUri()) : null; ConfigurePushAfterCloneTask task = new ConfigurePushAfterCloneTask( remoteName, pushInfo.getPushRefSpec(), uri); op.addPostCloneTask(task); } catch (URISyntaxException e) { Activator.handleError(UIText.GitCloneWizard_failed, e, true); } } private void configureRepositoryConfig(CloneOperation op) { for (RepositoryConfigProperty p : gitRepositoryInfo .getRepositoryConfigProperties()) { SetRepositoryConfigPropertyTask task = new SetRepositoryConfigPropertyTask( p.getSection(), p.getSubsection(), p.getName(), p.getValue()); op.addPostCloneTask(task); } } private IStatus executeCloneOperation(final CloneOperation op, final IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { final RepositoryUtil util = Activator.getDefault().getRepositoryUtil(); op.run(monitor); util.addConfiguredRepository(op.getGitDir()); try { if (gitRepositoryInfo.shouldSaveCredentialsInSecureStore()) SecureStoreUtils.storeCredentials(gitRepositoryInfo.getCredentials(), new URIish(gitRepositoryInfo.getCloneUri())); } catch (Exception e) { AwsToolkitCore.getDefault().logWarning(e.getMessage(), e); } return Status.OK_STATUS; } }
7,740
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/ToolkitAnalyticsUtils.java
/* * Copyright 2016 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.core.telemetry; public final class ToolkitAnalyticsUtils { public static void publishBooleansEvent(AwsToolkitMetricType metricType, String name, Boolean value) { MetricsDataModel dataModel = new MetricsDataModel(metricType); dataModel.addBooleanMetric(name, value); dataModel.publishEvent(); } public static void trackSpeedMetrics( final ToolkitAnalyticsManager analytics, final String eventType, final String metricNameTime, final long time, final String metricNameSize, final long size, final String metricNameSpeed) { analytics.publishEvent(analytics.eventBuilder() .setEventType(eventType) .addMetric(metricNameTime, time) .addMetric(metricNameSize, size) .addMetric(metricNameSpeed, (double)size / (double)time) .build()); } }
7,741
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/ClientContextConfig.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry; import static com.amazonaws.eclipse.core.telemetry.internal.Constants.JAVA_PREFERENCE_NODE_FOR_AWS_TOOLKIT_FOR_ECLIPSE; import static com.amazonaws.eclipse.core.telemetry.internal.Constants.MOBILE_ANALYTICS_CLIENT_ID_PREF_STORE_KEY; import java.util.Locale; import java.util.UUID; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.preferences.ConfigurationScope; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.jface.preference.IPreferenceStore; import org.osgi.framework.Bundle; import com.amazonaws.annotation.Immutable; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.internal.Constants; import com.amazonaws.util.StringUtils; /** * Container for all the data required in the x-amz-client-context header. * * @see http://docs.aws.amazon.com/mobileanalytics/latest/ug/PutEvents.html#putEvents-request-client-context-header */ @Immutable public class ClientContextConfig { private final String envPlatformName; private final String envPlatformVersion; private final String eclipseVersion; private final String envLocale; private final String clientId; private final String version; public static final ClientContextConfig PROD_CONFIG = new ClientContextConfig( _getSystemOsName(), _getSystemOsVersion(), _getSystemLocaleCountry(), getOrGenerateClientId()); public static final ClientContextConfig TEST_CONFIG = new ClientContextConfig( _getSystemOsName(), _getSystemOsVersion(), _getSystemLocaleCountry(), getOrGenerateClientId()); private ClientContextConfig(String envPlatformName, String envPlatformVersion, String envLocale, String clientId) { this.eclipseVersion = eclipseVersion(); this.version = getPluginVersion(); this.envPlatformName = envPlatformName; this.envPlatformVersion = envPlatformVersion; this.envLocale = envLocale; this.clientId = clientId; } private String eclipseVersion() { try { Bundle bundle = Platform.getBundle("org.eclipse.platform"); return bundle.getVersion().toString(); } catch (Exception e) { return "Unknown"; } } private String getPluginVersion() { try { Bundle bundle = Platform.getBundle("com.amazonaws.eclipse.core"); return bundle.getVersion().toString(); } catch (Exception e) { return "Unknown"; } } public String getEnvPlatformName() { return envPlatformName; } public String getEnvPlatformVersion() { return envPlatformVersion; } public String getEnvLocale() { return envLocale; } public String getClientId() { return clientId; } public String getVersion() { return version; } public String getEclipseVersion() { return eclipseVersion; } private static String _getSystemOsName() { try { String osName = System.getProperty("os.name"); if (osName == null) { return null; } osName = osName.toLowerCase(); if (osName.startsWith("windows")) { return Constants.CLIENT_CONTEXT_ENV_PLATFORM_WINDOWS; } if (osName.startsWith("mac")) { return Constants.CLIENT_CONTEXT_ENV_PLATFORM_MACOS; } if (osName.startsWith("linux")) { return Constants.CLIENT_CONTEXT_ENV_PLATFORM_LINUX; } AwsToolkitCore.getDefault().logInfo("Unknown OS name: " + osName); return null; } catch (Exception e) { return null; } } private static String _getSystemOsVersion() { try { return System.getProperty("os.version"); } catch (Exception e) { return null; } } private static String _getSystemLocaleCountry() { try { return Locale.getDefault().getDisplayCountry(Locale.US); } catch (Exception e) { return null; } } public static String getOrGenerateClientId() { // This is the Java preferences scope Preferences awsToolkitNode = Preferences.userRoot().node(JAVA_PREFERENCE_NODE_FOR_AWS_TOOLKIT_FOR_ECLIPSE); String clientId = awsToolkitNode.get(MOBILE_ANALYTICS_CLIENT_ID_PREF_STORE_KEY, null); if (!StringUtils.isNullOrEmpty(clientId)) { return clientId; } // This is an installation scope PreferenceStore. IEclipsePreferences eclipsePreferences = ConfigurationScope.INSTANCE.getNode( AwsToolkitCore.getDefault().getBundle().getSymbolicName()); clientId = eclipsePreferences.get(MOBILE_ANALYTICS_CLIENT_ID_PREF_STORE_KEY, null); if (StringUtils.isNullOrEmpty(clientId)) { // This is an instance scope PreferenceStore. IPreferenceStore store = AwsToolkitCore.getDefault().getPreferenceStore(); clientId = store.getString(MOBILE_ANALYTICS_CLIENT_ID_PREF_STORE_KEY); } if (StringUtils.isNullOrEmpty(clientId)) { // Generate a GUID as the client id and persist it in the preference store clientId = UUID.randomUUID().toString(); } awsToolkitNode.put(MOBILE_ANALYTICS_CLIENT_ID_PREF_STORE_KEY, clientId); try { awsToolkitNode.flush(); } catch (BackingStoreException e) { // Silently fails if exception occurs when flushing the client id. } return clientId; } }
7,742
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/AwsToolkitMetricType.java
/* * Copyright 2017 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry; /** * These are predefined metric types. */ public enum AwsToolkitMetricType { /* AWS Overview Events */ OVERVIEW("aws_loadOverview"), /* AWS Explorer Events */ EXPLORER_LOADING("aws_loadExplorer"), /* Explorer Dynamodb Actions */ EXPLORER_DYNAMODB_OPEN_TABLE_EDITOR("dynamo_openEditor"), EXPLORER_DYNAMODB_RUN_SCAN("dynamo_runScan"), EXPLORER_DYNAMODB_SAVE("dynamo_save"), EXPLORER_DYNAMODB_EXPORT_AS_CSV("dynamo_exportCsv"), EXPLORER_DYNAMODB_ADD_NEW_ATTRIBUTE("dynamo_addAttribute"), /* Explorer CodeDeploy Actions */ EXPLORER_CODEDEPLOY_REFRESH_DEPLOYMENT_GROUP_EDITOR("codedeploy_refreshGroup"), EXPLORER_CODEDEPLOY_OPEN_DEPLOYMENT_GROUP("codedeploy_openGroup"), /* Explorer CodeCommit Actions */ EXPLORER_CODECOMMIT_REFRESH_REPO_EDITOR("codecommit_refreshEditor"), EXPLORER_CODECOMMIT_CREATE_REPO("codecommit_create"), EXPLORER_CODECOMMIT_CLONE_REPO("codecommit_clone"), EXPLORER_CODECOMMIT_DELETE_REPO("codecommit_delete"), EXPLORER_CODECOMMIT_OPEN_REPO_EDITOR("codecommit_openEditor"), /* Explorer Beanstalk Actions */ EXPLORER_BEANSTALK_OPEN_ENVIRONMENT_EDITOR("beanstalk_openEditor"), EXPLORER_BEANSTALK_DELETE_APPLICATION("beanstalk_deleteApplication"), EXPLORER_BEANSTALK_TERMINATE_ENVIRONMENT("beanstalk_terminateEnvironment"), EXPLORER_BEANSTALK_REFRESH_ENVIRONMENT_EDITOR("beanstalk_refreshEditor"), EXPLORER_BEANSTALK_IMPORT_TEMPLATE("beanstalk_importTemplate"), EXPLORER_BEANSTALK_EXPORT_TEMPLATE("beanstalk_exportTemplate"), /* Explorer S3 Actions */ EXPLORER_S3_CREATE_BUCKET("s3_createBucket"), EXPLORER_S3_OPEN_BUCKET_EDITOR("s3_openEditor"), EXPLORER_S3_REFRESH_BUCKET_EDITOR("s3_refreshEditor"), EXPLORER_S3_DELETE_BUCKET("s3_deleteBucket"), EXPLORER_S3_DELETE_OBJECTS("s3_deleteObjects"), EXPLORER_S3_GENERATE_PRESIGNED_URL("s3_genereatePresignedUrl"), EXPLORER_S3_EDIT_OBJECT_TAGS("s3_editObjectTags"), EXPLORER_S3_EDIT_OBJECT_PERMISSIONS("s3_editObjectPermissions"), /* Explorer EC2 Actions */ EXPLORER_EC2_OPEN_VIEW("ec2_openEditor"), EXPLORER_EC2_OPEN_AMIS_VIEW("ec2_openAmis"), EXPLORER_EC2_OPEN_INSTANCES_VIEW("ec2_openInstances"), EXPLORER_EC2_OPEN_EBS_VIEW("ec2_openEbs"), EXPLORER_EC2_OPEN_SECURITY_GROUPS_VIEW("ec2_openSecurityGroups"), EXPLORER_EC2_NEW_SECURITY_GROUP("ec2_createSecurityGroup"), EXPLORER_EC2_DELETE_SECURITY_GROUP("ec2_deleteSecurityGroup"), EXPLORER_EC2_ADD_PERMISSIONS_TO_SECURITY_GROUP("ec2_addPermissionToSecurityGroup"), EXPLORER_EC2_REMOVE_PERMISSIONS_FROM_SECURITY_GROUP("ec2_removePermissionFromSecurityGroup"), EXPLORER_EC2_REFRESH_SECURITY_GROUP("ec2_refreshSecurityGroup"), EXPLORER_EC2_OPEN_SHELL_ACTION("ec2_openShell"), EXPLORER_EC2_REBOOT_ACTION("ec2_reboot"), EXPLORER_EC2_TERMINATE_ACTION("ec2_terminate"), EXPLORER_EC2_CREATE_AMI_ACTION("ec2_createAmi"), EXPLORER_EC2_COPY_PUBLIC_DNS_NAME_ACTION("ec2_copyDnsName"), EXPLORER_EC2_ATTACH_NEW_VOLUME_ACTION("ec2_attachVolume"), EXPLORER_EC2_START_INSTANCES_ACTION("ec2_startInstance"), EXPLORER_EC2_STOP_INSTANCES_ACTION("ec2_stopInstance"), /* Aws level Events */ AWS_NEW_JAVA_PROJECT_WIZARD("project_new"), /* Dynamodb Events */ DYNAMODB_INSTALL_TEST_TOOL("dynamo_installTestTool"), DYNAMODB_UNINSTALL_TEST_TOOL("dynamo_uninstallTestTool"), /* Ec2 Events */ EC2_LAUNCH_INSTANCES("Ec2-LaunchInstances"), /* Lambda Events */ LAMBDA_NEW_LAMBDA_FUNCTION_WIZARD("project_new"), LAMBDA_NEW_LAMBDA_PROJECT_WIZARD("project_new"), LAMBDA_NEW_SERVERLESS_PROJECT_WIZARD("sam_init"), LAMBDA_UPLOAD_FUNCTION_WIZARD("lambda_deploy"), LAMBDA_INVOKE_FUNCTION_DIALOG("lambda_invokeRemote"), LAMBDA_DEPLOY_SERVERLESS_PROJECT_WIZARD("sam_deploy"), /* SAM Local Events */ SAMLOCAL_GENERATE_EVENT("sam_generateEvent"), SAMLOCAL_LAUNCH("lambda_invokeLocal"), ; private final String metricName; private AwsToolkitMetricType(String metricName) { this.metricName = metricName; } public String getName() { return metricName; } }
7,743
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/TelemetryClientV2.java
/* * Copyright 2020 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry; import java.util.Collection; import com.amazonaws.auth.AWSCredentialsProvider; import software.amazon.awssdk.services.toolkittelemetry.TelemetryClient; import software.amazon.awssdk.services.toolkittelemetry.model.MetricDatum; import software.amazon.awssdk.services.toolkittelemetry.model.PostMetricsRequest; public class TelemetryClientV2 { private TelemetryClient client; private ClientContextConfig config; public TelemetryClientV2(AWSCredentialsProvider credentialsProvider, ClientContextConfig clientContextConfig) { try { this.client = getTelemetryClient(credentialsProvider); this.config = clientContextConfig; } catch (Throwable e) { this.client = null; } } public void publish(Collection<MetricDatum> event) { if (client == null || event == null) { return; } final PostMetricsRequest request = new PostMetricsRequest().aWSProduct("AWS Toolkit For Eclipse").parentProduct("Eclipse") .parentProductVersion(config.getEclipseVersion()).clientID(config.getClientId()).metricData(event).oSVersion(config.getEnvPlatformVersion()) .oS(config.getEnvPlatformName()).aWSProductVersion(config.getVersion()); client.postMetrics(request); } private TelemetryClient getTelemetryClient(AWSCredentialsProvider credentialsProvider) throws Exception { return TelemetryClient.builder().endpoint("https://client-telemetry.us-east-1.amazonaws.com").iamCredentials(credentialsProvider).build(); } }
7,744
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/ToolkitEvent.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import java.time.Instant; import com.amazonaws.annotation.Immutable; import com.amazonaws.eclipse.core.telemetry.internal.Constants; import com.amazonaws.eclipse.core.telemetry.internal.ToolkitSession; import software.amazon.awssdk.services.toolkittelemetry.model.MetadataEntry; import software.amazon.awssdk.services.toolkittelemetry.model.MetricDatum; import software.amazon.awssdk.services.toolkittelemetry.model.Unit; @Immutable public class ToolkitEvent { private ToolkitSession session; private String eventType; private Date timestamp; private final Map<String, String> attributes = new HashMap<>(); private final Map<String, Double> metrics = new HashMap<>(); public MetricDatum toMetricDatum() { // we don't differentiate attributes/metrics anymore so add both Collection<MetadataEntry> metadata = this.metrics.entrySet().stream().map((it) -> new MetadataEntry().key(it.getKey()).value(it.getValue().toString())) .filter(it -> it.getValue() != null && !it.getValue().isEmpty()).collect(Collectors.toList()); metadata.addAll(this.attributes.entrySet().stream().map(it -> new MetadataEntry().key(it.getKey()).value(it.getValue())) .filter(it -> it.getValue() != null && !it.getValue().isEmpty()).collect(Collectors.toList())); final MetricDatum datum = new MetricDatum().metricName(this.eventType).value(1.0).unit(Unit.None).epochTimestamp(Instant.now().toEpochMilli()) .metadata(metadata); return datum; } /** * http://docs.aws.amazon.com/mobileanalytics/latest/ug/limits.html */ public boolean isValid() { if (session == null) { return false; } if (session.getId() == null) { return false; } if (session.getStartTimestamp() == null) { return false; } if (eventType == null || eventType.isEmpty()) { return false; } if (timestamp == null) { return false; } if (attributes.size() + metrics.size() > Constants.MAX_ATTRIBUTES_AND_METRICS_PER_EVENT) { return false; } for (Entry<String, String> attribute : attributes.entrySet()) { if (attribute.getKey().length() > Constants.MAX_ATTRIBUTE_OR_METRIC_NAME_LENGTH) { return false; } if (attribute.getValue() == null) { return false; } if (attribute.getValue().length() > Constants.MAX_ATTRIBUTE_VALUE_LENGTH) { return false; } if (attribute.getValue().isEmpty()) { return false; } } for (Entry<String, Double> metric : metrics.entrySet()) { if (metric.getKey().length() > Constants.MAX_ATTRIBUTE_OR_METRIC_NAME_LENGTH) { return false; } if (metric.getValue() == null) { return false; } } return true; } /** * The constructor is intentionally marked as private; caller should use * ToolkitEventBuilder to create event instance */ private ToolkitEvent() { } public static class ToolkitEventBuilder { private final ToolkitEvent event = new ToolkitEvent(); public ToolkitEventBuilder(ToolkitSession session) { this.event.session = session; } public ToolkitEventBuilder setEventType(String eventType) { this.event.eventType = eventType; return this; } /** * If not specified, the timestamp is by default set to the current time. */ public ToolkitEventBuilder setTimestamp(Date timestamp) { this.event.timestamp = timestamp; return this; } public ToolkitEventBuilder addAttribute(String name, String value) { this.event.attributes.put(name, value); return this; } public ToolkitEventBuilder addMetric(String name, double value) { this.event.metrics.put(name, value); return this; } public ToolkitEventBuilder addBooleanMetric(String name, boolean value) { this.event.attributes.put(name, value ? "true" : "false"); return this; } public ToolkitEvent build() { if (this.event.timestamp == null) { this.event.timestamp = new Date(); } return this.event; } } }
7,745
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/ToolkitAnalyticsManager.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry; import com.amazonaws.eclipse.core.accounts.AwsPluginAccountManager; import com.amazonaws.eclipse.core.telemetry.ToolkitEvent.ToolkitEventBuilder; /** * The entry point for managing Toolkit analytics sessions and events. */ public interface ToolkitAnalyticsManager { /** * Start a new session by sending out a session.start event. After this point, * all the events published by this manager will be bound to this new session. * * @param accountManager The account manager needed to start the credentials * changed listener * @param forceFlushEvents true if the session.start event should be sent * immediately after the method call. */ public void startSession(AwsPluginAccountManager accountManager, boolean forceFlushEvents); /** * Terminate the current session (if any) by sending out a session.stop event. * After this point, any call of {@link #publishEvent(ToolkitEvent)} won't have * any effect, until the next {@link #startSession(boolean)} call is made. * * @param forceFlushEvents true if all the cached events should be forcefully * sent out to the Analytics service after this method * call. */ public void endSession(boolean forceFlushEvents); /** * @return a builder for {@link ToolkitEvent}s. The generated event will by * default be bound to the current session of the manager. */ public ToolkitEventBuilder eventBuilder(); /** * Publish a new {@link ToolkitEvent}. This method call won't take any affect if * the manager is not currently tracking an on-going session. * * @param event the toolkit event to be published. */ public void publishEvent(ToolkitEvent event); /** * Enable or disable the analytics collection. When disabled, none of the * methods of the manager takes any effect. */ public void setEnabled(boolean enabled); }
7,746
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/MetricsDataModel.java
/* * Copyright 2017 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.ToolkitEvent.ToolkitEventBuilder; public class MetricsDataModel { private static final Map<String, String> METRICS_METADATA = new HashMap<>(); private final ToolkitAnalyticsManager analytics = AwsToolkitCore.getDefault().getAnalyticsManager(); private final AwsToolkitMetricType metricType; private ToolkitEventBuilder eventBuilder; public MetricsDataModel(AwsToolkitMetricType metricType) { this.metricType = metricType; this.eventBuilder = analytics.eventBuilder(); this.eventBuilder.setEventType(metricType.getName()); } public AwsToolkitMetricType getMetricType() { return metricType; } public final MetricsDataModel addAttribute(String name, String value) { eventBuilder.addAttribute(name, value); return this; } public final MetricsDataModel addBooleanMetric(String name, Boolean value) { eventBuilder.addBooleanMetric(name, value); return this; } public final MetricsDataModel addMetric(String name, Double value) { eventBuilder.addMetric(name, value); return this; } public final void publishEvent() { for (Entry<String, String> entry : METRICS_METADATA.entrySet()) { addAttribute(entry.getKey(), entry.getValue()); } analytics.publishEvent(eventBuilder.build()); eventBuilder = analytics.eventBuilder().setEventType(metricType.getName()); } }
7,747
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/ui/ToolkitAnalyticsPreferencePage.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.preferences.PreferenceConstants; import com.amazonaws.eclipse.core.ui.WebLinkListener; import com.amazonaws.eclipse.core.ui.preferences.AwsToolkitPreferencePage; import com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory; public class ToolkitAnalyticsPreferencePage extends AwsToolkitPreferencePage implements IWorkbenchPreferencePage { private Button analyticsEnabledButton; public ToolkitAnalyticsPreferencePage() { super("Collection of Analytics"); setPreferenceStore(AwsToolkitCore.getDefault().getPreferenceStore()); setDescription("Collection of Analytics"); } @Override public void init(IWorkbench workbench) { } @Override protected Control createContents(Composite parent) { Composite composite = new Composite(parent, SWT.LEFT); GridLayout layout = new GridLayout(); layout.marginWidth = 10; layout.marginHeight = 8; composite.setLayout(layout); GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.widthHint = 300; composite.setLayoutData(gridData); WizardWidgetFactory.newLink(composite, new WebLinkListener(), String.format( "By leaving this box checked, you agree that AWS may " + "collect analytics about your usage of AWS Toolkit. AWS will handle " + "all information received in accordance with the <a href=\"%s\">AWS Privacy Policy</a>.\n" + "When available, an AWS Account ID is associated with this information.", "http://aws.amazon.com/privacy/"), 1); analyticsEnabledButton = new Button(composite, SWT.CHECK | SWT.MULTI | SWT.WRAP); analyticsEnabledButton.setText("Enable collection of analytics"); analyticsEnabledButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); analyticsEnabledButton.setSelection(getPreferenceStore().getBoolean( PreferenceConstants.P_TOOLKIT_ANALYTICS_COLLECTION_ENABLED)); return composite; } @Override protected void performDefaults() { analyticsEnabledButton.setSelection( getPreferenceStore().getDefaultBoolean( PreferenceConstants.P_TOOLKIT_ANALYTICS_COLLECTION_ENABLED)); } @Override public boolean performOk() { boolean enabled = analyticsEnabledButton.getSelection(); getPreferenceStore().setValue( PreferenceConstants.P_TOOLKIT_ANALYTICS_COLLECTION_ENABLED, enabled); AwsToolkitCore.getDefault().getAnalyticsManager().setEnabled(enabled); return super.performOk(); } }
7,748
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/cognito/AWSCognitoCredentialsProvider.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry.cognito; import java.util.Date; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSSessionCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.AnonymousAWSCredentials; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.eclipse.core.telemetry.cognito.identity.AWSCognitoIdentityIdProvider; import com.amazonaws.eclipse.core.telemetry.cognito.identity.ToolkitCachedCognitoIdentityIdProvider; import com.amazonaws.eclipse.core.telemetry.internal.Constants; import com.amazonaws.regions.Regions; import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentity; import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient; import com.amazonaws.services.cognitoidentity.model.GetCredentialsForIdentityRequest; /** * AWSCredentialsProvider implementation that uses the Amazon Cognito Identity * service to create temporary, short-lived sessions to use for authentication */ public class AWSCognitoCredentialsProvider implements AWSCredentialsProvider { public static final AWSCognitoCredentialsProvider TEST_PROVIDER = new AWSCognitoCredentialsProvider( ToolkitCachedCognitoIdentityIdProvider.TEST_PROVIDER); public static final AWSCognitoCredentialsProvider V2_PROVIDER = new AWSCognitoCredentialsProvider( ToolkitCachedCognitoIdentityIdProvider.V2_PROVIDER); private final AWSCognitoIdentityIdProvider identityIdProvider; /** The Cognito Identity Service client for requesting session credentials */ private final AmazonCognitoIdentity cognitoIdentityClient; /** The current session credentials */ private volatile AWSSessionCredentials sessionCredentials; /** The expiration time for the current session credentials */ private volatile Date sessionCredentialsExpiration; public AWSCognitoCredentialsProvider( AWSCognitoIdentityIdProvider identityIdProvider, Regions region) { this.identityIdProvider = identityIdProvider; this.cognitoIdentityClient = AmazonCognitoIdentityClient.builder() .withRegion(region) .withCredentials(new AWSStaticCredentialsProvider(new AnonymousAWSCredentials())) .build(); } public AWSCognitoCredentialsProvider( AWSCognitoIdentityIdProvider identityIdProvider) { this(identityIdProvider, Constants.COGNITO_IDENTITY_SERVICE_REGION); } /** * If the current session has expired/credentials are invalid, a new session * is started, establishing the credentials. In either case, those * credentials are returned */ @Override public AWSSessionCredentials getCredentials() { if (needsNewSession()) { startSession(); } return sessionCredentials; } @Override public void refresh() { startSession(); } /** threshold for refreshing session credentials */ private static final int CREDS_REFRESH_THRESHOLD_SECONDS = 500; private boolean needsNewSession() { if (sessionCredentials == null) { return true; } long timeRemaining = sessionCredentialsExpiration.getTime() - System.currentTimeMillis(); return timeRemaining < (CREDS_REFRESH_THRESHOLD_SECONDS * 1000); } private void startSession() { String identityId = identityIdProvider.getIdentityId(); com.amazonaws.services.cognitoidentity.model.Credentials credentials = cognitoIdentityClient .getCredentialsForIdentity( new GetCredentialsForIdentityRequest() .withIdentityId(identityId)).getCredentials(); sessionCredentials = new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretKey(), credentials.getSessionToken()); sessionCredentialsExpiration = credentials.getExpiration(); } }
7,749
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/cognito
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/cognito/identity/AWSCognitoIdentityIdProvider.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry.cognito.identity; /** * Responsible for establishing a Cognito identity and providing the identity id * for the current user. * * @see http://docs.aws.amazon.com/cognito/devguide/identity/concepts/authentication-flow/ */ public interface AWSCognitoIdentityIdProvider { /** * @return the identity id for the current user. */ String getIdentityId(); }
7,750
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/cognito
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/cognito/identity/ToolkitCachedCognitoIdentityIdProvider.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry.cognito.identity; import org.eclipse.jface.preference.IPreferenceStore; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.AnonymousAWSCredentials; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.internal.Constants; import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentity; import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient; import com.amazonaws.services.cognitoidentity.model.GetIdRequest; /** * Provide Cognito identity id by making unauthenticated API calls to the * Cognito Identity Service. The returned identity id will be cached in the * toolkit preference store for subsequent {@link #getIdentityId()} calls. */ public class ToolkitCachedCognitoIdentityIdProvider implements AWSCognitoIdentityIdProvider { public static final ToolkitCachedCognitoIdentityIdProvider TEST_PROVIDER = new ToolkitCachedCognitoIdentityIdProvider( Constants.COGNITO_IDENTITY_POOL_ID_TEST, AwsToolkitCore .getDefault().getPreferenceStore()); public static final ToolkitCachedCognitoIdentityIdProvider V2_PROVIDER = new ToolkitCachedCognitoIdentityIdProvider( Constants.COGNITO_IDENTITY_POOL_ID_PROD_V2, AwsToolkitCore .getDefault().getPreferenceStore()); private final String identityPoolId; private final IPreferenceStore prefStore; private final AmazonCognitoIdentity cognitoIdentityClient; /** The current identity id */ private volatile String identityId; /** * @param identityPoolId * id of the identity pool where the identity id will be * requested from. The cached identity id will be invalidated if * this pool id does not match the value persisted in the * preference store. * @param prefStore * the preference store for caching the requested identity id, * and the pool id where the cached identity was originally * requested from. */ public ToolkitCachedCognitoIdentityIdProvider(String identityPoolId, IPreferenceStore prefStore) { this.identityPoolId = identityPoolId; this.prefStore = prefStore; this.cognitoIdentityClient = AmazonCognitoIdentityClient.builder() .withRegion(Constants.COGNITO_IDENTITY_SERVICE_REGION) .withCredentials(new AWSStaticCredentialsProvider(new AnonymousAWSCredentials())) .build(); } @Override public String getIdentityId() { if (identityId == null) { if (isPersistedIdentityIdValid()) { identityId = loadIdentityIdFromPrefStore(); AwsToolkitCore.getDefault().logInfo( "Found valid identity id cache " + identityId); } else { identityId = requestAndCacheNewIdentityId(); AwsToolkitCore.getDefault().logInfo( "Initialized a new Cognito identity " + identityId); } } return identityId; } private boolean isPersistedIdentityIdValid() { String cachedId = prefStore .getString(Constants.COGNITO_IDENTITY_ID_PREF_STORE_KEY); String cachedPoolId = prefStore .getString(Constants.COGNITO_IDENTITY_POOL_ID_PREF_STORE_KEY); return !isEmpty(cachedId) && identityPoolId.equals(cachedPoolId); } private String requestAndCacheNewIdentityId() { String newId = requestIdentityId(); prefStore.setValue(Constants.COGNITO_IDENTITY_ID_PREF_STORE_KEY, newId); prefStore.setValue(Constants.COGNITO_IDENTITY_POOL_ID_PREF_STORE_KEY, identityPoolId); return newId; } private String loadIdentityIdFromPrefStore() { return prefStore .getString(Constants.COGNITO_IDENTITY_ID_PREF_STORE_KEY); } private String requestIdentityId() { String identityId = cognitoIdentityClient.getId( new GetIdRequest().withIdentityPoolId(identityPoolId)) .getIdentityId(); return identityId; } private boolean isEmpty(String value) { return value == null || value.isEmpty(); } }
7,751
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/batchclient/TelemetryBatchClient.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry.batchclient; import software.amazon.awssdk.services.toolkittelemetry.model.MetricDatum; public interface TelemetryBatchClient { /** * To improve performance, the client may cache the incoming event and wait * till it has collected a big enough batch of events and then send out the * batch with one single API call. The implementation of this API should * never block. */ void putEvent(MetricDatum event); /** * Flush the local cache by sending out all the cached events to the * service. This is usually called at the end of an application life-cycle, * to make sure all the events are sent before the end of the session. */ void flush(); }
7,752
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/batchclient
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/batchclient/internal/TelemetryBatchClientImpl.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry.batchclient.internal; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.ICoreRunnable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.Job; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.ClientContextConfig; import com.amazonaws.eclipse.core.telemetry.TelemetryClientV2; import com.amazonaws.eclipse.core.telemetry.batchclient.TelemetryBatchClient; import software.amazon.awssdk.services.toolkittelemetry.model.MetricDatum; /** * An implementation of MobileAnalyticsBatchClient which uses a bounded queue * for caching incoming events and a single-threaded service client for sending * out event batches. It also guarantees that the events are sent in the same * order as they are accepted by the client. */ public class TelemetryBatchClientImpl implements TelemetryBatchClient { private static final int MIN_EVENT_BATCH_SIZE = 20; private static final int MAX_QUEUE_SIZE = 500; private final TelemetryClientV2 telemetryClient; /** * For caching incoming events for batching */ private final EventQueue eventQueue = new EventQueue(); /** * To keep track of the on-going putEvents request and make sure only one * request can be made at a time. */ private final AtomicBoolean isSendingPutEventsRequest = new AtomicBoolean(false); public TelemetryBatchClientImpl(AWSCredentialsProvider credentialsProvider, ClientContextConfig clientContextConfig) { this.telemetryClient = new TelemetryClientV2(credentialsProvider, clientContextConfig); } @Override public void putEvent(MetricDatum event) { // we don't lock the queue when accepting incoming event, and the // queue size is only a rough estimate. int queueSize = eventQueue.size(); // keep the queue bounded if (queueSize >= MAX_QUEUE_SIZE) { tryDispatchAllEventsAsync(); return; } eventQueue.addToTail(event); if (queueSize >= MIN_EVENT_BATCH_SIZE) { tryDispatchAllEventsAsync(); } } @Override public void flush() { tryDispatchAllEventsAsync(); } /** * To make sure the order of the analytic events is preserved, this method call * will immediately return if there is an ongoing PutEvents call. */ private void tryDispatchAllEventsAsync() { boolean contentionDetected = this.isSendingPutEventsRequest.getAndSet(true); AwsToolkitCore.getDefault().logInfo("Trying to dispatch events, contention detected: " + contentionDetected); if (!contentionDetected) { dispatchAllEventsAsync(); } } /** * Only one thread can call this method at a time */ private void dispatchAllEventsAsync() { final List<MetricDatum> eventsBatch = this.eventQueue.pollAllQueuedEvents(); final int POLL_LIMIT = 20; Job j = Job.create("Posting telemetry", new ICoreRunnable() { @Override public void run(IProgressMonitor monitor) throws CoreException { try { postTelemetry(); } finally { isSendingPutEventsRequest.set(false); } } private void postTelemetry() { int base = 0; while (base < eventsBatch.size()) { final List<MetricDatum> events = eventsBatch.subList(base, Math.min(base + POLL_LIMIT, eventsBatch.size())); if (events.isEmpty()) { break; } try { telemetryClient.publish(events); AwsToolkitCore.getDefault().logInfo("Posting telemetry succeeded"); } catch (Exception e) { eventQueue.addToHead(events); AwsToolkitCore.getDefault().logError("Unable to post telemetry", e); } base += POLL_LIMIT; } } }); j.setSystem(true); j.schedule(); } }
7,753
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/batchclient
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/batchclient/internal/EventQueue.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry.batchclient.internal; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import software.amazon.awssdk.services.toolkittelemetry.model.MetricDatum; /** * A very simplistic implementation of a double-ended queue with non-blocking * write access. */ class EventQueue { private final ConcurrentLinkedQueue<MetricDatum> headQueue = new ConcurrentLinkedQueue<>(); private final ConcurrentLinkedQueue<MetricDatum> tailQueue = new ConcurrentLinkedQueue<>(); /** * Not thread safe. * * @throws IllegalStateException * if this queue still contains event added via any previous * addToHead calls */ public void addToHead(List<MetricDatum> events) { if (!headQueue.isEmpty()) { throw new IllegalStateException(); } headQueue.addAll(events); } public void addToTail(MetricDatum event) { tailQueue.add(event); } /** * Not thread safe. */ public int size() { return headQueue.size() + tailQueue.size(); } /** * Not thread safe. */ public List<MetricDatum> pollAllQueuedEvents() { List<MetricDatum> events = new LinkedList<>(); events.addAll(pollAll(headQueue)); events.addAll(pollAll(tailQueue)); return events; } private List<MetricDatum> pollAll(Queue<MetricDatum> queue) { List<MetricDatum> events = new LinkedList<>(); while (true) { MetricDatum polled = queue.poll(); if (polled != null) { events.add(polled); } else { break; } } return events; } }
7,754
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/internal/ToolkitSession.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry.internal; import java.util.Date; import java.util.UUID; import com.amazonaws.annotation.Immutable; import com.amazonaws.services.mobileanalytics.model.Session; import com.amazonaws.util.DateUtils; @Immutable public class ToolkitSession { private final String id; private final Date startTimestamp; ToolkitSession(String id, Date startTimestamp) { this.id = id; this.startTimestamp = startTimestamp; } public static ToolkitSession newSession() { String id = UUID.randomUUID().toString(); Date now = new Date(); return new ToolkitSession(id, now); } public String getId() { return id; } public Date getStartTimestamp() { return startTimestamp; } public Session toMobileAnalyticsSession() { Session session = new Session(); session.setId(this.id); session.setStartTimestamp(DateUtils.formatISO8601Date(this.startTimestamp)); return session; } }
7,755
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/internal/NoOpToolkitAnalyticsManager.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry.internal; import com.amazonaws.eclipse.core.accounts.AwsPluginAccountManager; import com.amazonaws.eclipse.core.telemetry.ToolkitAnalyticsManager; import com.amazonaws.eclipse.core.telemetry.ToolkitEvent; import com.amazonaws.eclipse.core.telemetry.ToolkitEvent.ToolkitEventBuilder; public class NoOpToolkitAnalyticsManager implements ToolkitAnalyticsManager { @Override public void startSession(AwsPluginAccountManager accountManager, boolean forceFlushEvents) { } @Override public void endSession(boolean forceFlushEvents) { } @Override public ToolkitEventBuilder eventBuilder() { return new ToolkitEventBuilder(null); } @Override public void publishEvent(ToolkitEvent event) { } @Override public void setEnabled(boolean enabled) { } }
7,756
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/internal/ToolkitAnalyticsManagerImpl.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry.internal; import static com.amazonaws.eclipse.core.util.ValidationUtils.validateNonNull; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.ICoreRunnable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.Job; import com.amazonaws.annotation.ThreadSafe; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.eclipse.core.AWSClientFactory; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.accounts.AwsPluginAccountManager; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.telemetry.ClientContextConfig; import com.amazonaws.eclipse.core.telemetry.ToolkitAnalyticsManager; import com.amazonaws.eclipse.core.telemetry.ToolkitEvent; import com.amazonaws.eclipse.core.telemetry.ToolkitEvent.ToolkitEventBuilder; import com.amazonaws.eclipse.core.telemetry.batchclient.TelemetryBatchClient; import com.amazonaws.eclipse.core.telemetry.batchclient.internal.TelemetryBatchClientImpl; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest; import com.fasterxml.jackson.core.JsonProcessingException; import software.amazon.awssdk.services.toolkittelemetry.model.MetadataEntry; import software.amazon.awssdk.services.toolkittelemetry.model.MetricDatum; @ThreadSafe public class ToolkitAnalyticsManagerImpl implements ToolkitAnalyticsManager { private volatile boolean enabled = true; private volatile String userId = null; /** * The low level client for sending PutEvents requests, which also deals with * event batching transparently */ private final TelemetryBatchClient batchClient; /** * Write access to this field is protected by this manager instance. */ private volatile ToolkitSession currentSession; /** * @param credentialsProvider the credentials provider for Mobile Analytics API * calls * @param clientContextConfig the client context to be specified in all the * PutEvents requests. * @throws JsonProcessingException if the clientContextConfig fails to be * serialized to JSON format */ public ToolkitAnalyticsManagerImpl(AWSCredentialsProvider credentialsProvider, ClientContextConfig clientContextConfig) throws JsonProcessingException { this(new TelemetryBatchClientImpl(credentialsProvider, clientContextConfig)); } /** * @param batchClient the client that is responsible for sending the events to * mobile analytics service. */ ToolkitAnalyticsManagerImpl(TelemetryBatchClient batchClient) { this.batchClient = validateNonNull(batchClient, "batchClient"); } @Override public synchronized void startSession(AwsPluginAccountManager accountManager, boolean forceFlushEvents) { if (!this.enabled) { return; } // create a new session with a random id ToolkitSession newSession = ToolkitSession.newSession(); // create a new session.start event // make sure the event timestamp is aligned to the startTimestamp of the new // session ToolkitEvent startSessionEvent = new ToolkitEventBuilder(newSession).setEventType(Constants.SESSION_START_EVENT_TYPE) .setTimestamp(newSession.getStartTimestamp()).build(); publishEvent(startSessionEvent); this.currentSession = newSession; accountManager.addAccountInfoChangeListener(this::getAccountIdFromSTS); if (forceFlushEvents) { this.batchClient.flush(); } } @Override public synchronized void endSession(boolean forceFlushEvents) { if (!this.enabled) { return; } // Do nothing if we are not in a session if (this.currentSession == null) { return; } ToolkitEvent endSessionEvent = new ToolkitEventBuilder(this.currentSession).setEventType(Constants.SESSION_STOP_EVENT_TYPE).build(); publishEvent(endSessionEvent); if (forceFlushEvents) { this.batchClient.flush(); } } @Override public ToolkitEventBuilder eventBuilder() { // Start building the event based on the current session return new ToolkitEventBuilder(this.currentSession); } @Override public void publishEvent(ToolkitEvent event) { if (!this.enabled) { return; } if (event.isValid()) { final MetricDatum metricDatum = event.toMetricDatum(); injectAccountMetadata(metricDatum); this.batchClient.putEvent(metricDatum); } else { AwsToolkitCore.getDefault().logInfo("Discarding invalid analytics event"); } } @Override public void setEnabled(boolean enabled) { this.enabled = enabled; } private void injectAccountMetadata(MetricDatum metricDatum) { final String awsAccount = userId; String region = null; try { Region r = RegionUtils.getCurrentRegion(); if (r != null) { region = r.getId(); } // regionutils throws a runtime exception if it can't determine region, ignore // if this happens } catch (Exception e) { ; } if (region != null && !region.isEmpty()) { metricDatum.getMetadata().add(new MetadataEntry().key("awsRegion").value(region)); } if (awsAccount != null && !awsAccount.isEmpty()) { metricDatum.getMetadata().add(new MetadataEntry().key("awsAccount").value(userId)); } } private void getAccountIdFromSTS() { Job j = Job.create("Loading account ID", new ICoreRunnable() { @Override public void run(IProgressMonitor monitor) throws CoreException { try { final AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(); AWSSecurityTokenService service = clientFactory.getSTSClient(); userId = service.getCallerIdentity(new GetCallerIdentityRequest()).getAccount(); } catch (Exception e) { // wipe out the field if it's enabled userId = null; } } }); j.setSystem(true); j.schedule(); } }
7,757
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/telemetry/internal/Constants.java
/* * Copyright 2015 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.core.telemetry.internal; import com.amazonaws.regions.Regions; public class Constants { /** * API Gateway endpoint for ErrorReport service. */ public static final String ERROR_REPORT_SERVICE_ENDPOINT = "https://hshkx4p74l.execute-api.us-east-1.amazonaws.com/"; public static final String AWS_TOOLKIT_FOR_ECLIPSE_PRODUCT_NAME = "aws-toolkit-for-eclipse"; public static final String AWS_TOOLKIT_FOR_ECLIPSE_PRODUCT_NAME_TEST = "aws-toolkit-for-eclipse-test"; /* * Debug setup */ public static final String MOBILE_ANALYTICS_APP_TITLE_TEST = "eclipse-toolkit-test"; public static final String MOBILE_ANALYTICS_APP_ID_TEST = "7acd90a2b0ea495aa08b83afad9d37ba"; public static final String COGNITO_IDENTITY_POOL_ID_TEST = "us-east-1:f63ac181-d01d-4a8f-91b2-c6aac01f899b"; /* * Error reporting prod setup */ public static final String MOBILE_ANALYTICS_APP_TITLE_PROD = "eclipse-toolkit-prod"; public static final String MOBILE_ANALYTICS_APP_ID_PROD = "f46ac3eb2a67407caf8352a3210bf8b0"; public static final String COGNITO_IDENTITY_POOL_ID_PROD = "us-east-1:d4fdc07f-94fd-4cc6-94fb-f903657f05c1"; /* * V2 setup */ public static final String COGNITO_IDENTITY_POOL_ID_PROD_V2 = "us-east-1:820fd6d1-95c0-4ca4-bffb-3f01d32da842"; /* * Java preferences system data key */ public static final String JAVA_PREFERENCE_NODE_FOR_AWS_TOOLKIT_FOR_ECLIPSE = "aws-toolkit-for-eclipse"; /* * Preference store location for persisting user data */ public static final String MOBILE_ANALYTICS_CLIENT_ID_PREF_STORE_KEY = "mobileAnalyticsClientId"; public static final String COGNITO_IDENTITY_ID_PREF_STORE_KEY = "cognitoIdentityId"; public static final String COGNITO_IDENTITY_POOL_ID_PREF_STORE_KEY = "cognitoIdentityPoolId"; /* * For constructing client context header */ public static final String CLIENT_CONTEXT_MAP_KEY_CLIENT_ID = "client_id"; public static final String CLIENT_CONTEXT_MAP_KEY_APP_TITLE = "app_title"; public static final String CLIENT_CONTEXT_MAP_KEY_PLATFORM_NAME = "platform"; public static final String CLIENT_CONTEXT_MAP_KEY_PLATFORM_VERSION = "platform_version"; public static final String CLIENT_CONTEXT_MAP_KEY_LOCALE = "locale"; public static final String CLIENT_CONTEXT_MAP_KEY_SERVICE_NAME = "mobile_analytics"; public static final String CLIENT_CONTEXT_MAP_KEY_APP_ID = "app_id"; /* * See valid values for platform name: * http://docs.aws.amazon.com/mobileanalytics/latest/ug/PutEvents.html#putEvents-request-client-context-header */ public static final String CLIENT_CONTEXT_ENV_PLATFORM_WINDOWS = "windows"; public static final String CLIENT_CONTEXT_ENV_PLATFORM_MACOS = "macos"; public static final String CLIENT_CONTEXT_ENV_PLATFORM_LINUX = "linux"; public static final String SESSION_START_EVENT_TYPE = "session_start"; public static final String SESSION_STOP_EVENT_TYPE = "session_stop"; /* * Mobile Analytics service limits */ public static final int MAX_ATTRIBUTES_AND_METRICS_PER_EVENT = 40; public static final int MAX_ATTRIBUTE_OR_METRIC_NAME_LENGTH = 50; public static final int MAX_ATTRIBUTE_VALUE_LENGTH = 200; /* * Default region for Cognito Identity service */ public static final Regions COGNITO_IDENTITY_SERVICE_REGION = Regions.US_EAST_1; /* * Mobile Analytics service version * http://docs.aws.amazon.com/mobileanalytics/latest/ug/PutEvents.html#putEvents-requests */ public static final String MOBILE_ANALYTICS_SERVICE_VERSION = "v2.0"; }
7,758
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/AWSResourcesRootElement.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; /** * Generic root object for the resource explorer tree. */ public class AWSResourcesRootElement {}
7,759
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/DragAdapterAssistant.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.Transfer; import org.eclipse.ui.navigator.CommonDragAdapterAssistant; import org.eclipse.ui.part.PluginTransfer; import com.amazonaws.services.s3.model.S3ObjectSummary; public class DragAdapterAssistant extends CommonDragAdapterAssistant { @Override public void dragStart(DragSourceEvent anEvent, IStructuredSelection aSelection) { anEvent.doit = aSelection.size() == 1 && aSelection.getFirstElement() instanceof S3ObjectSummary; /* * We need to make sure that our drag is treated *only* as a plugin * transfer, whereas the superclass defaults to treating all such events * as either LocalSelectionTransfer or PluginTransfer. In the case of * the former, the drag adapter for other views won't recognize the * object being dropped and so disallows it. */ DragSource source = ((DragSource) anEvent.getSource()); source.setTransfer(getSupportedTransferTypes()); //printEvent(anEvent); } public DragAdapterAssistant() { } /* * This list is added to the list of defaults, so it's a no-op in its * intended context. However, we include it here as a convenience for * dragStart() */ @Override public Transfer[] getSupportedTransferTypes() { return new Transfer[] { PluginTransfer.getInstance(), }; } private void printEvent(DragSourceEvent e) { System.out.println("\n\n\nEVENT START\n\n\n"); StringBuffer sb = new StringBuffer(); DragSource source = ((DragSource) e.widget); sb.append("widget: "); sb.append(e.widget); sb.append(", source.Transfer: "); sb.append(source.getTransfer().length + " elements; "); for ( Transfer transfer : source.getTransfer() ) { sb.append(transfer).append("; "); } sb.append(System.identityHashCode(source)); sb.append(", time: "); sb.append(e.time); sb.append(", operation: "); sb.append(e.detail); sb.append(", type: "); sb.append(e.dataType != null ? e.dataType.type : 0); sb.append(", doit: "); sb.append(e.doit); sb.append(", data: "); sb.append(e.data); sb.append(", dataType: "); sb.append(e.dataType); sb.append("\n"); System.out.println(sb.toString()); System.out.println("\n\n\nEVENT END\n\n\n"); } /* (non-Javadoc) * @see org.eclipse.ui.navigator.CommonDragAdapterAssistant#setDragData(org.eclipse.swt.dnd.DragSourceEvent, org.eclipse.jface.viewers.IStructuredSelection) */ @Override public boolean setDragData(DragSourceEvent anEvent, IStructuredSelection aSelection) { //printEvent(anEvent); return true; } }
7,760
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/AccountNotConfiguredContentProvider.java
/* * Copyright 2011-2013 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.dialogs.PreferencesUtil; import com.amazonaws.eclipse.core.AwsToolkitCore; /** * A single content provider for the AWS Explorer view that notifies the user * of process-wide configuration issues like not having configured any * credentials to use for communicating with AWS. If there is such an issue, * this provider contributes a single child to the AWSResourcesRootElement * that describes the error and gives quick links to fix it. Otherwise, it * lurks silently in the background contributing nothing. */ public class AccountNotConfiguredContentProvider implements ITreeContentProvider { @Override public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) { } /** * This content provider contributes a child to the root element if and * only if there are no valid credentials configured. */ @Override public boolean hasChildren(final Object element) { return ((element instanceof AWSResourcesRootElement) && !areCredentialsConfigured()); } @Override public Object[] getChildren(final Object parentElement) { if (parentElement instanceof AWSResourcesRootElement && !areCredentialsConfigured()) { return new Object[] { new AccountNotConfiguredNode() }; } return new Object[0]; } @Override public Object[] getElements(final Object inputElement) { return getChildren(inputElement); } @Override public Object getParent(final Object element) { return null; } @Override public void dispose() { } private boolean areCredentialsConfigured() { return AwsToolkitCore.getDefault().getAccountInfo().isValid(); } /** * An action that opens the account preferences tab so the user * can configure some credentials. */ private static final class OpenAccountPreferencesAction extends Action { public OpenAccountPreferencesAction() { super.setText("Configure AWS Accounts"); super.setImageDescriptor(AwsToolkitCore .getDefault() .getImageRegistry() .getDescriptor(AwsToolkitCore.IMAGE_GEAR) ); } @Override public void run() { String resource = AwsToolkitCore.ACCOUNT_PREFERENCE_PAGE_ID; PreferencesUtil.createPreferenceDialogOn( null, // shell; null uses the active workbench window resource, new String[] { resource }, null // data; not used in this case ).open(); } } /** * ExplorerNode alerting users that the current account is not fully * configured. */ public static class AccountNotConfiguredNode extends ExplorerNode { public AccountNotConfiguredNode() { super("AWS Account not Configured", 0, // sort priority. ExplorerNode.loadImage(AwsToolkitCore.IMAGE_GEARS), new OpenAccountPreferencesAction()); } } }
7,761
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/ContentProviderRegistry.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; import java.util.HashSet; import java.util.Set; /** * Registry of content providers which are providing content for the AWS Explorer view. */ public class ContentProviderRegistry { private static Set<AbstractContentProvider> contentProviders = new HashSet<>(); private ContentProviderRegistry() {} public static void registerContentProvider(AbstractContentProvider contentProvider) { contentProviders.add(contentProvider); } public static void unregisterContentProvider(AbstractContentProvider contentProvider) { contentProviders.remove(contentProvider); } public static void refreshAllContentProviders() { for (AbstractContentProvider contentProvider : contentProviders) { contentProvider.refresh(); } } public static void clearAllCachedResponses () { for (AbstractContentProvider contentProvider : contentProviders) { contentProvider.clearCachedResponse(); } } }
7,762
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/AbstractAwsResourceEditorInput.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IPersistableElement; public abstract class AbstractAwsResourceEditorInput implements IEditorInput { private final String regionEndpoint; private final String accountId; private final String regionId; /** * @deprecated over {@link #AbstractAwsResourceEditorInput(String, String, String)} */ @Deprecated public AbstractAwsResourceEditorInput(String regionEndpoint, String accountId) { this(regionEndpoint, accountId, null); } public AbstractAwsResourceEditorInput(String regionEndpoint, String accountId, String regionId) { this.regionEndpoint = regionEndpoint; this.accountId = accountId; this.regionId = regionId; } public String getRegionEndpoint() { return regionEndpoint; } public String getAccountId() { return accountId; } public String getRegionId() { return regionId; } @Override public Object getAdapter(Class adapter) { return null; } @Override public boolean exists() { return true; } @Override public IPersistableElement getPersistable() { return null; } }
7,763
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/RefreshRunnable.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; import org.eclipse.jface.viewers.TreeViewer; /** * Display-thread runnable to refresh an element in the tree. */ public final class RefreshRunnable implements Runnable { private final Object parentElement; private final TreeViewer viewer; public RefreshRunnable(TreeViewer viewer, Object parentElement) { this.parentElement = parentElement; this.viewer = viewer; } @Override public void run() { this.viewer.refresh(parentElement); } }
7,764
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/ResourcesView.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; import java.util.Iterator; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IMemento; import org.eclipse.ui.IViewSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.navigator.CommonNavigator; import org.eclipse.ui.navigator.CommonViewer; import com.amazonaws.eclipse.core.AccountAndRegionChangeListener; import com.amazonaws.eclipse.core.AwsToolkitCore; public class ResourcesView extends CommonNavigator { private static final ExplorerNodeOpenListener EXPLORER_NODE_OPEN_LISTENER = new ExplorerNodeOpenListener(); public static final AWSResourcesRootElement rootElement = new AWSResourcesRootElement(); private CommonViewer viewer; private AccountAndRegionChangeListener accountAndRegionChangeListener; @Override protected Object getInitialInput() { return rootElement; } @Override protected CommonViewer createCommonViewerObject(Composite aParent) { viewer = super.createCommonViewerObject(aParent); viewer.addOpenListener(EXPLORER_NODE_OPEN_LISTENER); viewer.setAutoExpandLevel(1); return viewer; } @Override public void dispose() { getCommonViewer().removeOpenListener(EXPLORER_NODE_OPEN_LISTENER); if (accountAndRegionChangeListener != null) { AwsToolkitCore.getDefault().getAccountManager().removeAccountInfoChangeListener(accountAndRegionChangeListener); AwsToolkitCore.getDefault().getAccountManager().removeDefaultAccountChangeListener(accountAndRegionChangeListener); AwsToolkitCore.getDefault().removeDefaultRegionChangeListener(accountAndRegionChangeListener); } } @Override public void init(IViewSite aSite, IMemento aMemento) throws PartInitException { super.init(aSite, aMemento); accountAndRegionChangeListener = new AccountAndRegionChangeListener() { @Override public void onAccountOrRegionChange() { ContentProviderRegistry.clearAllCachedResponses(); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { viewer.refresh(); viewer.collapseAll(); } }); } }; Display.getDefault().asyncExec(new Runnable() { @Override public void run() { AwsToolkitCore.getDefault().getAccountManager().addAccountInfoChangeListener(accountAndRegionChangeListener); AwsToolkitCore.getDefault().getAccountManager().addDefaultAccountChangeListener(accountAndRegionChangeListener); AwsToolkitCore.getDefault().addDefaultRegionChangeListener(accountAndRegionChangeListener); } }); } private static final class ExplorerNodeOpenListener implements IOpenListener { @Override public void open(OpenEvent event) { StructuredSelection selection = (StructuredSelection)event.getSelection(); Iterator<?> i = selection.iterator(); while (i.hasNext()) { Object obj = i.next(); if (obj instanceof ExplorerNode) { ExplorerNode explorerNode = (ExplorerNode)obj; IAction openAction = explorerNode.getOpenAction(); if (openAction != null) openAction.run(); } } } } }
7,765
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/AwsAction.java
/* * Copyright 2017 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; import org.eclipse.jface.action.Action; import org.eclipse.jface.resource.ImageDescriptor; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.core.telemetry.MetricsDataModel; public abstract class AwsAction extends Action { public static final String END_RESULT = "result"; public static final String SUCCEEDED = "Succeeded"; public static final String FAILED = "Failed"; public static final String CANCELED = "Canceled"; private final MetricsDataModel metricsDataModel; protected AwsAction() { metricsDataModel = null; } protected AwsAction(AwsToolkitMetricType metricType) { if (metricType == null) { metricsDataModel = null; } else { metricsDataModel = new MetricsDataModel(metricType); } } protected AwsAction(AwsToolkitMetricType metricType, String text) { super(text); this.metricsDataModel = new MetricsDataModel(metricType); } protected AwsAction(AwsToolkitMetricType metricType, String text, int style) { super(text, style); this.metricsDataModel = new MetricsDataModel(metricType); } protected AwsAction(AwsToolkitMetricType metricType, String text, ImageDescriptor image) { super(text, image); this.metricsDataModel = new MetricsDataModel(metricType); } private final void actionPerformed() { if (metricsDataModel != null) { metricsDataModel.addAttribute(END_RESULT, SUCCEEDED); } } protected final void actionSucceeded() { if (metricsDataModel != null) { metricsDataModel.addAttribute(END_RESULT, SUCCEEDED); } } protected final void actionFailed() { if (metricsDataModel != null) { metricsDataModel.addAttribute(END_RESULT, FAILED); } } protected final void actionCanceled() { if (metricsDataModel != null) { metricsDataModel.addAttribute(END_RESULT, CANCELED); } } protected final void actionFinished() { if (metricsDataModel != null) { metricsDataModel.publishEvent(); } } @Override public void run() { actionPerformed(); doRun(); } protected abstract void doRun(); // Helper method to publish a failed action metric immediately public static void publishFailedAction(AwsToolkitMetricType metricType) { publishFailedAction(new MetricsDataModel(metricType)); } // Helper method to publish a failed action metric immediately public static void publishFailedAction(MetricsDataModel dataModel) { dataModel.addAttribute(END_RESULT, FAILED).publishEvent(); } // Helper method to publish a succeeded action metric immediately public static void publishSucceededAction(AwsToolkitMetricType metricType) { publishSucceededAction(new MetricsDataModel(metricType)); } // Helper method to publish a succeeded action metric immediately public static void publishSucceededAction(MetricsDataModel dataModel) { dataModel.addAttribute(END_RESULT, SUCCEEDED).publishEvent(); } // Helper method to publish a performed action metric immediately public static void publishPerformedAction(AwsToolkitMetricType metricType) { publishPerformedAction(new MetricsDataModel(metricType)); } // Helper method to publish a performed action metric immediately public static void publishPerformedAction(MetricsDataModel dataModel) { dataModel.addAttribute(END_RESULT, SUCCEEDED).publishEvent(); } }
7,766
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/Loading.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; import org.eclipse.core.runtime.PlatformObject; /** * Simple marker object for asynchronous tree updates. */ public class Loading extends PlatformObject { public static final Object[] LOADING = new Object[] { new Loading() }; private Loading() { } @Override public String toString() { return "Loading..."; } }
7,767
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/ExplorerNode.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; import org.eclipse.core.runtime.PlatformObject; import org.eclipse.jface.action.IAction; import org.eclipse.swt.graphics.Image; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin; public class ExplorerNode extends PlatformObject { private int sortPriority; private final String name; private Image image; private IAction openAction; public ExplorerNode(String name) { this.name = name; } public ExplorerNode(String name, int sortPriority) { this(name); setSortPriority(sortPriority); } public ExplorerNode(String name, int sortPriority, Image image) { this(name, sortPriority); setImage(image); } public ExplorerNode(String name, int sortPriority, Image image, IAction openAction) { this(name, sortPriority, image); setOpenAction(openAction); } public int getSortPriority() { return sortPriority; } public String getName() { return name; } public void setSortPriority(int sortPriority) { this.sortPriority = sortPriority; } public void setImage(Image image) { this.image = image; } public Image getImage() { return image; } public void setOpenAction(IAction openAction) { this.openAction = openAction; } public IAction getOpenAction() { return openAction; } @Override public String toString() { return "ExplorerNode: " + name; } protected static Image loadImage(final String imageId) { return loadImage(AwsToolkitCore.getDefault(), imageId); } protected static Image loadImage(AbstractAwsPlugin plugin, final String imageId) { return plugin.getImageRegistry().get(imageId); } }
7,768
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/ExplorerNodeLabelProvider.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; public class ExplorerNodeLabelProvider extends LabelProvider { @Override public String getText(Object element) { return getExplorerNodeText(element); } @Override public Image getImage(Object element) { if (element instanceof ExplorerNode) { ExplorerNode navigatorNode = (ExplorerNode)element; return navigatorNode.getImage(); } return getDefaultImage(element); } public String getExplorerNodeText(Object element) { if (element instanceof ExplorerNode) { ExplorerNode navigatorNode = (ExplorerNode)element; return navigatorNode.getName(); } return element.toString(); } /** * Subclasses can override this method to provide their own default image to * display for nodes in the Explorer view. * * @param element * The element whose default image is being requested. * * @return The default image to display for nodes in the Explorer view. */ public Image getDefaultImage(Object element) { return null; } }
7,769
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/AbstractContentProvider.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer; import static com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType.EXPLORER_LOADING; import static com.amazonaws.eclipse.core.telemetry.ToolkitAnalyticsUtils.publishBooleansEvent; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.widgets.Display; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.BrowserUtils; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.core.ui.IRefreshable; /** * Abstract base class for AWS Explorer content providers. This class provides * basic implementations for ContentProvider methods as well as handling * refreshing the content when the current account or region changes. This class * also handles caching and returning results for previously loaded data. */ public abstract class AbstractContentProvider implements ITreeContentProvider, IRefreshable { /** Reference to the TreeViewer in which content will be displayed. */ protected TreeViewer viewer; /** Cache for previously loaded data */ protected Map<Object, Object[]> cachedResponses = new ConcurrentHashMap<>(); protected BackgroundContentUpdateJobFactory backgroundJobFactory; /** * Creates a new AbstractContentProvider and registers it with the registry * of AWS Explorer ContentProviders. */ public AbstractContentProvider() { ContentProviderRegistry.registerContentProvider(this); } /** * Loads the children for the specified parent element. Subclasses must * implement this method, and should use {@link DataLoaderThread} * implementations to load any remote AWS data asynchronously. Caching is * handling by {@link AbstractContentProvider}, so this method will only be * invoked if no data was found in the cache and remote data needs to be * loaded. * <p> * Subclasses should implement this method and <b>not</b> the getElement or * getChildren methods. * * @param parentElement * The parent element indicating what child data needs to be * loaded. * * @return The child elements for the specified parent, or null if they are * being loaded asynchronously, and the super class will handle * displaying a loading message. */ public abstract Object[] loadChildren(Object parentElement); /** * Returns the service abbreviation uniquely identifying the service the * ContentProvider subclass is working with. * * @see ServiceAbbreviations * * @return the service abbreviation uniquely identifying the service the * ContentProvider subclass is working with. */ public abstract String getServiceAbbreviation(); /** * Thread to asynchronously load data for an AWS Explorer ContentProvider. * This class takes care of several error cases, such as not being signed up * for a service yet and handles them correctly so that subclasses don't * have to worry about. Subclasses simply need to implement the loadData() * method to return their specific data. * * This class also takes care of storing the returned results from * loadData() into the ContentProvider's cache. */ protected abstract class DataLoaderThread extends Thread { private final Object parentElement; /** Various AWS error codes indicating that a developer isn't signed up yet. */ private final List<String> NOT_SIGNED_UP_ERROR_CODES = Arrays.asList("NotSignedUp", "SubscriptionCheckFailed", "OptInRequired"); public DataLoaderThread(Object parentElement) { this.parentElement = parentElement; } /** * Returns the data being loaded by this thread, which is specific to * each individual ContentProvider (ex: SimpleDB domains, EC2 instances, * etc). * * @return The loaded data (ex: an array of EC2 instances, or SimpleDB * domains, etc). */ public abstract Object[] loadData(); @Override public final void run() { try { cachedResponses.put(parentElement, loadData()); if ( null != backgroundJobFactory ) { backgroundJobFactory.startBackgroundContentUpdateJob(parentElement); } } catch (Exception e) { if ( e instanceof AmazonServiceException && NOT_SIGNED_UP_ERROR_CODES.contains(((AmazonServiceException) e).getErrorCode()) ) { cachedResponses.put(parentElement, new Object[] { new NotSignedUpNode(((AmazonServiceException) e).getServiceName()) }); } else { cachedResponses.put(parentElement, new Object[] { new UnableToConnectNode() }); } AwsToolkitCore.getDefault().logWarning("Error loading explorer data", e); } Display.getDefault().syncExec(new RefreshRunnable(viewer, parentElement)); } } /** * Clears all cached responses and reinitializes the tree. */ public synchronized void refresh() { this.cachedResponses.clear(); Object[] children = this.getChildren(new AWSResourcesRootElement()); if (children.length == 0) { return; } Object tempObject = null; if (children.length == 1) { tempObject = children[0]; } final Object rootElement = tempObject; Display.getDefault().asyncExec(new Runnable() { @Override public void run() { viewer.getTree().deselectAll(); viewer.refresh(rootElement); viewer.expandToLevel(1); } }); } @Override public void refreshData() { refresh(); } @Override public Object[] getElements(Object inputElement) { return getChildren(inputElement); } @Override public Object getParent(Object element) { return null; } @Override public final Object[] getChildren(final Object parentElement) { if (!RegionUtils.isServiceSupportedInCurrentRegion(getServiceAbbreviation())) { return new Object[0]; } if ( cachedResponses.containsKey(parentElement)) { if ( null != backgroundJobFactory ) { backgroundJobFactory.startBackgroundContentUpdateJob(parentElement); } if (!(parentElement instanceof AWSResourcesRootElement)) { publishBooleansEvent(EXPLORER_LOADING, parentElement.getClass().getSimpleName(), true); } return cachedResponses.get(parentElement); } if (!AwsToolkitCore.getDefault().getAccountInfo().isValid()) { return new Object[0]; } Object[] children = loadChildren(parentElement); if (children == null) { children = Loading.LOADING; } return children; } @Override public void dispose() { ContentProviderRegistry.unregisterContentProvider(this); } public void clearCachedResponse() { cachedResponses.clear(); } @Override public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) { this.viewer = (TreeViewer) viewer; } /** * Sets a background job factory which will create Job and execute it * periodically to update the content. The underlying Job object will be * scheduled whenever {@link AbstractContentProvider#getChildren(Object)} * method is called. */ public void setBackgroundJobFactory(BackgroundContentUpdateJobFactory backgroundJobFactory) { this.backgroundJobFactory = backgroundJobFactory; } /** ExplorerNode alerting the user that they need to sign up for a service. */ private static class NotSignedUpNode extends ExplorerNode { private static final class SignUpAction extends Action { public SignUpAction() { super.setText("Sign up"); super.setImageDescriptor(AwsToolkitCore .getDefault() .getImageRegistry() .getDescriptor(AwsToolkitCore.IMAGE_EXTERNAL_LINK) ); } @Override public void run() { BrowserUtils.openExternalBrowser("https://aws-portal.amazon.com/gp/aws/developer/registration"); } } public NotSignedUpNode(final String serviceName) { super(serviceName + " (not signed up)", 0, loadImage(AwsToolkitCore.IMAGE_EXTERNAL_LINK), new SignUpAction()); } } /** ExplorerNode alerting users that we couldn't connect to AWS. */ private static class UnableToConnectNode extends ExplorerNode { public UnableToConnectNode() { super("Unable to connect", 0, loadImage(AwsToolkitCore.IMAGE_AWS_ICON)); } } protected abstract class BackgroundContentUpdateJobFactory { private Map<Object, Job> backgroundJobs = new ConcurrentHashMap<>(); /** * Defines the behavior of the background job. Returned boolean values * indicates whether the background should keep running. */ protected abstract boolean executeBackgroundJob(Object parentElement) throws AmazonClientException; /** * This method will be used for setting the delay between subsequent * execution of the background job. */ protected abstract long getRefreshDelay(); private Job getBackgroundJobByParentElement(Object parentElement) { return backgroundJobs.get(parentElement); } public synchronized void startBackgroundContentUpdateJob(final Object parentElement) { Job currentJob = getBackgroundJobByParentElement(parentElement); if ( currentJob == null ) { /* * Initiates a new background job for asynchronously updating the * content. (e.g. updating TableNode status) */ final Job newJob = new Job("Updating contents") { private Object updatedParentElement = parentElement; @Override protected IStatus run(IProgressMonitor monitor) { try { if ( executeBackgroundJob(updatedParentElement) ) { /* Reschedule the job after some delay */ this.schedule(getRefreshDelay()); } else { /* If the background job has already finished its work, * remove the parent element from the map. */ backgroundJobs.remove(updatedParentElement); } } catch (AmazonClientException e) { return new Status(Status.ERROR, AwsToolkitCore.getDefault().getPluginId(), "Unable to update the content: " + e.getMessage(), e); } return Status.OK_STATUS; } }; newJob.schedule(); backgroundJobs.put(parentElement, newJob); } else { /* Restart the current job */ currentJob.cancel(); currentJob.schedule(); } } } }
7,770
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/BucketEditor.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.part.EditorPart; import com.amazonaws.AmazonClientException; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.Region; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.eclipse.explorer.s3.acls.EditBucketPermissionsDialog; import com.amazonaws.eclipse.explorer.s3.acls.EditPermissionsDialog; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.Bucket; public class BucketEditor extends EditorPart { public final static String ID = "com.amazonaws.eclipse.explorer.s3.bucketEditor"; private BucketEditorInput bucketEditorInput; private S3ObjectSummaryTable objectSummaryTable; public S3ObjectSummaryTable getObjectSummaryTable() { return objectSummaryTable; } @Override public void doSave(IProgressMonitor monitor) {} @Override public void doSaveAs() {} @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); bucketEditorInput = (BucketEditorInput) input; setPartName(input.getName()); } @Override public boolean isDirty() { return false; } @Override public boolean isSaveAsAllowed() { return false; } @Override public void createPartControl(Composite parent) { FormToolkit toolkit = new FormToolkit(Display.getDefault()); ScrolledForm form = new ScrolledForm(parent, SWT.V_SCROLL); form.setExpandHorizontal(true); form.setExpandVertical(true); form.setBackground(toolkit.getColors().getBackground()); form.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); form.setFont(JFaceResources.getHeaderFont()); form.setText(bucketEditorInput.getBucketName()); toolkit.decorateFormHeading(form.getForm()); form.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_BUCKET)); form.getBody().setLayout(new GridLayout(1, false)); createBucketSummary(form, toolkit, bucketEditorInput.getBucketName()); createBucketObjectList(form, toolkit, bucketEditorInput.getBucketName()); form.getToolBarManager().add(new RefreshAction()); form.getToolBarManager().update(true); } private class RefreshAction extends AwsAction { public RefreshAction() { super(AwsToolkitMetricType.EXPLORER_S3_REFRESH_BUCKET_EDITOR); this.setText("Refresh"); this.setToolTipText("Refresh bucket contents"); this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH)); } @Override protected void doRun() { objectSummaryTable.refresh(null); actionFinished(); } } /** * Creates a table of buckets */ private void createBucketObjectList(final ScrolledForm form, final FormToolkit toolkit, final String bucketName) { objectSummaryTable = new S3ObjectSummaryTable(bucketEditorInput.getAccountId(), bucketEditorInput.getBucketName(), bucketEditorInput.getRegionEndpoint(), form.getBody(), toolkit, SWT.None); objectSummaryTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); } /** * Creates a summary of a bucket */ private void createBucketSummary(final ScrolledForm form, final FormToolkit toolkit, final String bucketName) { final Composite parent = toolkit.createComposite(form.getBody(), SWT.None); parent.setLayout(new GridLayout(2, false)); toolkit.createLabel(parent, "Bucket info loading"); toolkit.createLabel(parent, ""); new Thread() { @Override public void run() { Bucket bucket = null; // TODO: We don't need to list all the buckets just to get one for ( Bucket b : AwsToolkitCore.getClientFactory().getS3Client().listBuckets() ) { if ( b.getName().equals(bucketEditorInput.getName()) ) { bucket = b; break; } } if ( bucket == null ) return; updateComposite(form, toolkit, bucket); } protected void updateComposite(final ScrolledForm form, final FormToolkit toolkit, final Bucket b) { Display.getDefault().syncExec(new Runnable() { @Override public void run() { for ( Control c : parent.getChildren() ) { c.dispose(); } toolkit.createLabel(parent, "Owner: "); toolkit.createLabel(parent, b.getOwner().getDisplayName()); toolkit.createLabel(parent, "Creation Date: "); toolkit.createLabel(parent, b.getCreationDate().toString()); Button editBucketAclButton = toolkit.createButton(parent, "Edit Bucket ACL", SWT.PUSH); editBucketAclButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { final EditPermissionsDialog editPermissionsDialog = new EditBucketPermissionsDialog(b); if (editPermissionsDialog.open() == 0) { Region region = RegionUtils.getRegionByEndpoint(bucketEditorInput.getRegionEndpoint()); final AmazonS3 s3 = AwsToolkitCore.getClientFactory().getS3ClientByRegion(region.getId()); new Job("Updating bucket ACL") { @Override protected IStatus run(IProgressMonitor monitor) { try { s3.setBucketAcl(b.getName(), editPermissionsDialog.getAccessControlList()); } catch (AmazonClientException ace) { AwsToolkitCore.getDefault().reportException("Unable to update bucket ACL", ace); } return Status.OK_STATUS; } }.schedule(); } } @Override public void widgetDefaultSelected(SelectionEvent e) {} }); form.reflow(true); } }); } }.start(); } @Override public void setFocus() { } }
7,771
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/S3Constants.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.explorer.s3; public class S3Constants { public static final int MAX_S3_OBJECT_TAGS = 10; public static final int MAX_S3_OBJECT_TAG_KEY_LENGTH = 128; public static final int MAX_S3_OBJECT_TAG_VALUE_LENGTH = 256; }
7,772
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/BucketEditorInput.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3; import org.eclipse.jface.resource.ImageDescriptor; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.explorer.AbstractAwsResourceEditorInput; public final class BucketEditorInput extends AbstractAwsResourceEditorInput { private final String bucketName; public BucketEditorInput(String bucketName, String endpoint, String accountId) { super(endpoint, accountId); this.bucketName = bucketName; } @Override public String getToolTipText() { return "Amazon S3 Bucket Editor - " + bucketName; } @Override public String getName() { return bucketName; } @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_BUCKET); } public String getBucketName() { return bucketName; } @Override public boolean equals(Object obj) { if ( obj == null || !(obj instanceof BucketEditorInput) ) return false; return ((BucketEditorInput) obj).getBucketName().equals(this.getBucketName()); } }
7,773
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/OpenBucketEditorAction.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.explorer.AwsAction; public class OpenBucketEditorAction extends AwsAction { private final String bucketName; public OpenBucketEditorAction(String bucketName) { super(AwsToolkitMetricType.EXPLORER_S3_OPEN_BUCKET_EDITOR); this.bucketName = bucketName; this.setText("Open in S3 Bucket Editor"); } @Override protected void doRun() { String endpoint = AwsToolkitCore.getClientFactory().getS3BucketEndpoint(bucketName); String accountId = AwsToolkitCore.getDefault().getCurrentAccountId(); final IEditorInput input = new BucketEditorInput(bucketName, endpoint, accountId); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); activeWindow.getActivePage().openEditor(input, "com.amazonaws.eclipse.explorer.s3.bucketEditor"); actionSucceeded(); } catch (PartInitException e) { actionFailed(); AwsToolkitCore.getDefault().logError("Unable to open the Amazon S3 bucket editor", e); } finally { actionFinished(); } } }); } }
7,774
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/S3LabelProvider.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3; import org.eclipse.swt.graphics.Image; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider; import com.amazonaws.services.s3.model.Bucket; public class S3LabelProvider extends ExplorerNodeLabelProvider { @Override public String getText(Object element) { if ( element instanceof Bucket ) { return ((Bucket)element).getName(); } if ( element instanceof S3RootElement ) { return "Amazon S3"; } return getExplorerNodeText(element); } /* * All elements in the tree right now are buckets, and we want a bucket to * represent the root node as well */ @Override public Image getDefaultImage(Object element) { if ( element instanceof S3RootElement ) { return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_S3_SERVICE); } else { return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_BUCKET); } } }
7,775
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/BucketLinkHelper.java
package com.amazonaws.eclipse.explorer.s3; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.navigator.ILinkHelper; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.s3.model.Bucket; public class BucketLinkHelper implements ILinkHelper { /** * Finds the bucket corresponding to the editor input. */ @Override public IStructuredSelection findSelection(IEditorInput anInput) { if (!( anInput instanceof BucketEditorInput )) return null; Object[] buckets = S3ContentProvider.getInstance().getChildren(S3RootElement.ROOT_ELEMENT); Object bucket = null; for ( Object o : buckets ) { Bucket b = (Bucket) o; if ( b.getName().equals(((BucketEditorInput) anInput).getBucketName()) ) { bucket = b; } } if ( bucket == null ) return null; return new StructuredSelection(bucket); } /** * Activates the relevant editor for the selection given. If an editor for * this bucket isn't already open, won't open it. */ @Override public void activateEditor(IWorkbenchPage aPage, IStructuredSelection aSelection) { Bucket b = (Bucket) aSelection.getFirstElement(); try { for ( IEditorReference ref : aPage.getEditorReferences() ) { if ( ref.getEditorInput() instanceof BucketEditorInput ) { if ( b.getName().equals(((BucketEditorInput) ref.getEditorInput()).getBucketName()) ) { aPage.openEditor(ref.getEditorInput(), BucketEditor.ID); return; } } } } catch ( PartInitException e ) { AwsToolkitCore.getDefault().logError("Unable to open the Amazon S3 bucket editor: ", e); } } }
7,776
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/S3ContentProvider.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3; import java.util.Iterator; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.ServiceAbbreviations; import com.amazonaws.eclipse.explorer.AWSResourcesRootElement; import com.amazonaws.eclipse.explorer.AbstractContentProvider; import com.amazonaws.eclipse.explorer.Loading; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.Bucket; public class S3ContentProvider extends AbstractContentProvider { private static S3ContentProvider instance; private final IOpenListener listener = new IOpenListener() { @Override public void open(OpenEvent event) { StructuredSelection selection = (StructuredSelection)event.getSelection(); Iterator<?> i = selection.iterator(); while ( i.hasNext() ) { Object obj = i.next(); if ( obj instanceof Bucket ) { Bucket bucket = (Bucket) obj; OpenBucketEditorAction action = new OpenBucketEditorAction(bucket.getName()); action.run(); } } } }; @Override public void dispose() { viewer.removeOpenListener(listener); super.dispose(); } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { super.inputChanged(viewer, oldInput, newInput); this.viewer.addOpenListener(listener); } public S3ContentProvider() { instance = this; } public static S3ContentProvider getInstance() { return instance; } @Override public boolean hasChildren(Object element) { return (element instanceof AWSResourcesRootElement || element instanceof S3RootElement); } @Override public Object[] loadChildren(Object parentElement) { if ( parentElement instanceof AWSResourcesRootElement ) { return new Object[] { S3RootElement.ROOT_ELEMENT }; } if ( parentElement instanceof S3RootElement ) { new DataLoaderThread(parentElement) { @Override public Object[] loadData() { AmazonS3 s3 = AwsToolkitCore.getClientFactory().getS3Client(); return s3.listBuckets().toArray(); } }.start(); } return Loading.LOADING; } @Override public String getServiceAbbreviation() { return ServiceAbbreviations.S3; }; }
7,777
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/S3RootElement.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3; /** * Root element for S3 resources in the resource explorer */ public class S3RootElement { public static final S3RootElement ROOT_ELEMENT = new S3RootElement(); private S3RootElement() { } @Override public String toString() { return "Amazon S3"; } }
7,778
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/S3ObjectSummaryTable.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.layout.TreeColumnLayout; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.util.LocalSelectionTransfer; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ILazyTreePathContentProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.ITreeSelection; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceAdapter; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetAdapter; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.part.PluginTransfer; import org.eclipse.ui.part.PluginTransferData; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.explorer.s3.actions.DeleteObjectAction; import com.amazonaws.eclipse.explorer.s3.actions.EditObjectPermissionsAction; import com.amazonaws.eclipse.explorer.s3.actions.EditObjectTagsAction; import com.amazonaws.eclipse.explorer.s3.actions.GeneratePresignedUrlAction; import com.amazonaws.eclipse.explorer.s3.dnd.S3ObjectSummaryDropAction; import com.amazonaws.eclipse.explorer.s3.dnd.UploadDropAssistant; import com.amazonaws.eclipse.explorer.s3.dnd.UploadFilesJob; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.transfer.TransferManager; /** * S3 object listing with virtual directory support. */ public class S3ObjectSummaryTable extends Composite { private final static Object LOADING = new Object(); private final static Object LOADING_DONE = new Object(); private final static String DEFAULT_DELIMITER = "/"; private static final int KEY_COL = 0; private static final int ETAG_COL = 1; private static final int OWNER_COL = 2; private static final int SIZE_COL = 3; private static final int STORAGE_CLASS_COL = 4; private static final int LAST_MODIFIED_COL = 5; private final String bucketName; private final String accountId; private final String regionId; private final Map<TreePath, Object[]> children; private final TreeViewer viewer; private final Map<ImageDescriptor, Image> imageCache = new HashMap<>(); private final class S3ObjectSummaryContentProvider implements // ITreePathContentProvider, ILazyTreePathContentProvider { private TreeViewer viewer; @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { this.viewer = (TreeViewer) viewer; } @Override public void dispose() { for ( Image img : imageCache.values() ) { img.dispose(); } } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ITreePathContentProvider#getParents(java * .lang.Object) */ @Override public TreePath[] getParents(Object element) { return null; } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ILazyTreePathContentProvider#updateElement * (org.eclipse.jface.viewers.TreePath, int) */ @Override public void updateElement(TreePath parentPath, int index) { cacheChildren(parentPath); Object[] childNodes = children.get(parentPath); if ( index >= childNodes.length ) return; viewer.replace(parentPath, index, childNodes[index]); updateHasChildren(parentPath.createChildPath(childNodes[index])); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ILazyTreePathContentProvider#updateChildCount * (org.eclipse.jface.viewers.TreePath, int) */ @Override public void updateChildCount(TreePath treePath, int currentChildCount) { cacheChildren(treePath); Object[] objects = children.get(treePath); viewer.setChildCount(treePath, objects.length); for ( int i = 0; i < objects.length; i++ ) { if ( objects[i] instanceof IPath ) { viewer.setHasChildren(treePath.createChildPath(objects[i]), true); } } return; } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ILazyTreePathContentProvider#updateHasChildren * (org.eclipse.jface.viewers.TreePath) */ @Override public void updateHasChildren(TreePath path) { viewer.setHasChildren(path, path.getSegmentCount() > 0 && path.getLastSegment() instanceof IPath); } /* * Non-virtual tree content provider implementation below */ /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ITreePathContentProvider#getElements(java * .lang.Object) */ @SuppressWarnings("unused") public Object[] getElements(Object inputElement) { TreePath treePath = new TreePath(new Object[0]); cacheChildren(treePath); return children.get(treePath); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ITreePathContentProvider#getChildren(org * .eclipse.jface.viewers.TreePath) */ @SuppressWarnings("unused") public Object[] getChildren(TreePath parentPath) { cacheChildren(parentPath); return children.get(parentPath); } /* * (non-Javadoc) * * @see * org.eclipse.jface.viewers.ITreePathContentProvider#hasChildren(org * .eclipse.jface.viewers.TreePath) */ @SuppressWarnings("unused") public boolean hasChildren(TreePath path) { return path.getLastSegment() instanceof IPath; } } private final class S3ObjectSummaryLabelProvider implements ITableLabelProvider { @Override public void removeListener(ILabelProviderListener listener) { } @Override public boolean isLabelProperty(Object element, String property) { return true; } @Override public void dispose() { } @Override public void addListener(ILabelProviderListener listener) { } @Override public String getColumnText(Object element, int columnIndex) { if ( element == LOADING ) { return "Loading..."; } else if ( element instanceof IPath ) { if ( columnIndex == 0 ) return ((IPath) element).lastSegment(); else return ""; } S3ObjectSummary s = (S3ObjectSummary) element; switch (columnIndex) { case KEY_COL: int index = s.getKey().lastIndexOf(DEFAULT_DELIMITER); if ( index > 0 ) { return s.getKey().substring(index + 1); } else { return s.getKey(); } case ETAG_COL: return s.getETag(); case OWNER_COL: return s.getOwner().getDisplayName(); case SIZE_COL: return "" + s.getSize(); case STORAGE_CLASS_COL: return s.getStorageClass(); case LAST_MODIFIED_COL: return s.getLastModified().toString(); } return ""; } @Override public Image getColumnImage(Object element, int columnIndex) { if ( columnIndex == 0 && element != LOADING ) { if ( element instanceof IPath ) { return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER); } S3ObjectSummary s = (S3ObjectSummary) element; return getCachedImage(PlatformUI.getWorkbench().getEditorRegistry().getImageDescriptor(s.getKey())); } return null; } public Image getCachedImage(ImageDescriptor img) { if ( !imageCache.containsKey(img) ) { imageCache.put(img, img.createImage()); } return imageCache.get(img); } } public S3ObjectSummaryTable(String accountId, String bucketName, String s3Endpoint, Composite composite, FormToolkit toolkit, int style) { super(composite, style); this.accountId = accountId; this.regionId = RegionUtils.getRegionByEndpoint(s3Endpoint).getId(); this.bucketName = bucketName; this.children = Collections.synchronizedMap(new HashMap<TreePath, Object[]>()); GridLayout gridLayout = new GridLayout(1, false); gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; setLayout(gridLayout); Composite sectionComp = toolkit.createComposite(this, SWT.None); sectionComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); sectionComp.setLayout(new GridLayout(1, false)); Composite headingComp = toolkit.createComposite(sectionComp, SWT.None); headingComp.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); headingComp.setLayout(new GridLayout()); Label label = toolkit.createLabel(headingComp, "Object listing: drag and drop local files to the table view to upload to S3 bucket"); label.setFont(JFaceResources.getHeaderFont()); label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); Composite tableHolder = toolkit.createComposite(sectionComp, SWT.None); tableHolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); FillLayout layout = new FillLayout(); layout.marginHeight = 0; layout.marginWidth = 10; layout.type = SWT.VERTICAL; tableHolder.setLayout(layout); Composite tableComp = toolkit.createComposite(tableHolder, SWT.None); TreeColumnLayout tableColumnLayout = new TreeColumnLayout(); tableComp.setLayout(tableColumnLayout); viewer = new TreeViewer(tableComp, SWT.BORDER | SWT.VIRTUAL | SWT.MULTI); viewer.getTree().setLinesVisible(true); viewer.getTree().setHeaderVisible(true); viewer.setUseHashlookup(true); viewer.setLabelProvider(new S3ObjectSummaryLabelProvider()); viewer.setContentProvider(new S3ObjectSummaryContentProvider()); Tree tree = viewer.getTree(); createColumns(tableColumnLayout, tree); initializeDragAndDrop(); final TreePath rootPath = new TreePath(new Object[0]); final Thread t = cacheChildren(rootPath); viewer.setInput(LOADING); new Thread() { @Override public void run() { try { t.join(); } catch ( InterruptedException e1 ) { return; } Display.getDefault().syncExec(new Runnable() { @Override public void run() { // Preserve the current column widths int[] colWidth = new int[viewer.getTree().getColumns().length]; int i = 0; for ( TreeColumn col : viewer.getTree().getColumns() ) { colWidth[i++] = col.getWidth(); } viewer.setInput(LOADING_DONE); i = 0; for ( TreeColumn col : viewer.getTree().getColumns() ) { col.setWidth(colWidth[i++]); } } }); } }.start(); hookContextMenu(); } protected void initializeDragAndDrop() { DragSource dragSource = new DragSource(viewer.getTree(), DND.DROP_COPY | DND.DROP_DEFAULT | DND.DROP_MOVE); dragSource.setTransfer(new Transfer[] { PluginTransfer.getInstance() }); dragSource.addDragListener(new DragSourceAdapter() { @Override public void dragStart(DragSourceEvent event) { event.doit = false; ISelection selection = viewer.getSelection(); if ( selection instanceof IStructuredSelection ) { if ( ((IStructuredSelection) selection).size() == 1 && ((IStructuredSelection) selection).getFirstElement() instanceof S3ObjectSummary ) { event.doit = true; } } } @Override public void dragSetData(DragSourceEvent event) { Object o = ((ITreeSelection) viewer.getSelection()).getFirstElement(); if ( o instanceof S3ObjectSummary ) { S3ObjectSummary s = (S3ObjectSummary) o; event.data = new PluginTransferData(S3ObjectSummaryDropAction.ID, S3ObjectSummaryDropAction .encode(s)); } else { event.doit = false; } } }); DropTarget dropTarget = new DropTarget(viewer.getTree(), DND.DROP_COPY | DND.DROP_DEFAULT | DND.DROP_MOVE); dropTarget.setTransfer(new Transfer[] { LocalSelectionTransfer.getTransfer(), FileTransfer.getInstance() }); dropTarget.addDropListener(new DropTargetAdapter() { @Override public void drop(DropTargetEvent event) { File[] files = UploadDropAssistant.getFileToDrop(event.currentDataType); if (files == null || files.length == 0) { return; } String prefix = ""; if ( event.item instanceof TreeItem ) { TreeItem item = (TreeItem) event.item; if ( item.getData() instanceof IPath ) { IPath path = (IPath) item.getData(); prefix = path.toString(); } } final TransferManager transferManager = new TransferManager(getS3Client()); UploadFilesJob uploadFileJob = new UploadFilesJob(String.format("Upload files to bucket %s", bucketName), bucketName, files, transferManager); uploadFileJob.setRefreshRunnable(new Runnable() { @Override public void run() { refresh(null); } }); uploadFileJob.schedule(); } }); } public synchronized AmazonS3 getS3Client() { return AwsToolkitCore.getClientFactory(accountId).getS3ClientByRegion(regionId); } protected void createColumns(TreeColumnLayout tableColumnLayout, Tree tree) { TreeColumn column = new TreeColumn(tree, SWT.NONE); column.setText("Key"); ColumnWeightData cwd_column = new ColumnWeightData(30); cwd_column.minimumWidth = 1; tableColumnLayout.setColumnData(column, cwd_column); TreeColumn column_1 = new TreeColumn(tree, SWT.NONE); column_1.setMoveable(true); column_1.setText("E-tag"); tableColumnLayout.setColumnData(column_1, new ColumnWeightData(15)); TreeColumn column_2 = new TreeColumn(tree, SWT.NONE); column_2.setMoveable(true); column_2.setText("Owner"); tableColumnLayout.setColumnData(column_2, new ColumnWeightData(15)); TreeColumn column_3 = new TreeColumn(tree, SWT.NONE); column_3.setMoveable(true); column_3.setText("Size"); tableColumnLayout.setColumnData(column_3, new ColumnWeightData(15)); TreeColumn column_4 = new TreeColumn(tree, SWT.NONE); column_4.setMoveable(true); column_4.setText("Storage class"); tableColumnLayout.setColumnData(column_4, new ColumnWeightData(10)); TreeColumn column_5 = new TreeColumn(tree, SWT.NONE); column_5.setMoveable(true); column_5.setText("Last modified"); tableColumnLayout.setColumnData(column_5, new ColumnWeightData(15)); } /** * Fills in the children for the tree path given, which must either be empty * or end in a File object. */ protected Thread cacheChildren(final TreePath treePath) { if ( children.containsKey(treePath) ) return null; children.put(treePath, new Object[] { LOADING }); Thread thread = new Thread() { @Override public void run() { String prefix; if ( treePath.getSegmentCount() == 0 ) { prefix = ""; } else { prefix = ((IPath) treePath.getLastSegment()).toString(); } List<S3ObjectSummary> filteredObjectSummaries = new LinkedList<>(); List<String> filteredCommonPrefixes = new LinkedList<>(); ObjectListing listObjectsResponse = null; AmazonS3 s3 = getS3Client(); do { if (listObjectsResponse == null) { ListObjectsRequest listObjectsRequest = new ListObjectsRequest() .withBucketName(S3ObjectSummaryTable.this.bucketName) .withDelimiter(DEFAULT_DELIMITER) .withPrefix(prefix); listObjectsResponse = s3.listObjects(listObjectsRequest); } else { listObjectsResponse = s3.listNextBatchOfObjects(listObjectsResponse); } for ( S3ObjectSummary s : listObjectsResponse.getObjectSummaries() ) { if ( !s.getKey().equals(prefix) ) { filteredObjectSummaries.add(s); } } filteredCommonPrefixes.addAll(listObjectsResponse.getCommonPrefixes()); } while (listObjectsResponse.isTruncated()); final Object[] objects = new Object[filteredObjectSummaries.size() + filteredCommonPrefixes.size()]; filteredObjectSummaries.toArray(objects); int i = filteredObjectSummaries.size(); for ( String commonPrefix : filteredCommonPrefixes ) { objects[i++] = new Path(null, commonPrefix); } children.put(treePath, objects); viewer.getTree().getDisplay().syncExec(new Runnable() { @Override public void run() { if ( treePath.getSegmentCount() == 0 ) viewer.setChildCount(treePath, objects.length); viewer.refresh(); } }); } }; thread.start(); return thread; } /** * Hooks a context menu for the table control. */ private void hookContextMenu() { MenuManager menuMgr = new MenuManager("#PopupMenu"); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { manager.add(new DeleteObjectAction(S3ObjectSummaryTable.this)); manager.add(new Separator()); manager.add(new EditObjectPermissionsAction(S3ObjectSummaryTable.this)); manager.add(new EditObjectTagsAction(S3ObjectSummaryTable.this)); manager.add(new Separator()); manager.add(new GeneratePresignedUrlAction(S3ObjectSummaryTable.this)); } }); Menu menu = menuMgr.createContextMenu(viewer.getControl()); viewer.getControl().setMenu(menu); menuMgr.createContextMenu(this); } /** * Returns all selected S3 summaries in the table. */ public Collection<S3ObjectSummary> getSelectedObjects() { IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); List<S3ObjectSummary> summaries = new LinkedList<>(); Iterator<?> iter = s.iterator(); while ( iter.hasNext() ) { Object next = iter.next(); if ( next instanceof S3ObjectSummary ) summaries.add((S3ObjectSummary) next); } return summaries; } /** * Refreshes the table, optionally at at given root. */ public void refresh(String prefix) { if ( prefix == null ) { children.clear(); viewer.refresh(); } else { List<IPath> paths = new LinkedList<>(); IPath p = new Path(""); for ( String dir : prefix.split("/") ) { p = p.append(dir + "/"); paths.add(p); } TreePath treePath = new TreePath(paths.toArray()); children.remove(treePath); viewer.refresh(new Path(prefix)); } } }
7,779
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/util/ObjectUtils.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.util; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.S3VersionSummary; import com.amazonaws.services.s3.model.VersionListing; /** * Utilities for common Amazon S3 object operations. */ public class ObjectUtils { /** * Deletes an object along with all object versions, if any exist. */ public void deleteObjectAndAllVersions(String bucketName, String key) { AmazonS3 s3 = AwsToolkitCore.getClientFactory().getS3ClientForBucket(bucketName); VersionListing versionListing = null; do { if (versionListing == null) { versionListing = s3.listVersions(bucketName, key); } else { versionListing = s3.listNextBatchOfVersions(versionListing); } for (S3VersionSummary versionSummary : versionListing.getVersionSummaries()) { s3.deleteVersion(bucketName, key, versionSummary.getVersionId()); } } while (versionListing.isTruncated()); } /** * Deletes a bucket along with all contained objects and any object versions if they exist. */ public void deleteBucketAndAllVersions(String bucketName) { AmazonS3 s3 = AwsToolkitCore.getClientFactory().getS3ClientForBucket(bucketName); VersionListing versionListing = null; do { if (versionListing == null) { versionListing = s3.listVersions(bucketName, null); } else { versionListing = s3.listNextBatchOfVersions(versionListing); } for (S3VersionSummary versionSummary : versionListing.getVersionSummaries()) { s3.deleteVersion(bucketName, versionSummary.getKey(), versionSummary.getVersionId()); } } while (versionListing.isTruncated()); s3.deleteBucket(bucketName); } }
7,780
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/acls/EditBucketPermissionsDialog.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.acls; import java.util.ArrayList; import java.util.List; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.AccessControlList; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.Permission; /** * Dialog for editing an Amazon S3 bucket ACL. */ public class EditBucketPermissionsDialog extends EditPermissionsDialog { private Bucket bucket; public EditBucketPermissionsDialog(Bucket bucket) { this.bucket = bucket; } @Override protected String getShellTitle() { return "Edit Bucket Permissions"; } @Override protected List<PermissionOption> getPermissionOptions() { List<PermissionOption> list = new ArrayList<>(); list.add(new PermissionOption(Permission.Read, "List Contents")); list.add(new PermissionOption(Permission.Write, "Edit Contents")); list.add(new PermissionOption(Permission.ReadAcp, "Read ACL")); list.add(new PermissionOption(Permission.WriteAcp, "Write ACL")); return list; } @Override protected AccessControlList getAcl() { AmazonS3 s3 = AwsToolkitCore.getClientFactory().getS3ClientForBucket(bucket.getName()); return s3.getBucketAcl(bucket.getName()); } }
7,781
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/acls/EditObjectPermissionsDialog.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.acls; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.AccessControlList; import com.amazonaws.services.s3.model.Permission; import com.amazonaws.services.s3.model.S3ObjectSummary; /** * Dialog for editing an Amazon S3 object ACL. */ public class EditObjectPermissionsDialog extends EditPermissionsDialog { private Collection<S3ObjectSummary> objects; public EditObjectPermissionsDialog(Collection<S3ObjectSummary> objects) { super(); this.objects = objects; } @Override protected List<PermissionOption> getPermissionOptions() { List<PermissionOption> list = new ArrayList<>(); list.add(new PermissionOption(Permission.Read, "Read Data")); list.add(new PermissionOption(Permission.ReadAcp, "Read ACL")); list.add(new PermissionOption(Permission.WriteAcp, "Write ACL")); return list; } @Override protected String getShellTitle() { return "Edit Object Permissions"; } @Override protected AccessControlList getAcl() { S3ObjectSummary firstObject = objects.iterator().next(); String bucket = objects.iterator().next().getBucketName(); AmazonS3 s3 = AwsToolkitCore.getClientFactory().getS3ClientForBucket(bucket); return s3.getObjectAcl(firstObject.getBucketName(), firstObject.getKey()); } }
7,782
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/acls/EditPermissionsDialog.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.acls; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.s3.model.AccessControlList; import com.amazonaws.services.s3.model.CanonicalGrantee; import com.amazonaws.services.s3.model.EmailAddressGrantee; import com.amazonaws.services.s3.model.Grant; import com.amazonaws.services.s3.model.Grantee; import com.amazonaws.services.s3.model.GroupGrantee; import com.amazonaws.services.s3.model.Owner; import com.amazonaws.services.s3.model.Permission; /** * Abstract base class providing the framework for object and bucket ACL editing UIs. */ public abstract class EditPermissionsDialog extends Dialog { private Table table; private AccessControlList acl; protected EditPermissionsDialog() { super(Display.getDefault().getActiveShell()); setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.APPLICATION_MODAL); } /** * Returns the title to set for the dialog shell. * * @return the title to set for the dialog shell. */ protected abstract String getShellTitle(); /** * Returns a list of PermissionOption objects that describe which S3 * Permissions are applicable for the specific UI provided by a subclass. * * @return a list of PermissionOption objects that describe which S3 * Permissions are applicable for the specific UI provided by a * subclass. */ protected abstract List<PermissionOption> getPermissionOptions(); /** * Returns the S3 ACL to use when initializing the dialog's UI. * * @return the S3 ACL to use when initializing the dialog's UI. */ protected abstract AccessControlList getAcl(); @Override public void create() { super.create(); getShell().setText(getShellTitle()); } @Override protected Control createDialogArea(final Composite parent) { parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); final Composite composite = new Composite(parent, SWT.BORDER); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); composite.setLayout(new GridLayout()); createPermissionsTable(composite); Composite buttonComposite = new Composite(composite, SWT.NONE); GridLayout buttonCompositeLayout = new GridLayout(2, true); buttonCompositeLayout.horizontalSpacing = 0; buttonCompositeLayout.marginLeft = 0; buttonCompositeLayout.marginWidth = 0; buttonCompositeLayout.marginHeight = 0; buttonComposite.setLayout(buttonCompositeLayout); buttonComposite.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false)); Button addButton = new Button(buttonComposite, SWT.PUSH); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); addButton.setLayoutData(gridData); addButton.setText("Add Grant"); addButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD)); addButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { createTableItem(true); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); Button removeButton = new Button(buttonComposite, SWT.PUSH); removeButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); removeButton.setText("Remove Grants"); removeButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_REMOVE)); removeButton.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { List<Integer> selectionIndices = new ArrayList<>(); for (int selectionIndex : table.getSelectionIndices()) { // Skip the first two rows with group permissions if (selectionIndex < 2) continue; selectionIndices.add(selectionIndex); TableItem item = table.getItem(selectionIndex); TableItemData data = (TableItemData)item.getData(); for (Button button : data.checkboxes) button.dispose(); if (data.granteeTextbox != null) data.granteeTextbox.dispose(); } int[] indiciesToRemove = new int[selectionIndices.size()]; for (int i = 0; i < selectionIndices.size(); i++) { indiciesToRemove[i] = selectionIndices.get(i); } table.remove(indiciesToRemove); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); displayPermissions(); return composite; } public AccessControlList getAccessControlList() { return acl; } @Override public boolean close() { acl = new AccessControlList(); acl.setOwner((Owner)table.getData("owner")); Set<Grant> grants = acl.getGrants(); for (TableItem item : table.getItems()) { TableItemData data = (TableItemData)item.getData(); Grantee grantee = data.grantee; for (Button checkbox : data.checkboxes) { if (checkbox.getSelection()) { Permission permission = (Permission)checkbox.getData(); grants.add(new Grant(grantee, permission)); } } } /* * TODO: We might want to run the S3 setAcl call here in case it * fails with some correctable error, like a non-unique email * address grantee, uknown id, etc. */ return super.close(); } private void createPermissionsTable(Composite composite) { table = new Table(composite, SWT.BORDER | SWT.MULTI); table.setLinesVisible(true); table.setHeaderVisible(true); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true); layoutData.minimumHeight = 125; table.setLayoutData(layoutData); TableColumn granteeColumn = new TableColumn(table, SWT.NONE); granteeColumn.setWidth(250); granteeColumn.setText("Grantee"); for (PermissionOption permissionOption : getPermissionOptions()) { TableColumn readDataPermissionColumn = new TableColumn(table, SWT.CENTER); readDataPermissionColumn.setWidth(75); readDataPermissionColumn.setText(permissionOption.header); } table.addListener(SWT.MeasureItem, new Listener() { private Point preferredSize; @Override public void handleEvent(Event event) { if (preferredSize == null) { Text text = new Text(table, SWT.BORDER); preferredSize = text.computeSize(SWT.DEFAULT, SWT.DEFAULT); text.dispose(); } event.height = preferredSize.y; } }); table.layout(); } static class PermissionOption { Permission permission; String header; PermissionOption(Permission permission, String header) { this.permission = permission; this.header = header; } } private TableItem createTableItem(boolean withTextEditor) { final TableItem item = new TableItem(table, SWT.NONE); final TableItemData data = new TableItemData(); item.setData(data); if (withTextEditor) { TableEditor editor = new TableEditor(table); final Text granteeText = new Text(table, SWT.BORDER); data.granteeTextbox = granteeText; granteeText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { String grantee = granteeText.getText(); if (grantee.contains("@")) { data.grantee = new EmailAddressGrantee(grantee); } else { data.grantee = new CanonicalGrantee(grantee); } } }); granteeText.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) {} @Override public void focusGained(FocusEvent e) { table.setSelection(item); } }); granteeText.setFocus(); editor.grabHorizontal = true; editor.setEditor(granteeText, item, 0); } int column = 1; for (PermissionOption permissionOption : getPermissionOptions()) { TableEditor editor = new TableEditor(table); final Button checkbox = new Button(table, SWT.CHECK); checkbox.setData(permissionOption.permission); Point checkboxSize = checkbox.computeSize(SWT.DEFAULT, table.getItemHeight()); editor.minimumWidth = checkboxSize.x; editor.minimumHeight = checkboxSize.y; editor.setEditor(checkbox, item, column++); data.checkboxes.add(checkbox); } return item; } private void displayPermissions() { AccessControlList startingAcl = getAcl(); table.clearAll(); table.setData("owner", startingAcl.getOwner()); Map<Grantee, Set<Permission>> permissionsByGrantee = new TreeMap<>(new GranteeComparator()); permissionsByGrantee.put(GroupGrantee.AllUsers, new HashSet<Permission>()); permissionsByGrantee.put(GroupGrantee.AuthenticatedUsers, new HashSet<Permission>()); for (Grant grant : startingAcl.getGrants()) { if (permissionsByGrantee.get(grant.getGrantee()) == null) { permissionsByGrantee.put(grant.getGrantee(), new HashSet<Permission>()); } Set<Permission> permissions = permissionsByGrantee.get(grant.getGrantee()); permissions.add(grant.getPermission()); } for (Grantee grantee : permissionsByGrantee.keySet()) { Set<Permission> permissions = permissionsByGrantee.get(grantee); TableItem item = createTableItem(false); TableItemData data = (TableItemData)item.getData(); data.grantee = grantee; item.setText(new String[] {getGranteeDisplayName(grantee), "", ""}); if (permissions.contains(Permission.FullControl)) { for (Button checkbox : data.checkboxes) { checkbox.setSelection(true); } } for (Button checkbox : data.checkboxes) { Permission permission = (Permission)checkbox.getData(); if (permissions.contains(permission)) { checkbox.setSelection(true); } } } } private String getGranteeDisplayName(Grantee grantee) { if (grantee instanceof CanonicalGrantee) { CanonicalGrantee canonicalGrantee = (CanonicalGrantee)grantee; if (canonicalGrantee.getDisplayName() != null) { return canonicalGrantee.getDisplayName(); } } if (grantee instanceof GroupGrantee) { switch ((GroupGrantee)grantee) { case AllUsers: return "All Users"; case AuthenticatedUsers: return "Authenticated Users"; case LogDelivery: return "Log Delivery"; } } return grantee.getIdentifier(); } static class TableItemData { Grantee grantee; List<Button> checkboxes = new ArrayList<>(); Text granteeTextbox; } }
7,783
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/acls/GranteeComparator.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.acls; import java.util.Comparator; import com.amazonaws.services.s3.model.Grantee; import com.amazonaws.services.s3.model.GroupGrantee; /** * Comparator implementation that sorts Amazon S3 Grantee objects. Group * Grantees are ordered first (starting with All Users, then Authenticated * Users), and any non-group Grantees are sorted by ID. */ final class GranteeComparator implements Comparator<Grantee> { @Override public int compare(Grantee g1, Grantee g2) { if (g1.getIdentifier().equals(g2.getIdentifier())) return 0; if (g1 instanceof GroupGrantee) { // List groups first if (g2 instanceof GroupGrantee == false) return -1; GroupGrantee gg1 = (GroupGrantee)g1; if (gg1 == GroupGrantee.AllUsers) return -1; } if (g2 instanceof GroupGrantee) { // List groups first if (g1 instanceof GroupGrantee == false) return 1; GroupGrantee gg2 = (GroupGrantee)g2; if (gg2 == GroupGrantee.AllUsers) return 1; } return g1.getIdentifier().compareTo(g2.getIdentifier()); } }
7,784
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/dnd/UploadFilesJob.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.dnd; import java.io.File; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.event.ProgressEvent; import com.amazonaws.event.ProgressEventType; import com.amazonaws.event.ProgressListener; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.Upload; /** * Background job to upload files to S3 */ public class UploadFilesJob extends Job { private final String bucketName; private final File[] filesToUpload; private final TransferManager transferManager; private Runnable refreshRunnable; public Runnable getRefreshRunnable() { return refreshRunnable; } /** * Sets a runnable to refresh a UI element after the upload has been * complete. */ public void setRefreshRunnable(Runnable refreshRunnable) { this.refreshRunnable = refreshRunnable; } public UploadFilesJob(String name, String bucketName, File[] toUpload, TransferManager transferManager) { super(name); this.bucketName = bucketName; this.filesToUpload = toUpload; this.transferManager = transferManager; this.setUser(true); } @Override protected IStatus run(IProgressMonitor monitor) { List<KeyFilePair> pairSet = getActualFilesToUpload(); int totalFilesToUpload = pairSet.size(); monitor.beginTask(String.format("Uploading %d files to Amazon S3!", totalFilesToUpload), 100 * totalFilesToUpload); List<IStatus> errorStatuses = new ArrayList<>(); int uploadedFiles = 0; for (KeyFilePair pair : pairSet) { String name = pair.keyName; monitor.setTaskName(String.format("%d/%d uploaded! Uploading %s!", uploadedFiles++, totalFilesToUpload, name)); doUpload(name, pair.file, errorStatuses, monitor); } monitor.done(); if (!errorStatuses.isEmpty()) { String errorMessages = aggregateErrorMessages(errorStatuses); AwsToolkitCore.getDefault().reportException(errorMessages, null); } return Status.OK_STATUS; } private String aggregateErrorMessages(List<IStatus> statuses) { StringBuilder builder = new StringBuilder(); for (IStatus status : statuses) { builder.append(status.getMessage() + "\n"); } return builder.toString(); } private List<KeyFilePair> getActualFilesToUpload() { List<KeyFilePair> pairSet = new ArrayList<>(); for (File file : filesToUpload) { putFilesToList(null, file, pairSet); } return pairSet; } private void putFilesToList(String prefix, File file, List<KeyFilePair> pairSet) { String keyName = prefix == null ? file.getName() : prefix + "/" + file.getName(); if (file.exists() && file.isFile()) { pairSet.add(new KeyFilePair(keyName, file)); } else if (file.isDirectory()) { File[] files = file.listFiles(); for (File subFile : files) { putFilesToList(keyName, subFile, pairSet); } } } private void doUpload(final String keyName, final File file, List<IStatus> statuses, final IProgressMonitor monitor) { final Upload upload = transferManager.upload(bucketName, keyName, file); upload.addProgressListener(new ProgressListener(){ private final long totalBytes = file.length(); private long transferredBytes = 0; private int percentTransferred = 0; @Override public void progressChanged(ProgressEvent event) { ProgressEventType type = event.getEventType(); if (type == ProgressEventType.REQUEST_BYTE_TRANSFER_EVENT) { transferredBytes += event.getBytesTransferred(); int progress = Math.min((int) (100 * transferredBytes / totalBytes), 100); if (progress <= percentTransferred) { return; } monitor.worked(progress - percentTransferred); percentTransferred = progress; } else if (type == ProgressEventType.TRANSFER_COMPLETED_EVENT || type == ProgressEventType.TRANSFER_CANCELED_EVENT || type == ProgressEventType.TRANSFER_FAILED_EVENT) { if (percentTransferred < 100) { monitor.worked(100 - percentTransferred); } } } }); try { upload.waitForCompletion(); } catch (Exception e) { statuses.add(new Status(IStatus.ERROR, AwsToolkitCore.getDefault().getPluginId(), String.format("Error uploading %s: %s", keyName, e.getMessage()))); } if ( getRefreshRunnable() != null ) { Display.getDefault().syncExec(getRefreshRunnable()); } } private static class KeyFilePair { String keyName; File file; public KeyFilePair(String keyName, File file) { this.keyName = keyName; this.file = file; } } }
7,785
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/dnd/UploadDropAssistant.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.dnd; import java.io.File; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.util.LocalSelectionTransfer; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.TransferData; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.navigator.CommonDropAdapter; import org.eclipse.ui.navigator.CommonDropAdapterAssistant; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.explorer.s3.BucketEditor; import com.amazonaws.eclipse.explorer.s3.BucketEditorInput; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.transfer.TransferManager; /** * Handles dropping a resource into a bucket, uploading it. */ public class UploadDropAssistant extends CommonDropAdapterAssistant { public UploadDropAssistant() { } @Override public IStatus validateDrop(final Object target, final int operation, final TransferData transferType) { if ( target instanceof Bucket ) { return Status.OK_STATUS; } else { return Status.CANCEL_STATUS; } } @Override public boolean isSupportedType(TransferData aTransferType) { return LocalSelectionTransfer.getTransfer().isSupportedType(aTransferType) || FileTransfer.getInstance().isSupportedType(aTransferType); } @Override public IStatus handleDrop(CommonDropAdapter aDropAdapter, final DropTargetEvent aDropTargetEvent, Object aTarget) { final Bucket bucket = (Bucket) aTarget; File[] filesToUpload = getFileToDrop(aDropAdapter.getCurrentTransfer()); if (filesToUpload == null || filesToUpload.length == 0) return Status.CANCEL_STATUS; final TransferManager transferManager = new TransferManager(AwsToolkitCore.getClientFactory().getS3ClientForBucket(bucket.getName())); UploadFilesJob uploadFileJob = new UploadFilesJob(String.format("Upload files to bucket %s", bucket.getName()), bucket.getName(), filesToUpload, transferManager); uploadFileJob.setRefreshRunnable(new Runnable() { @Override public void run() { try { for ( IEditorReference ref : PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage().getEditorReferences() ) { if ( ref.getEditorInput() instanceof BucketEditorInput ) { if ( bucket.getName() .equals(((BucketEditorInput) ref.getEditorInput()).getBucketName()) ) { BucketEditor editor = (BucketEditor) ref.getEditor(false); editor.getObjectSummaryTable().refresh(null); return; } } } } catch ( PartInitException e ) { AwsToolkitCore.getDefault().logError("Unable to open the Amazon S3 bucket editor: ", e); } } }); uploadFileJob.schedule(); return Status.OK_STATUS; } public static File[] getFileToDrop(TransferData transfer) { if ( LocalSelectionTransfer.getTransfer().isSupportedType(transfer) ) { IStructuredSelection selection = (IStructuredSelection) LocalSelectionTransfer.getTransfer().nativeToJava( transfer); IResource resource = (IResource) selection.getFirstElement(); return new File[] {resource.getLocation().toFile()}; } else if ( FileTransfer.getInstance().isSupportedType(transfer) ) { String[] files = (String[]) FileTransfer.getInstance().nativeToJava(transfer); File[] filesToDrop = new File[files.length]; for (int i = 0; i < files.length; ++i) { filesToDrop[i] = new File(files[i]); } return filesToDrop; } return null; } }
7,786
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/dnd/S3ObjectSummaryDropAction.java
package com.amazonaws.eclipse.explorer.s3.dnd; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.RandomAccessFile; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.part.IDropActionDelegate; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectSummary; public class S3ObjectSummaryDropAction implements IDropActionDelegate { public static final String ID = "com.amazonaws.eclipse.explorer.s3.objectSummaryDropAction"; @Override public boolean run(Object source, Object target) { BucketAndKey bk = new BucketAndKey((byte[]) source); IContainer dropFolder; if ( target instanceof IContainer ) { dropFolder = (IContainer) target; } else if ( target instanceof IFile ) { dropFolder = ((IFile) target).getParent(); } else if ( target instanceof IJavaProject ) { dropFolder = ((IJavaProject) target).getProject(); } else if ( target instanceof IJavaElement ) { IJavaElement j = (IJavaElement) target; try { return run(source, j.getUnderlyingResource()); } catch ( JavaModelException e ) { AwsToolkitCore.getDefault().logError("Couldn't determine java resource", e); return false; } } else { return false; } final File f = dropFolder.getLocation().toFile(); if ( !f.exists() ) return false; String fileName = getOutputFileName(bk.key, f); if ( fileName == null || fileName.length() == 0 ) { return false; } final File outputFile = new File(fileName); new DownloadObjectJob("Downloading " + bk.key, bk.bucket, bk.key, dropFolder, outputFile).schedule(); return true; } /** * Opens a save-file dialog to prompt the user for a file name. */ private String getOutputFileName(final String key, final File f) { FileDialog dialog = new FileDialog(Display.getDefault().getActiveShell(), SWT.SAVE); dialog.setFilterPath(f.getAbsolutePath()); String keyToDisplay = key; if ( keyToDisplay.contains("/") ) { keyToDisplay = keyToDisplay.substring(keyToDisplay.lastIndexOf('/') + 1); } dialog.setFileName(keyToDisplay); dialog.setOverwrite(true); String fileName = dialog.open(); return fileName; } private final class DownloadObjectJob extends Job { private final String key; private final String bucket; private final IResource dropFolder; private final File outputFile; private DownloadObjectJob(String name, String bucket, String key, IContainer dropFolder, File outputFile) { super(name); this.bucket = bucket; this.key = key; this.dropFolder = dropFolder; this.outputFile = outputFile; } @Override protected IStatus run(final IProgressMonitor monitor) { FileOutputStream fos = null; try { // TODO: this won't work if the current account doesn't have read permission for the bucket and key AmazonS3 client = AwsToolkitCore.getClientFactory().getS3ClientForBucket(bucket); S3Object object = client.getObject(bucket, key); // This number is used for reporting only; the download // will appear to complete early if the file is bigger // than 2GB. long totalNumBytes = object.getObjectMetadata().getContentLength(); if ( totalNumBytes > Integer.MAX_VALUE ) totalNumBytes = Integer.MAX_VALUE; monitor.beginTask("Downloading", (int) totalNumBytes); // For a new file this is a no-op, but it truncates an // existing file for overwrite. try (RandomAccessFile raf = new RandomAccessFile(outputFile, "rw")) { raf.setLength(0); } fos = new FileOutputStream(outputFile); InputStream is = object.getObjectContent(); byte[] buffer = new byte[4096]; int bytesRead = 0; while ( (bytesRead = is.read(buffer)) > 0 ) { fos.write(buffer, 0, bytesRead); monitor.worked(bytesRead); } } catch ( Exception e ) { return new Status(Status.ERROR, AwsToolkitCore.getDefault().getPluginId(), "Error downloading file from S3", e); } finally { if ( fos != null ) { try { fos.close(); } catch ( Exception e ) { AwsToolkitCore.getDefault().logError("Couldn't close file output stream", e); } } monitor.done(); } // Refresh the drop folder // TODO: this won't work if they chose another folder in the // file selection dialog. Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { dropFolder.refreshLocal(1, monitor); } catch ( CoreException e ) { AwsToolkitCore.getDefault().logError("Couldn't refresh local files", e); } } }); return Status.OK_STATUS; } } /** * Encodes the object summary as a byte array. */ public static byte[] encode(S3ObjectSummary s) { return BucketAndKey.encode(s); } static private class BucketAndKey { private String bucket; private String key; public static byte[] encode(S3ObjectSummary s) { StringBuilder b = new StringBuilder(); b.append(s.getBucketName()).append('\t').append(s.getKey()); return b.toString().getBytes(); } public BucketAndKey(byte[] data) { String s = new String(data); int index = s.indexOf('\t'); if ( index < 0 ) throw new RuntimeException("Unable to decode bucket and key"); bucket = s.substring(0, index); key = s.substring(index + 1); } } }
7,787
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/dnd/KeySelectionDialog.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.dnd; import java.io.File; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AwsToolkitCore; public class KeySelectionDialog extends MessageDialog { String keyName; public KeySelectionDialog(Shell shell, File toUpload) { this(shell, "", toUpload); } public KeySelectionDialog(Shell shell, String prefix, File toUpload) { super(shell, "Choose a key name", AwsToolkitCore.getDefault() .getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON), "Enter a key to upload the file", 0, new String[] { "OK", "Cancel" }, 0); this.keyName = prefix + toUpload.getName(); } @Override protected Control createCustomArea(Composite parent) { final Text text = new Text(parent, SWT.BORDER); text.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); text.setText(keyName); text.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { keyName = text.getText(); } }); return parent; } public String getKeyName() { return keyName; } }
7,788
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/dnd/DownloadDropAssistant.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.dnd; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.RandomAccessFile; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.util.LocalSelectionTransfer; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.TransferData; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.navigator.CommonDropAdapter; import org.eclipse.ui.navigator.CommonDropAdapterAssistant; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectSummary; /** * Handles dropping an S3 key onto a supported resource in the project explorer. */ public class DownloadDropAssistant extends CommonDropAdapterAssistant { public DownloadDropAssistant() { } /** * All validation is left to the configuration in plugin.xml. Any match * between possibleChildren and possibleDropTargets will be considered * valid. */ @Override public IStatus validateDrop(Object target, int operation, TransferData transferType) { return validatePluginTransferDrop((IStructuredSelection) LocalSelectionTransfer.getTransfer().getSelection(), target); } @Override public IStatus validatePluginTransferDrop(IStructuredSelection aDragSelection, Object aDropTarget) { if (aDropTarget instanceof IResource) return Status.OK_STATUS; else return Status.CANCEL_STATUS; } @Override public IStatus handlePluginTransferDrop(IStructuredSelection aDragSelection, Object aDropTarget) { return doDrop(aDropTarget, aDragSelection); } @Override public IStatus handleDrop(CommonDropAdapter aDropAdapter, final DropTargetEvent aDropTargetEvent, Object aTarget) { if ( aDropTargetEvent.data instanceof StructuredSelection ) { IStructuredSelection s3ObjectSelection = (StructuredSelection) aDropTargetEvent.data; return doDrop(aTarget, s3ObjectSelection); } return Status.OK_STATUS; } protected IStatus doDrop(Object aTarget, IStructuredSelection s3ObjectSelection) { if ( !(aTarget instanceof IResource) ) { return Status.CANCEL_STATUS; } // Drop targets can be folders, projects, or files. In the case of // files, we just want to identify the parent directory. IResource resource = (IResource) aTarget; if ( resource instanceof IFile ) { resource = resource.getParent(); } final IResource dropFolder = resource; final S3ObjectSummary s3object = (S3ObjectSummary) s3ObjectSelection .getFirstElement(); final File f = dropFolder.getLocation().toFile(); if ( !f.exists() ) return Status.CANCEL_STATUS; String fileName = getOutputFileName(s3object, f); if ( fileName == null || fileName.length() == 0 ) { return Status.CANCEL_STATUS; } final File outputFile = new File(fileName); new DownloadObjectJob("Downloading " + s3object.getKey(), s3object, dropFolder, outputFile).schedule(); return Status.OK_STATUS; } /** * Opens a save-file dialog to prompt the user for a file name. */ private String getOutputFileName(final S3ObjectSummary s3object, final File f) { FileDialog dialog = new FileDialog(Display.getDefault().getActiveShell(), SWT.SAVE); dialog.setFilterPath(f.getAbsolutePath()); dialog.setFileName(s3object.getKey()); dialog.setOverwrite(true); String fileName = dialog.open(); return fileName; } /** * Async job to download an object from S3 */ private final class DownloadObjectJob extends Job { private final S3ObjectSummary s3object; private final IResource dropFolder; private final File outputFile; private DownloadObjectJob(String name, S3ObjectSummary s3object, IResource dropFolder, File outputFile) { super(name); this.s3object = s3object; this.dropFolder = dropFolder; this.outputFile = outputFile; } @Override protected IStatus run(final IProgressMonitor monitor) { FileOutputStream fos = null; try { AmazonS3 client = AwsToolkitCore.getClientFactory().getS3ClientForBucket(s3object.getBucketName()); S3Object object = client.getObject(s3object.getBucketName(), s3object.getKey()); // This number is used for reporting only; the download // will appear to complete early if the file is bigger // than 2GB. long totalNumBytes = object.getObjectMetadata().getContentLength(); if ( totalNumBytes > Integer.MAX_VALUE ) totalNumBytes = Integer.MAX_VALUE; monitor.beginTask("Downloading", (int) totalNumBytes); // For a new file this is a no-op, but it truncates an // existing file for overwrite. try (RandomAccessFile raf = new RandomAccessFile(outputFile, "rw")) { raf.setLength(0); } fos = new FileOutputStream(outputFile); InputStream is = object.getObjectContent(); byte[] buffer = new byte[4096]; int bytesRead = 0; while ( (bytesRead = is.read(buffer)) > 0 ) { fos.write(buffer, 0, bytesRead); monitor.worked(bytesRead); } } catch ( Exception e ) { return new Status(Status.ERROR, AwsToolkitCore.getDefault().getPluginId(), "Error downloading file from S3", e); } finally { if ( fos != null ) { try { fos.close(); } catch ( Exception e ) { AwsToolkitCore.getDefault().logError("Couldn't close file output stream", e); } } monitor.done(); } // Refresh the drop folder // TODO: this won't work if they chose another folder in the // file selection dialog. Display.getDefault().asyncExec(new Runnable() { @Override public void run() { try { dropFolder.refreshLocal(1, monitor); } catch ( CoreException e ) { AwsToolkitCore.getDefault().logError("Couldn't refresh local files", e); } } }); return Status.OK_STATUS; } } }
7,789
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/actions/S3ActionProvider.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.actions; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.navigator.CommonActionProvider; import com.amazonaws.eclipse.explorer.s3.OpenBucketEditorAction; import com.amazonaws.services.s3.model.Bucket; public class S3ActionProvider extends CommonActionProvider { @Override public void fillContextMenu(IMenuManager menu) { IStructuredSelection selection = (IStructuredSelection) getContext().getSelection(); if (selection.size() == 1 && selection.toList().get(0) instanceof Bucket) { Bucket bucket = (Bucket)selection.toList().get(0); menu.add(new OpenBucketEditorAction(bucket.getName())); menu.add(new Separator()); } boolean onlyBucketsSelected = true; for (Object obj : selection.toList()) { if (obj instanceof Bucket == false) { onlyBucketsSelected = false; break; } } menu.add(new CreateBucketAction()); if (onlyBucketsSelected) { menu.add(new DeleteBucketAction(selection.toList())); } } }
7,790
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/actions/DeleteBucketAction.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.actions; import java.util.Collection; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.eclipse.explorer.s3.S3ContentProvider; import com.amazonaws.eclipse.explorer.s3.util.ObjectUtils; import com.amazonaws.services.s3.model.Bucket; public class DeleteBucketAction extends AwsAction { private Collection<Bucket> buckets; public DeleteBucketAction(Collection<Bucket> buckets) { super(AwsToolkitMetricType.EXPLORER_S3_DELETE_BUCKET); this.buckets = buckets; } @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor("remove"); } @Override public String getText() { if ( buckets.size() > 1 ) return "Delete Buckets"; else return "Delete Bucket"; } private Dialog newConfirmationDialog(String title, String message) { return new MessageDialog(Display.getDefault().getActiveShell(), title, null, message, MessageDialog.QUESTION, new String[] {"No", "Yes"}, 1); } @Override protected void doRun() { Dialog dialog = newConfirmationDialog(getText() + "?", "Are you sure you want to delete the selected buckets?"); if (dialog.open() != 1) { actionCanceled(); actionFinished(); return; } new Job("Deleting Buckets") { @Override protected IStatus run(IProgressMonitor monitor) { try { ObjectUtils objectUtils = new ObjectUtils(); for ( Bucket bucket : buckets ) { objectUtils.deleteBucketAndAllVersions(bucket.getName()); } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { S3ContentProvider.getInstance().refresh(); } }); actionSucceeded(); return Status.OK_STATUS; } catch (Exception e) { actionFailed(); return new Status(IStatus.ERROR, AwsToolkitCore.getDefault().getPluginId(), "Unable to delete buckets: " + e.getMessage(), e); } finally { actionFinished(); } } }.schedule(); } }
7,791
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/actions/GeneratePresignedUrlAction.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.actions; import java.net.URL; import java.util.Calendar; import java.util.Date; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.DateTime; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.eclipse.explorer.s3.S3ObjectSummaryTable; import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest; import com.amazonaws.services.s3.model.ResponseHeaderOverrides; import com.amazonaws.services.s3.model.S3ObjectSummary; /** * Action to generate a pre-signed URL for accessing an object. */ public class GeneratePresignedUrlAction extends AwsAction { private final S3ObjectSummaryTable table; public GeneratePresignedUrlAction(S3ObjectSummaryTable s3ObjectSummaryTable) { super(AwsToolkitMetricType.EXPLORER_S3_GENERATE_PRESIGNED_URL); table = s3ObjectSummaryTable; setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_HTML_DOC)); } @Override public String getText() { return "Generate Pre-signed URL"; } @Override protected void doRun() { DateSelectionDialog dialog = new DateSelectionDialog(Display.getDefault().getActiveShell()); if ( dialog.open() != Window.OK ) { actionCanceled(); actionFinished(); return; } try { S3ObjectSummary selectedObject = table.getSelectedObjects().iterator().next(); GeneratePresignedUrlRequest rq = new GeneratePresignedUrlRequest(selectedObject.getBucketName(), selectedObject.getKey()).withExpiration(dialog.getDate()); if ( dialog.getContentType() != null && dialog.getContentType().length() > 0 ) { rq.setResponseHeaders(new ResponseHeaderOverrides().withContentType(dialog.getContentType())); } URL presignedUrl = table.getS3Client().generatePresignedUrl(rq); final Clipboard cb = new Clipboard(Display.getDefault()); TextTransfer textTransfer = TextTransfer.getInstance(); cb.setContents(new Object[] { presignedUrl.toString() }, new Transfer[] { textTransfer }); actionSucceeded(); } catch (Exception e) { actionFailed(); AwsToolkitCore.getDefault().reportException(e.getMessage(), e); } finally { actionFinished(); } } @Override public boolean isEnabled() { return table.getSelectedObjects().size() == 1; } private final class DateSelectionDialog extends MessageDialog { public String getContentType() { return contentType; } public Date getDate() { return calendar.getTime(); } private Calendar calendar = Calendar.getInstance(); private String contentType; @Override protected Control createDialogArea(Composite parent) { // create the top level composite for the dialog area Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginHeight = 0; layout.marginWidth = 0; composite.setLayout(layout); GridData data = new GridData(GridData.FILL_BOTH); data.horizontalSpan = 2; composite.setLayoutData(data); createCustomArea(composite); return composite; } @Override protected Control createCustomArea(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, false); composite.setLayoutData(layoutData); composite.setLayout(new GridLayout(1, false)); new Label(composite, SWT.None).setText("Expiration date:"); final DateTime calendarControl = new DateTime(composite, SWT.CALENDAR); calendarControl.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { calendar.set(Calendar.YEAR, calendarControl.getYear()); calendar.set(Calendar.MONTH, calendarControl.getMonth()); calendar.set(Calendar.DAY_OF_MONTH, calendarControl.getDay()); } }); Composite timeComposite = new Composite(composite, SWT.NONE); timeComposite.setLayout(new GridLayout(2, false)); new Label(timeComposite, SWT.None).setText("Expiration time: "); final DateTime timeControl = new DateTime(timeComposite, SWT.TIME); timeControl.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { calendar.set(Calendar.HOUR, timeControl.getHours()); calendar.set(Calendar.MINUTE, timeControl.getMinutes()); calendar.set(Calendar.SECOND, timeControl.getSeconds()); } }); Composite contentTypeComp = new Composite(composite, SWT.None); contentTypeComp.setLayoutData(layoutData); contentTypeComp.setLayout(new GridLayout(1, false)); new Label(contentTypeComp, SWT.None).setText("Content-type override (optional): "); final Text contentTypeText = new Text(contentTypeComp, SWT.BORDER); contentTypeText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { contentType = contentTypeText.getText(); } }); contentTypeText.setLayoutData(GridDataFactory.fillDefaults().grab(true, false).create()); return composite; } protected DateSelectionDialog(Shell parentShell) { super(parentShell, "Generate Presigned URL", AwsToolkitCore.getDefault().getImageRegistry() .get(AwsToolkitCore.IMAGE_AWS_ICON), "Expiration date:", MessageDialog.NONE, new String[] { "Copy to clipboard" }, 0); } } }
7,792
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/actions/CreateBucketAction.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.actions; import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.explorer.AwsAction; public class CreateBucketAction extends AwsAction { public CreateBucketAction() { super(AwsToolkitMetricType.EXPLORER_S3_CREATE_BUCKET); setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor("add")); setText("Create New Bucket"); } @Override protected void doRun() { WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), new CreateBucketWizard()); if (Window.OK == dialog.open()) { actionSucceeded(); } else { actionCanceled(); } actionFinished(); } }
7,793
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/actions/DeleteObjectAction.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.actions; import java.util.ArrayList; import java.util.Collection; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.eclipse.explorer.s3.S3ObjectSummaryTable; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.S3ObjectSummary; public class DeleteObjectAction extends AwsAction { private final S3ObjectSummaryTable table; public DeleteObjectAction(S3ObjectSummaryTable s3ObjectSummaryTable) { super(AwsToolkitMetricType.EXPLORER_S3_DELETE_OBJECTS); table = s3ObjectSummaryTable; setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor("remove")); } @Override public String getText() { if ( table.getSelectedObjects().size() > 1 ) return "Delete Objects"; else return "Delete Object"; } private Dialog newConfirmationDialog(String title, String message) { return new MessageDialog(Display.getDefault().getActiveShell(), title, null, message, MessageDialog.QUESTION, new String[] {"No", "Yes"}, 1); } @Override protected void doRun() { Dialog dialog = newConfirmationDialog(getText() + "?", "Are you sure you want to delete the selected objects?"); if (dialog.open() != 1) { actionCanceled(); actionFinished(); return; } new Job("Deleting Objects") { @Override protected IStatus run(IProgressMonitor monitor) { final Collection<S3ObjectSummary> selectedObjects = new ArrayList<>(); Display.getDefault().syncExec(new Runnable() { @Override public void run() { selectedObjects.addAll(table.getSelectedObjects()); } }); monitor.beginTask("Deleting objects", selectedObjects.size()); try { AmazonS3 s3 = table.getS3Client(); for ( S3ObjectSummary summary : selectedObjects ) { s3.deleteObject(summary.getBucketName(), summary.getKey()); monitor.worked(1); } Display.getDefault().asyncExec(new Runnable() { @Override public void run() { String prefix = null; if (selectedObjects.size() == 1) { String key = selectedObjects.iterator().next().getKey(); int slashIndex = key.lastIndexOf('/'); if (slashIndex > 0) { prefix = key.substring(0, slashIndex); } } table.refresh(prefix); } }); actionSucceeded(); return Status.OK_STATUS; } catch (Exception e) { actionFailed(); return new Status(IStatus.ERROR, AwsToolkitCore.getDefault().getPluginId(), "Unable to delete objects: " + e.getMessage(), e); } finally { actionFinished(); monitor.done(); } } }.schedule(); } @Override public boolean isEnabled() { return table.getSelectedObjects().size() > 0; } }
7,794
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/actions/EditObjectTagsAction.java
/* * Copyright 2017 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 com.amazonaws.eclipse.explorer.s3.actions; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.window.Window; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Display; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.model.KeyValueSetDataModel; import com.amazonaws.eclipse.core.model.KeyValueSetDataModel.Pair; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.core.ui.TagsEditingDialog; import com.amazonaws.eclipse.core.ui.TagsEditingDialog.TagsEditingDialogBuilder; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.eclipse.explorer.s3.S3Constants; import com.amazonaws.eclipse.explorer.s3.S3ObjectSummaryTable; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.GetObjectTaggingRequest; import com.amazonaws.services.s3.model.ObjectTagging; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.model.SetObjectTaggingRequest; import com.amazonaws.services.s3.model.Tag; public class EditObjectTagsAction extends AwsAction { private final S3ObjectSummaryTable table; public EditObjectTagsAction(S3ObjectSummaryTable s3ObjectSummaryTable) { super(AwsToolkitMetricType.EXPLORER_S3_EDIT_OBJECT_TAGS); this.table = s3ObjectSummaryTable; setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_WRENCH)); setText("Edit Tags"); } @Override public boolean isEnabled() { return table.getSelectedObjects().size() == 1; } @Override protected void doRun() { final AmazonS3 s3 = table.getS3Client(); final S3ObjectSummary selectedObject = table.getSelectedObjects().iterator().next(); List<Tag> tags = s3.getObjectTagging(new GetObjectTaggingRequest( selectedObject.getBucketName(), selectedObject.getKey())) .getTagSet(); final KeyValueSetDataModel dataModel = convertToDataModel(tags); final TagsEditingDialog dialog = new TagsEditingDialogBuilder() .maxKeyLength(S3Constants.MAX_S3_OBJECT_TAG_KEY_LENGTH) .maxValueLength(S3Constants.MAX_S3_OBJECT_TAG_VALUE_LENGTH) .saveListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { saveTags(s3, selectedObject.getBucketName(), selectedObject.getKey(), dataModel); } }) .build(Display.getDefault().getActiveShell(), dataModel); if (Window.OK == dialog.open()) { try { saveTags(s3, selectedObject.getBucketName(), selectedObject.getKey(), dataModel); actionSucceeded(); } catch (Exception e) { actionFailed(); AwsToolkitCore.getDefault().reportException(e.getMessage(), e); } finally { actionFinished(); } } else { actionCanceled(); actionFinished(); } } private void saveTags(AmazonS3 s3, String bucket, String key, KeyValueSetDataModel dataModel) { List<Tag> tags = convertFromDataModel(dataModel); s3.setObjectTagging(new SetObjectTaggingRequest( bucket, key, new ObjectTagging(tags))); } private KeyValueSetDataModel convertToDataModel(List<Tag> tags) { List<Pair> pairList = new ArrayList<>(tags.size()); for (Tag tag : tags) { pairList.add(new Pair(tag.getKey(), tag.getValue())); } return new KeyValueSetDataModel(S3Constants.MAX_S3_OBJECT_TAGS, pairList); } private List<Tag> convertFromDataModel(KeyValueSetDataModel dataModel) { List<Tag> tags = new ArrayList<>(dataModel.getPairSet().size()); for (Pair pair : dataModel.getPairSet()) { tags.add(new Tag(pair.getKey(), pair.getValue())); } return tags; } }
7,795
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/actions/CreateBucketWizard.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.actions; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.eclipse.core.databinding.validation.ValidationStatus; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.wizard.Wizard; import com.amazonaws.AmazonServiceException; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.regions.RegionUtils; import com.amazonaws.eclipse.core.ui.wizards.CompositeWizardPage; import com.amazonaws.eclipse.core.ui.wizards.InputValidator; import com.amazonaws.eclipse.core.ui.wizards.TextWizardPageInput; import com.amazonaws.eclipse.core.ui.wizards.WizardPageInput; import com.amazonaws.eclipse.explorer.s3.S3ContentProvider; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.internal.BucketNameUtils; import com.amazonaws.services.s3.model.CreateBucketRequest; import com.amazonaws.services.s3.model.ListObjectsRequest; class CreateBucketWizard extends Wizard { private final CompositeWizardPage page; /** * Constructor. */ public CreateBucketWizard() { page = new CompositeWizardPage( "Create New Bucket", "Create New Bucket", AwsToolkitCore.getDefault() .getImageRegistry() .getDescriptor("aws-logo")); WizardPageInput bucketName = new TextWizardPageInput( "Bucket Name: ", null, // no descriptive text. IsBucketNameValid.INSTANCE, IsBucketNameUnique.INSTANCE ); page.addInput(BUCKET_NAME_INPUT, bucketName); } @Override public void addPages() { addPage(page); } @Override public int getPageCount() { return 1; } @Override public boolean needsPreviousAndNextButtons() { return false; } @Override public boolean performFinish() { String regionId = RegionUtils.getCurrentRegion().getId(); String bucketName = (String) page.getInputValue(BUCKET_NAME_INPUT); AmazonS3 client = AwsToolkitCore.getClientFactory().getS3Client(); CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName); if ("us-east-1".equals(regionId)) { // us-east-1 is the default, no need to set a location } else if ("eu-west-1".equals(regionId)) { // eu-west-1 uses an older style location createBucketRequest.setRegion("EU"); } else { createBucketRequest.setRegion(regionId); } client.createBucket(createBucketRequest); S3ContentProvider.getInstance().refresh(); return true; } private static final String BUCKET_NAME_INPUT = "bucketName"; /** * Synchronous validation; is this a syntactically-valid bucket name? */ private static class IsBucketNameValid implements InputValidator { public static final IsBucketNameValid INSTANCE = new IsBucketNameValid(); /** * Validate whether the input is a syntactically-valid bucket name. * * @param value the bucket name * @return the result of validation */ @Override public IStatus validate(final Object value) { String bucketName = (String) value; if (bucketName == null || bucketName.length() == 0) { return ValidationStatus.error("Please enter a bucket name"); } try { BucketNameUtils.validateBucketName(bucketName); } catch (IllegalArgumentException exception) { return ValidationStatus.error(exception.getMessage()); } return ValidationStatus.ok(); } /** * I'm stateless, use my singleton INSTANCE. */ private IsBucketNameValid() { } } /** * Asynchronous validation; is the bucket name already in use by * someone else? */ private static class IsBucketNameUnique implements InputValidator { public static final IsBucketNameUnique INSTANCE = new IsBucketNameUnique(); /** * Validate that there is no existing bucket with the given name. * * @param value the bucket name * @return the result of validation */ @Override public IStatus validate(final Object value) { String bucketName = (String) value; AmazonS3 client = AwsToolkitCore.getClientFactory().getS3Client(); try { client.listObjects(new ListObjectsRequest() .withBucketName(bucketName) .withMaxKeys(0)); } catch (AmazonServiceException exception) { if (VALID_ERROR_CODES.contains(exception.getErrorCode())) { return ValidationStatus.ok(); } // Not sure if listObjects will ever return this, but check // for it just in case... if ("InvalidBucketName".equals(exception.getErrorCode())) { return ValidationStatus.error("Invalid bucket name"); } if (!IN_USE_ERROR_CODES.contains(exception.getErrorCode())) { // Unanticipated error code; log it for future analysis. // Should we be erring on the side of leniency here and // treating these as valid so we don't accidentally block // a valid creation request? AwsToolkitCore.getDefault().logError( "Error checking whether bucket exists", exception ); return ValidationStatus.error("Error validating bucket name"); } } return ValidationStatus.error("Bucket name in use"); } /** * I'm stateless, use my singleton INSTANCE. */ private IsBucketNameUnique() { } /** * Error Codes for ListObjects which we interpret to mean that the * bucket name is valid and does not yet exist. */ private static final Set<String> VALID_ERROR_CODES; static { Set<String> set = new HashSet<>(); set.add("NoSuchBucket"); // err on the side of allowing the bucket creation in any // of these expected transient failure cases. set.add("RequestTimeout"); set.add("ServiceUnavailable"); set.add("SlowDown"); VALID_ERROR_CODES = Collections.unmodifiableSet(set); } /** * Error Codes for ListObjects which imply that the bucket already * exists. */ private static final Set<String> IN_USE_ERROR_CODES; static { Set<String> set = new HashSet<>(); set.add("AccessDenied"); set.add("InvalidBucketState"); set.add("InvalidObjectState"); set.add("PermanentRedirect"); set.add("Redirect"); set.add("TemporaryRedirect"); IN_USE_ERROR_CODES = Collections.unmodifiableSet(set); } }; }
7,796
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/s3/actions/EditObjectPermissionsAction.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.s3.actions; import java.util.Collection; import java.util.Iterator; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.window.Window; import com.amazonaws.AmazonClientException; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType; import com.amazonaws.eclipse.explorer.AwsAction; import com.amazonaws.eclipse.explorer.s3.S3ObjectSummaryTable; import com.amazonaws.eclipse.explorer.s3.acls.EditObjectPermissionsDialog; import com.amazonaws.eclipse.explorer.s3.acls.EditPermissionsDialog; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.AccessControlList; import com.amazonaws.services.s3.model.S3ObjectSummary; public class EditObjectPermissionsAction extends AwsAction { private final S3ObjectSummaryTable table; public EditObjectPermissionsAction(S3ObjectSummaryTable s3ObjectSummaryTable) { super(AwsToolkitMetricType.EXPLORER_S3_EDIT_OBJECT_PERMISSIONS); this.table = s3ObjectSummaryTable; setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_WRENCH)); setText("Edit Permissions"); } @Override public boolean isEnabled() { return table.getSelectedObjects().size() > 0; } @Override protected void doRun() { final Collection<S3ObjectSummary> selectedObjects = table.getSelectedObjects(); final EditPermissionsDialog editPermissionsDialog = new EditObjectPermissionsDialog(selectedObjects); if (editPermissionsDialog.open() == Window.OK) { final AmazonS3 s3 = table.getS3Client(); new Job("Updating object ACLs") { @Override protected IStatus run(IProgressMonitor monitor) { try { AccessControlList newAcl = editPermissionsDialog.getAccessControlList(); Iterator<S3ObjectSummary> iterator = selectedObjects.iterator(); while (iterator.hasNext()) { S3ObjectSummary obj = iterator.next(); s3.setObjectAcl(obj.getBucketName(), obj.getKey(), newAcl); } actionSucceeded(); } catch (AmazonClientException ace) { actionFailed(); AwsToolkitCore.getDefault().reportException("Unable to update object ACL", ace); } finally { actionFinished(); } return Status.OK_STATUS; } }.schedule(); } else { actionCanceled(); actionFinished(); } } }
7,797
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sns/TopicEditor.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.sns; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.layout.TreeColumnLayout; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.ITreePathContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.part.EditorPart; import com.amazonaws.eclipse.core.AWSClientFactory; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.core.ui.IRefreshable; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.model.GetTopicAttributesRequest; import com.amazonaws.services.sns.model.ListSubscriptionsByTopicRequest; import com.amazonaws.services.sns.model.ListSubscriptionsByTopicResult; import com.amazonaws.services.sns.model.Subscription; import com.amazonaws.services.sns.model.UnsubscribeRequest; public class TopicEditor extends EditorPart implements IRefreshable { private TopicEditorInput topicEditorInput; private TreeViewer viewer; private Text ownerLabel; private Text pendingSubscriptionsLabel; private Text confirmedSubscriptionsLabel; private Text deletedSubscriptionsLabel; private Text displayNameLabel; private Text topicArnLabel; @Override public void doSave(IProgressMonitor monitor) {} @Override public void doSaveAs() {} @Override public boolean isDirty() { return false; } @Override public boolean isSaveAsAllowed() { return false; } @Override public void setFocus() {} @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); setPartName(input.getName()); topicEditorInput = (TopicEditorInput)input; } @Override public void createPartControl(Composite parent) { FormToolkit toolkit = new FormToolkit(Display.getDefault()); ScrolledForm form = new ScrolledForm(parent, SWT.V_SCROLL); form.setExpandHorizontal(true); form.setExpandVertical(true); form.setBackground(toolkit.getColors().getBackground()); form.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); form.setFont(JFaceResources.getHeaderFont()); form.setText(topicEditorInput.getName()); toolkit.decorateFormHeading(form.getForm()); form.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_QUEUE)); form.getBody().setLayout(new GridLayout()); createTopicSummaryComposite(toolkit, form.getBody()); createSubscriptionsComposite(toolkit, form.getBody()); form.getToolBarManager().add(new RefreshAction()); form.getToolBarManager().add(new Separator()); form.getToolBarManager().add(new PublishMessageAction(getClient(), topicEditorInput.getTopic())); form.getToolBarManager().add(new NewSubscriptionAction(getClient(), topicEditorInput.getTopic(), this)); form.getToolBarManager().update(true); } private class LoadTopicAttributesThread extends Thread { @Override public void run() { try { GetTopicAttributesRequest request = new GetTopicAttributesRequest(topicEditorInput.getTopic().getTopicArn()); final Map<String, String> attributes = getClient().getTopicAttributes(request).getAttributes(); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { ownerLabel.setText(getValue(attributes,"Owner")); pendingSubscriptionsLabel.setText(getValue(attributes, "SubscriptionsPending")); confirmedSubscriptionsLabel.setText(getValue(attributes, "SubscriptionsConfirmed")); deletedSubscriptionsLabel.setText(getValue(attributes, "SubscriptionsDeleted")); displayNameLabel.setText(getValue(attributes, "DisplayName")); topicArnLabel.setText(getValue(attributes, "TopicArn")); } private String getValue(Map<String, String> map, String key) { if (map.get(key) != null) return map.get(key); return ""; } }); } catch (Exception e) { AwsToolkitCore.getDefault().reportException("Unable to load topic attributes", e); } } } private final class UnsubscribeAction extends Action { public UnsubscribeAction() { this.setText("Delete Subscription"); this.setToolTipText("Delete the selected subscriptions"); this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE)); } @Override public boolean isEnabled() { boolean isEmpty = viewer.getSelection().isEmpty(); return !isEmpty; } @Override public void run() { MessageDialog confirmationDialog = new MessageDialog( Display.getDefault().getActiveShell(), "Delete Subscriptions?", null, "Are you sure you want to delete the selected subscriptions?", MessageDialog.QUESTION, new String[] {"OK", "Cancel"}, 0); if (confirmationDialog.open() == 0) { StructuredSelection selection = (StructuredSelection)viewer.getSelection(); Iterator<Subscription> iterator = selection.iterator(); while (iterator.hasNext()) { Subscription subscription = iterator.next(); try { getClient().unsubscribe(new UnsubscribeRequest(subscription.getSubscriptionArn())); } catch (Exception e) { AwsToolkitCore.getDefault().reportException("Unable to delete subscription", e); } } new RefreshAction().run(); } } } private final class RefreshAction extends Action { public RefreshAction() { this.setText("Refresh"); this.setToolTipText("Refresh topic information and subscriptions"); this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH)); } @Override public void run() { new LoadTopicAttributesThread().start(); new LoadSubscriptionsThread().start(); } } private AmazonSNS getClient() { AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(topicEditorInput.getAccountId()); return clientFactory.getSNSClientByEndpoint(topicEditorInput.getRegionEndpoint()); } private final class SubscriptionContentProvider implements ITreePathContentProvider { private Subscription[] subscriptions; @Override public void dispose() {} @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { if (newInput instanceof List) { subscriptions = ((List<Subscription>)newInput).toArray(new Subscription[0]); } else { subscriptions = new Subscription[0]; } } @Override public Object[] getElements(Object inputElement) { return subscriptions; } @Override public Object[] getChildren(TreePath parentPath) { return null; } @Override public boolean hasChildren(TreePath path) { return false; } @Override public TreePath[] getParents(Object element) { return null; } } private final class SubscriptionLabelProvider implements ITableLabelProvider { @Override public void dispose() {} @Override public void addListener(ILabelProviderListener listener) {} @Override public void removeListener(ILabelProviderListener listener) {} @Override public boolean isLabelProperty(Object element, String property) { return false; } @Override public Image getColumnImage(Object element, int columnIndex) { return null; } @Override public String getColumnText(Object element, int columnIndex) { if (element instanceof Subscription == false) return "???"; Subscription subscription = (Subscription)element; switch (columnIndex) { case 0: return subscription.getProtocol(); case 1: return subscription.getOwner(); case 2: return subscription.getEndpoint(); case 3: return subscription.getSubscriptionArn(); default: return ""; } } } private void createTopicSummaryComposite(FormToolkit toolkit, Composite parent) { GridDataFactory gdf = GridDataFactory.swtDefaults().align(SWT.FILL, SWT.TOP).grab(true, false); Composite summaryComposite = toolkit.createComposite(parent, SWT.NONE); summaryComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); summaryComposite.setLayout(new GridLayout(2, false)); toolkit.createLabel(summaryComposite, "Owner ID:"); ownerLabel = toolkit.createText(summaryComposite, "", SWT.READ_ONLY); gdf.applyTo(ownerLabel); toolkit.createLabel(summaryComposite, "Pending Subscriptions:"); pendingSubscriptionsLabel = toolkit.createText(summaryComposite, "", SWT.READ_ONLY); gdf.applyTo(pendingSubscriptionsLabel); toolkit.createLabel(summaryComposite, "Confirmed Subscriptions:"); confirmedSubscriptionsLabel = toolkit.createText(summaryComposite, "", SWT.READ_ONLY); gdf.applyTo(confirmedSubscriptionsLabel); toolkit.createLabel(summaryComposite, "Deleted Subscriptions:"); deletedSubscriptionsLabel = toolkit.createText(summaryComposite, "", SWT.READ_ONLY); gdf.applyTo(deletedSubscriptionsLabel); toolkit.createLabel(summaryComposite, "Display Name:"); displayNameLabel = toolkit.createText(summaryComposite, "", SWT.READ_ONLY); gdf.applyTo(displayNameLabel); toolkit.createLabel(summaryComposite, "Topic ARN:"); topicArnLabel = toolkit.createText(summaryComposite, "", SWT.READ_ONLY); gdf.applyTo(topicArnLabel); new LoadTopicAttributesThread().start(); } private void createSubscriptionsComposite(FormToolkit toolkit, Composite parent) { Composite subscriptionsComposite = toolkit.createComposite(parent); subscriptionsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); subscriptionsComposite.setLayout(new GridLayout()); Label label = toolkit.createLabel(subscriptionsComposite, "Subscriptions"); label.setFont(JFaceResources.getHeaderFont()); label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); label.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false)); Composite composite = toolkit.createComposite(subscriptionsComposite); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); TreeColumnLayout tableColumnLayout = new TreeColumnLayout(); composite.setLayout(tableColumnLayout); SubscriptionContentProvider contentProvider = new SubscriptionContentProvider(); SubscriptionLabelProvider labelProvider = new SubscriptionLabelProvider(); viewer = new TreeViewer(composite, SWT.BORDER | SWT.MULTI); viewer.getTree().setLinesVisible(true); viewer.getTree().setHeaderVisible(true); viewer.setLabelProvider(labelProvider); viewer.setContentProvider(contentProvider); createColumns(tableColumnLayout, viewer.getTree()); viewer.setInput(new Object()); final IRefreshable refreshable = this; MenuManager menuManager = new MenuManager(); menuManager.setRemoveAllWhenShown(true); menuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { manager.add(new NewSubscriptionAction(getClient(), topicEditorInput.getTopic(), refreshable)); manager.add(new UnsubscribeAction()); } }); Menu menu = menuManager.createContextMenu(viewer.getTree()); viewer.getTree().setMenu(menu); getSite().registerContextMenu(menuManager, viewer); refreshData(); } private void createColumns(TreeColumnLayout columnLayout, Tree tree) { createColumn(tree, columnLayout, "Protocol"); createColumn(tree, columnLayout, "Owner"); createColumn(tree, columnLayout, "Endpoint"); createColumn(tree, columnLayout, "Subscription ARN"); } private TreeColumn createColumn(Tree tree, TreeColumnLayout columnLayout, String text) { TreeColumn column = new TreeColumn(tree, SWT.NONE); column.setText(text); column.setMoveable(true); columnLayout.setColumnData(column, new ColumnWeightData(30)); return column; } @Override public void refreshData() { new LoadSubscriptionsThread().start(); } private class LoadSubscriptionsThread extends Thread { @Override public void run() { AmazonSNS sns = getClient(); try { String topicArn = topicEditorInput.getTopic().getTopicArn(); String nextToken = null; ListSubscriptionsByTopicResult subscriptionsByTopic = null; final List<Subscription> subscriptions = new LinkedList<>(); do { if (subscriptionsByTopic != null) nextToken = subscriptionsByTopic.getNextToken(); subscriptionsByTopic = sns.listSubscriptionsByTopic(new ListSubscriptionsByTopicRequest(topicArn, nextToken)); subscriptions.addAll(subscriptionsByTopic.getSubscriptions()); } while (subscriptionsByTopic.getNextToken() != null); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { viewer.setInput(subscriptions); } }); } catch (Exception e) { AwsToolkitCore.getDefault().reportException("Unable to list subscriptions", e); } } } }
7,798
0
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer
Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/explorer/sns/TopicEditorInput.java
/* * Copyright 2011-2012 Amazon Technologies, Inc. * * 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://aws.amazon.com/apache2.0 * * This file 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 com.amazonaws.eclipse.explorer.sns; import org.eclipse.jface.resource.ImageDescriptor; import com.amazonaws.eclipse.core.AwsToolkitCore; import com.amazonaws.eclipse.explorer.AbstractAwsResourceEditorInput; import com.amazonaws.services.sns.model.Topic; public class TopicEditorInput extends AbstractAwsResourceEditorInput { private final Topic topic; private String name; public TopicEditorInput(final Topic topic, final String regionEndpoint, final String accountId) { super(regionEndpoint, accountId); this.topic = topic; } @Override public ImageDescriptor getImageDescriptor() { return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_TOPIC); } @Override public String getName() { if (name == null) { name = SNSContentProvider.parseTopicName(topic.getTopicArn()); } return name; } @Override public String getToolTipText() { return "Amazon SNS Topic Editor - " + getName(); } public Topic getTopic() { return topic; } @Override public String toString() { return topic.getTopicArn(); } @Override public int hashCode() { return topic.getTopicArn().hashCode(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof TopicEditorInput)) { return false; } TopicEditorInput that = (TopicEditorInput) obj; return topic.getTopicArn().equals(that.topic.getTopicArn()); } }
7,799