Java 类com.amazonaws.services.ec2.model.DescribeKeyPairsRequest 实例源码

项目:cerberus-lifecycle-cli    文件:Ec2ServiceTest.java   
@Test
public void testIsKeyPairPresentTrue() {

    String keyName = "key-name";

    when(ec2Client.describeKeyPairs(
            new DescribeKeyPairsRequest()
                    .withKeyNames(keyName)
            )
    ).thenReturn(
            new DescribeKeyPairsResult()
                    .withKeyPairs(
                            new KeyPairInfo()
                    )
    );

    // invoke method under test
    assertTrue(ec2Service.isKeyPairPresent(keyName));
}
项目:cerberus-lifecycle-cli    文件:Ec2ServiceTest.java   
@Test
public void testIsKeyPairPresentException() {

    String keyName = "key-name";
    String fakeExceptionMessage = "fake-exception";

    when(ec2Client.describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyName)))
            .thenThrow(new AmazonServiceException(fakeExceptionMessage));

    try {
        // invoke method under test
        ec2Service.isKeyPairPresent(keyName);
        fail("expected exception not passed up");
    } catch (AmazonServiceException ex) {
        // pass
        assertEquals(fakeExceptionMessage, ex.getErrorMessage());
    }
}
项目:dohko    文件:EC2.java   
public KeyPair getKeyPair(String keyName)
{
    KeyPair keyPair = null;

    if (!isNullOrEmpty(keyName))
    {
        try
        {
            DescribeKeyPairsResult describeKeyPairs = ec2_.describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyName));
            List<KeyPairInfo> keyPairs = describeKeyPairs.getKeyPairs();

            if (keyPairs != null && !keyPairs.isEmpty())
            {
                KeyPairInfo keyPairInfo = keyPairs.get(0);
                keyPair = new KeyPair(keyPairInfo.getKeyName()).withKeyFingerprint(keyPairInfo.getKeyFingerprint());
            }
        }
        catch (AmazonClientException exception)
        {
            LOG.debug("Error on describing keyPairs [{}] on [{}]. Error message: [{}]",  keyName,  credentials_.getProvider().getName(),
                       exception.getMessage());
        }
    }

    return keyPair;
}
项目:primecloud-controller    文件:AwsIaasGatewayScriptService.java   
@Override
public void importKeyPair(String keyName, String publicKey) throws AutoException {
    // キーペアがすでに登録されていたら何もしない
    DescribeKeyPairsRequest request = new DescribeKeyPairsRequest();
    DescribeKeyPairsResult result = ec2Client.describeKeyPairs(request);
    List<KeyPairInfo> keyPairs = result.getKeyPairs();

    for (KeyPairInfo keyPair : keyPairs) {
        if (keyPair.getKeyName().equals(keyName)) {
            log.info(platform.getPlatformName() + " の " + keyName + " はすでに登録されている為、キーのインポートをスキップします");
            System.out.println("IMPORT_SKIPPED");
            return;
        }
    }

    // インポート
    ImportKeyPairRequest request2 = new ImportKeyPairRequest();
    request2.withKeyName(keyName);
    request2.withPublicKeyMaterial(publicKey);
    ec2Client.importKeyPair(request2);

    log.info(keyName + "のキーをインポートしました。");
}
项目:cloudbreak    文件:AwsSetup.java   
private void validateExistingKeyPair(InstanceAuthentication instanceAuthentication, AwsCredentialView credentialView, String region) {
    String keyPairName = awsClient.getExistingKeyPairName(instanceAuthentication);
    if (StringUtils.isNoneEmpty(keyPairName)) {
        boolean keyPairIsPresentOnEC2 = false;
        try {
            AmazonEC2Client client = awsClient.createAccess(credentialView, region);
            DescribeKeyPairsResult describeKeyPairsResult = client.describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyPairName));
            keyPairIsPresentOnEC2 = describeKeyPairsResult.getKeyPairs().stream().findFirst().isPresent();
        } catch (RuntimeException e) {
            String errorMessage = String.format("Failed to get the key pair [name: '%s'] from EC2 [roleArn:'%s'], detailed message: %s.",
                    keyPairName, credentialView.getRoleArn(), e.getMessage());
            LOGGER.error(errorMessage, e);
        }
        if (!keyPairIsPresentOnEC2) {
            throw new CloudConnectorException(String.format("The key pair '%s' could not be found in the '%s' region of EC2.", keyPairName, region));
        }
    }
}
项目:cfnassist    文件:TestKeyPairCreationAndSave.java   
private List<KeyPairInfo> deleteKeyPair(String keypairName) {
    List<KeyPairInfo> keys;
    try {
        DescribeKeyPairsRequest query = new DescribeKeyPairsRequest().withKeyNames(keypairName);
        DescribeKeyPairsResult keysFound = ec2Client.describeKeyPairs(query);
        keys = keysFound.getKeyPairs();
    } catch (AmazonServiceException exception) {
        keys = new LinkedList<>();
    }

    if (keys.size() > 0) {
        DeleteKeyPairRequest deleteRequest = new DeleteKeyPairRequest().withKeyName(keypairName);
        ec2Client.deleteKeyPair(deleteRequest);
    }
    return keys;
}
项目:cerberus-lifecycle-cli    文件:Ec2Service.java   
/**
 * Checks if a key pair is present in AWS EC2.
 *
 * @param keyName Friendly name for the key
 * @return If present
 */
public boolean isKeyPairPresent(final String keyName) {
    final DescribeKeyPairsRequest request = new DescribeKeyPairsRequest().withKeyNames(keyName);

    try {
        final DescribeKeyPairsResult result = ec2Client.describeKeyPairs(request);
        return result.getKeyPairs().size() > 0;
    } catch (final AmazonServiceException ase) {
        if (ase.getErrorCode() == "InvalidKeyPair.NotFound") {
            return false;
        }

        throw ase;
    }
}
项目:cerberus-lifecycle-cli    文件:Ec2ServiceTest.java   
@Test
public void testIsKeyPairPresentFalse() {

    String keyName = "key-name";

    when(ec2Client.describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyName)))
            .thenReturn(new DescribeKeyPairsResult());

    // invoke method under test
    assertFalse(ec2Service.isKeyPairPresent(keyName));
}
项目:cerberus-lifecycle-cli    文件:Ec2ServiceTest.java   
@Test
public void testIsKeyPairPresentFalseNotFound() {

    String keyName = "key-name";

    AmazonServiceException ex = new AmazonServiceException("fake-exception");
    ex.setErrorCode("InvalidKeyPair.NotFound");

    when(ec2Client.describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyName)))
            .thenThrow(ex);

    // invoke method under test
    assertFalse(ec2Service.isKeyPairPresent(keyName));
}
项目:director-aws-plugin    文件:EC2InstanceTemplateConfigurationValidator.java   
/**
 * Validates the EC2 key name.
 *
 * @param client              the EC2 client
 * @param accumulator         the exception condition accumulator
 * @param localizationContext the localization context
 */
@VisibleForTesting
void checkKeyName(AmazonEC2Client client,
    Configured configuration,
    PluginExceptionConditionAccumulator accumulator,
    LocalizationContext localizationContext) {

  String keyName = configuration.getConfigurationValue(KEY_NAME, localizationContext);

  if (keyName != null) {
    LOG.info(">> Describing key pair");
    try {
      DescribeKeyPairsResult result = client.describeKeyPairs(
          new DescribeKeyPairsRequest().withKeyNames(keyName));
      // TODO Should this be REDACTED instead of NotDisplayed?
      checkCount(accumulator, KEY_NAME, localizationContext, "NotDisplayed",
          result.getKeyPairs());

    } catch (AmazonServiceException e) {
      if (e.getErrorCode().startsWith(INVALID_KEY_PAIR)) {
        addError(accumulator, KEY_NAME, localizationContext,
            null, INVALID_KEY_NAME_MSG, keyName);
      } else {
        throw Throwables.propagate(e);
      }
    }
  }
}
项目:cmn-project    文件:EC2.java   
public boolean keyPairExists(String name) {
    try {
        return !ec2.describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(name)).getKeyPairs().isEmpty();
    } catch (AmazonServiceException e) {
        if ("InvalidKeyPair.NotFound".equals(e.getErrorCode())) {
            return false;
        }
        throw e;
    }
}
项目:cmn-project    文件:KeyPairLoader.java   
public void load() {
    List<KeyPairInfo> remoteKeyPairs = AWS.ec2.ec2.describeKeyPairs(new DescribeKeyPairsRequest()
        .withFilters(new Filter("key-name").withValues(env.name + ":*"))).getKeyPairs();

    for (KeyPairInfo remoteKeyPair : remoteKeyPairs) {
        String keyPairId = keyPairId(env.name, remoteKeyPair.getKeyName());
        if (keyPairId != null) {
            KeyPair keyPair = resources.find(KeyPair.class, keyPairId)
                                       .orElseGet(() -> resources.add(new KeyPair(keyPairId, remoteKeyPair.getKeyName())));
            keyPair.remoteKeyPair = remoteKeyPair;
            keyPair.foundInRemote();
        }
    }
}
项目:primecloud-controller    文件:AwsDescribeServiceImpl.java   
/**
 * {@inheritDoc}
 */
@Override
public List<KeyPairInfo> getKeyPairs(Long userNo, Long platformNo) {
    // キーペアを取得
    AwsProcessClient awsProcessClient = awsProcessClientFactory.createAwsProcessClient(userNo, platformNo);
    DescribeKeyPairsRequest request = new DescribeKeyPairsRequest();
    DescribeKeyPairsResult result = awsProcessClient.getEc2Client().describeKeyPairs(request);
    List<KeyPairInfo> keyPairs = result.getKeyPairs();

    // ソート
    Collections.sort(keyPairs, Comparators.COMPARATOR_KEY_PAIR_INFO);

    return keyPairs;
}
项目:aws-sdk-java-resources    文件:EC2Impl.java   
@Override
public KeyPairCollection getKeyPairs(DescribeKeyPairsRequest request) {
    ResourceCollectionImpl result = service.getCollection("KeyPairs",
            request);

    if (result == null) return null;
    return new KeyPairCollectionImpl(result);
}
项目:cloudbreak    文件:AwsPlatformResources.java   
@Override
public CloudSshKeys sshKeys(CloudCredential cloudCredential, Region region, Map<String, String> filters) {
    Map<String, Set<CloudSshKey>> result = new HashMap<>();
    for (Region actualRegion : awsPlatformParameters.regions().types()) {
        // If region is provided then should filter for those region
        if (regionMatch(actualRegion, region)) {
            Set<CloudSshKey> cloudSshKeys = new HashSet<>();
            AmazonEC2Client ec2Client = awsClient.createAccess(new AwsCredentialView(cloudCredential), actualRegion.value());

            //create sshkey filter view
            PlatformResourceSshKeyFilterView filter = new PlatformResourceSshKeyFilterView(filters);

            DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();

            // If the filtervalue is provided then we should filter only for those securitygroups
            if (!Strings.isNullOrEmpty(filter.getKeyName())) {
                describeKeyPairsRequest.withKeyNames(filter.getKeyName());
            }

            for (KeyPairInfo keyPairInfo : ec2Client.describeKeyPairs(describeKeyPairsRequest).getKeyPairs()) {
                Map<String, Object> properties = new HashMap<>();
                properties.put("fingerPrint", keyPairInfo.getKeyFingerprint());
                cloudSshKeys.add(new CloudSshKey(keyPairInfo.getKeyName(), properties));
            }
            result.put(actualRegion.value(), cloudSshKeys);
        }
    }
    return new CloudSshKeys(result);
}
项目:clouck    文件:Ec2WrapperImpl.java   
@Override
public List<AbstractResource<?>> describeKeyPairs(Account account, Region region, DateTime dt, Ec2Filter... filters) {
    AmazonEC2 ec2 = findClient(account, region);

    DescribeKeyPairsRequest req = new DescribeKeyPairsRequest();
    for (Ec2Filter filter : filters) {
        Filter f = new Filter().withName(filter.getName()).withValues(filter.getValues());
        req.withFilters(f);
    }

    log.debug("start describing key pairs for account:{} in region:{} via api", account.getId() + "=>" + account.getName(), region);
    DescribeKeyPairsResult res = ec2.describeKeyPairs(req);

    return converter.toEc2KeyPairs(res.getKeyPairs(), account.getId(), region, dt);
}
项目:incubator-provisionr    文件:DeleteKeyPairLiveTest.java   
public void assertKeyNotFound(String keyName) {
    final DescribeKeyPairsRequest request = new DescribeKeyPairsRequest().withKeyNames(keyName);
    try {
        DescribeKeyPairsResult result = client.describeKeyPairs(request);
        fail("Found key " + result.getKeyPairs().get(0));

    } catch (AmazonServiceException e) {
        assertThat(e.getErrorCode()).isEqualTo(ErrorCodes.KEYPAIR_NOT_FOUND);
    }
}
项目:incubator-provisionr    文件:EnsureKeyPairExistsLiveTest.java   
private void assertKeyPairWasImportedAsExpected() {
    final DescribeKeyPairsRequest request = new DescribeKeyPairsRequest().withKeyNames(KEYPAIR_NAME);
    DescribeKeyPairsResult result = client.describeKeyPairs(request);

    assertThat(result.getKeyPairs()).hasSize(1);
    assertThat(result.getKeyPairs().get(0).getKeyFingerprint()).isEqualTo(TEST_KEY_FINGERPRINT);
}
项目:elasticsearch_my    文件:AmazonEC2Mock.java   
@Override
public DescribeKeyPairsResult describeKeyPairs(DescribeKeyPairsRequest describeKeyPairsRequest) throws AmazonServiceException, AmazonClientException {
    throw new UnsupportedOperationException("Not supported in mock");
}
项目:aws-sdk-java-resources    文件:KeyPairImpl.java   
@Override
public boolean load(DescribeKeyPairsRequest request) {
    return load(request, null);
}
项目:aws-sdk-java-resources    文件:KeyPairImpl.java   
@Override
public boolean load(DescribeKeyPairsRequest request,
        ResultCapture<DescribeKeyPairsResult> extractor) {

    return resource.load(request, extractor);
}
项目:aws-sdk-java-resources    文件:EC2Impl.java   
@Override
public KeyPairCollection getKeyPairs() {
    return getKeyPairs((DescribeKeyPairsRequest)null);
}
项目:datamung    文件:CreateJobPages.java   
private ModelAndView showWorkerInstanceOptions( JobInput input )
    throws IOException
{
    if ( input.getWorkerInstanceOptions() == null )
    {
        WorkerInstanceOptions defaultOptions = new WorkerInstanceOptions();

        input.setWorkerInstanceOptions( defaultOptions );
    }
    ModelAndView mav =
        new ModelAndView( "create/worker_options.vm" ).addObject( "input",
                                                                  input ).addObject( "inputData",
                                                                                     input.serializeTo() );
    AWSCredentials creds =
        new BasicAWSCredentials( input.getAwsAccessKeyId(),
                                 input.getAwsSecretKey() );

    // Fetch all keypairs
    mav.addObject( "allKeyPairs",
                   ec2.describeKeyPairs( decorate( new DescribeKeyPairsRequest(),
                                                   creds ) ).getKeyPairs() );

    // Fetch all security groups
    String vpcId = null;
    switch ( input.getActionType() )
    {
        case BACKUP_INSTANCE:
            DBInstance instance =
                rds.describeDBInstances( decorate( new DescribeDBInstancesRequest().withDBInstanceIdentifier( input.getSourceAndDestination().getDatabaseInstanceId() ),
                                                   creds ) ).getDBInstances().get( 0 );
            mav.addObject( "sourceDatabaseInstance", instance );
            if ( instance.getDBSubnetGroup() != null )
            {
                vpcId = instance.getDBSubnetGroup().getVpcId();
            }
            break;
        case CONVERT_SNAPSHOT:
            DBSnapshot snapshot =
                rds.describeDBSnapshots( decorate( new DescribeDBSnapshotsRequest().withDBSnapshotIdentifier( input.getSourceAndDestination().getDatabaseSnapshotId() ),
                                                   creds ) ).getDBSnapshots().get( 0 );
            mav.addObject( "sourceDatabaseSnapshot", snapshot );
            vpcId = snapshot.getVpcId();
            break;
        default:
            throw new IllegalStateException( "Action type "
                + input.getActionType() + " is not expected" );
    }
    mav.addObject( "vpcId", vpcId );

    List<SecurityGroup> availableGroups = new ArrayList<SecurityGroup>();
    for ( SecurityGroup group : ec2.describeSecurityGroups( decorate( new DescribeSecurityGroupsRequest(),
                                                                      creds ) ).getSecurityGroups() )
    {
        if ( StringUtils.equals( vpcId, group.getVpcId() )
            && !group.getGroupName().startsWith( "awseb-e-" ) )
        {
            availableGroups.add( group );
        }
    }
    mav.addObject( "allSecurityGroups", availableGroups );

    if ( vpcId != null )
    {
        List<Subnet> availableSubnets = new ArrayList<Subnet>();
        for ( Subnet subnet : ec2.describeSubnets( decorate( new DescribeSubnetsRequest(),
                                                             creds ) ).getSubnets() )
        {
            if ( StringUtils.equals( subnet.getVpcId(), vpcId ) )
            {
                availableSubnets.add( subnet );
            }
        }
        mav.addObject( "allSubnets", availableSubnets );
    }

    mav.addObject( "workerOptions", input.getWorkerInstanceOptions() );
    return mav;
}
项目:aws-sdk-java-resources    文件:EC2.java   
/**
 * Retrieves the KeyPairs collection referenced by this resource.
 */
KeyPairCollection getKeyPairs(DescribeKeyPairsRequest request);
项目:aws-sdk-java-resources    文件:KeyPair.java   
/**
 * Makes a call to the service to load this resource's attributes if they
 * are not loaded yet.
 * The following request parameters will be populated from the data of this
 * <code>KeyPair</code> resource, and any conflicting parameter value set in
 * the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>KeyNames.0</code></b>
 *         - mapped from the <code>Name</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return Returns {@code true} if the resource is not yet loaded when this
 *         method was invoked, which indicates that a service call has been
 *         made to retrieve the attributes.
 * @see DescribeKeyPairsRequest
 */
boolean load(DescribeKeyPairsRequest request);
项目:aws-sdk-java-resources    文件:KeyPair.java   
/**
 * Makes a call to the service to load this resource's attributes if they
 * are not loaded yet, and use a ResultCapture to retrieve the low-level
 * client response
 * The following request parameters will be populated from the data of this
 * <code>KeyPair</code> resource, and any conflicting parameter value set in
 * the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>KeyNames.0</code></b>
 *         - mapped from the <code>Name</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return Returns {@code true} if the resource is not yet loaded when this
 *         method was invoked, which indicates that a service call has been
 *         made to retrieve the attributes.
 * @see DescribeKeyPairsRequest
 */
boolean load(DescribeKeyPairsRequest request,
        ResultCapture<DescribeKeyPairsResult> extractor);