Search in sources :

Example 1 with BmcException

use of com.oracle.bmc.model.BmcException in project oci-java-sdk by oracle.

the class ResponseHelperTest method test_throwIfNotSuccessful_InvalidJsonResponse.

@Test
public void test_throwIfNotSuccessful_InvalidJsonResponse() {
    final Response jsonResponse = buildMockResponse(OPC_REQUEST_ID, JSON_MEDIA_TYPE, BAD_GATEWAY_STATUS);
    final String dummyServiceCode = "DummyServiceCode";
    final String dummyMessage = "DummyMessage";
    when(jsonResponse.readEntity(ResponseHelper.ErrorCodeAndMessage.class)).thenReturn(ResponseHelper.ErrorCodeAndMessage.builder().code(dummyServiceCode).message(dummyMessage).build());
    try {
        ResponseHelper.throwIfNotSuccessful(jsonResponse);
        fail("Should have thrown");
    } catch (BmcException exception) {
        validateExceptionFields(exception, OPC_REQUEST_ID, BAD_GATEWAY_STATUS, dummyServiceCode, dummyMessage);
    }
}
Also used : Response(javax.ws.rs.core.Response) BmcException(com.oracle.bmc.model.BmcException) Test(org.junit.Test)

Example 2 with BmcException

use of com.oracle.bmc.model.BmcException in project oci-java-sdk by oracle.

the class X509FederationClientTest method makeCall_shouldReuseWrappedInvocationBuilderReference_whenBmcExceptionIsThrown.

@Test
public void makeCall_shouldReuseWrappedInvocationBuilderReference_whenBmcExceptionIsThrown() throws Exception {
    // Set up WrappedInvocationBuilder used to verify
    URI requestURI = PowerMockito.mock(URI.class);
    final WrappedInvocationBuilder expectedWIb = mock(WrappedInvocationBuilder.class);
    final Invocation.Builder ib = mock(Invocation.Builder.class);
    whenNew(WrappedInvocationBuilder.class).withArguments(ib, requestURI).thenReturn(expectedWIb);
    final Response expectedResponse = mock(Response.class);
    // Stub exceptions thrown by the client 3 consecutive times then a successful
    when(mockFederationClient.post(Mockito.<WrappedInvocationBuilder>any(), Mockito.<X509FederationClient.X509FederationRequest>any(), Mockito.<BmcRequest>any())).thenThrow(new BmcException(409, "ServiceCode", "Exception 1", "RequestId")).thenThrow(new BmcException(409, "ServiceCode", "Exception 2", "RequestId")).thenThrow(new BmcException(409, "ServiceCode", "Exception 3", "RequestId")).thenReturn(expectedResponse);
    // Method under test.
    final Response actualResponse = clientUnderTest.makeCall(ib, requestURI, mock(X509FederationClient.X509FederationRequest.class));
    assertEquals("Response should be equal", expectedResponse, actualResponse);
    verify(mockFederationClient, times(4)).post(wrappedIbCaptor.capture(), isA(X509FederationClient.X509FederationRequest.class), isA(BmcRequest.class));
    final List<WrappedInvocationBuilder> wrappedIbsFromInvocation = wrappedIbCaptor.getAllValues();
    assertFalse("Captured list of WrappedInvocationBuilder should not be empty", wrappedIbsFromInvocation.isEmpty());
    assertEquals("Captured list of WrappedInvocationBuilder size should be 4", 4, /* expected number of captures */
    wrappedIbsFromInvocation.size());
    for (WrappedInvocationBuilder actualWib : wrappedIbsFromInvocation) {
        assertEquals("Captured WIB should be the same", expectedWIb, actualWib);
    }
}
Also used : Response(javax.ws.rs.core.Response) BmcException(com.oracle.bmc.model.BmcException) Invocation(javax.ws.rs.client.Invocation) BmcRequest(com.oracle.bmc.requests.BmcRequest) URI(java.net.URI) WrappedInvocationBuilder(com.oracle.bmc.http.internal.WrappedInvocationBuilder) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 3 with BmcException

use of com.oracle.bmc.model.BmcException in project oci-java-sdk by oracle.

the class DnsExample method patchZoneRecords.

/**
 * In addition to updates, we can use the patch operation to add and remove records from the zone without
 * having to send through the complete list of records each time. In this example, we'll remove the existing
 * TXT record that updateZoneRecords() added, and add a new one in
 */
private static void patchZoneRecords(final Dns client, final String zoneName, final String compartmentId) {
    final List<Record> allZoneRecords = getZoneRecords(client, GetZoneRecordsRequest.builder().zoneNameOrId(zoneName).zoneVersion(getZone(client, zoneName).getVersion()));
    Record txtRecord = null;
    for (Record r : allZoneRecords) {
        if (r.getRtype().equals("TXT")) {
            txtRecord = r;
            break;
        }
    }
    if (txtRecord == null) {
        throw new NullPointerException("Expected to find a TXT record in the list of zone records");
    }
    final List<RecordOperation> patchAddRemoveTxtRecord = new ArrayList<>();
    patchAddRemoveTxtRecord.add(RecordOperation.builder().domain(zoneName).recordHash(txtRecord.getRecordHash()).rtype("TXT").rdata(txtRecord.getRdata()).operation(RecordOperation.Operation.Remove).build());
    patchAddRemoveTxtRecord.add(RecordOperation.builder().domain(zoneName).rtype("TXT").rdata("Patch add new data").ttl(60).operation(RecordOperation.Operation.Remove).build());
    client.patchZoneRecords(PatchZoneRecordsRequest.builder().zoneNameOrId(zoneName).compartmentId(compartmentId).patchZoneRecordsDetails(PatchZoneRecordsDetails.builder().items(patchAddRemoveTxtRecord).build()).build());
    final List<Record> recordsAfterPatch = getZoneRecords(client, GetZoneRecordsRequest.builder().zoneNameOrId(zoneName).zoneVersion(getZone(client, zoneName).getVersion()));
    System.out.println();
    System.out.println("Zone records after patch");
    System.out.println("==========================");
    System.out.println(recordsAfterPatch);
    // As part of patch operations, we can also specify preconditions (REQUIRE - data must be present, and
    // PROHIBIT - data must not be present) which must be met for the operation to succeed.
    // 
    // Note that currently (as of 6 February 2018) sending through rdata or a record hash as part of a
    // precondition is not supported
    final List<RecordOperation> failingPatchOperation = new ArrayList<>();
    // This will fail as nothing matches this criteria
    failingPatchOperation.add(RecordOperation.builder().domain("testsubdomain1." + zoneName).rtype("A").rrsetVersion("1234567").operation(RecordOperation.Operation.Require).build());
    failingPatchOperation.add(RecordOperation.builder().domain("testsubdomain1." + zoneName).rtype("A").rdata("127.0.0.2").ttl(1800).operation(RecordOperation.Operation.Add).build());
    try {
        client.patchZoneRecords(PatchZoneRecordsRequest.builder().zoneNameOrId(zoneName).compartmentId(compartmentId).patchZoneRecordsDetails(PatchZoneRecordsDetails.builder().items(failingPatchOperation).build()).build());
    } catch (BmcException e) {
        System.out.println(String.format("Patch failed with BmcException of status: %d", e.getStatusCode()));
    }
    // This operation will succeed since we're asking that something matching the criteria doesn't exist (PROHIBIT). Note
    // also that the TTL will be applied to all other A records in the domain (i.e. our existing A record will have its
    // TTL changed to 2100)
    final List<RecordOperation> successfulPatchOperation = new ArrayList<>();
    successfulPatchOperation.add(RecordOperation.builder().domain("testsubdomain1." + zoneName).rtype("A").rrsetVersion("1234567").operation(RecordOperation.Operation.Prohibit).build());
    successfulPatchOperation.add(RecordOperation.builder().domain("testsubdomain1." + zoneName).rtype("A").rdata("127.0.0.2").ttl(2000).operation(RecordOperation.Operation.Add).build());
    client.patchZoneRecords(PatchZoneRecordsRequest.builder().zoneNameOrId(zoneName).compartmentId(compartmentId).patchZoneRecordsDetails(PatchZoneRecordsDetails.builder().items(patchAddRemoveTxtRecord).build()).build());
    final List<Record> recordsAfterPatchWithPreconditions = getZoneRecords(client, GetZoneRecordsRequest.builder().zoneNameOrId(zoneName).zoneVersion(getZone(client, zoneName).getVersion()));
    System.out.println();
    System.out.println("Zone records after patch with preconditions");
    System.out.println("==========================");
    System.out.println(recordsAfterPatchWithPreconditions);
}
Also used : BmcException(com.oracle.bmc.model.BmcException) ArrayList(java.util.ArrayList) RecordOperation(com.oracle.bmc.dns.model.RecordOperation) Record(com.oracle.bmc.dns.model.Record)

Example 4 with BmcException

use of com.oracle.bmc.model.BmcException in project oci-java-sdk by oracle.

the class GetInstancePublicIpExample method main.

public static void main(String[] args) throws Exception {
    // TODO: Fill in these values
    String instanceId = "SOME OCID";
    String compartmentId = "SOME OCID";
    String configurationFilePath = "~/.oci/config";
    String profile = "DEFAULT";
    // Configuring the AuthenticationDetailsProvider. It's assuming there is a default OCI config file
    // "~/.oci/config", and a profile in that config with the name "DEFAULT". Make changes to the following
    // line if needed and use ConfigFileReader.parse(CONFIG_LOCATION, profile);
    final ConfigFileReader.ConfigFile configFile = ConfigFileReader.parseDefault();
    final AuthenticationDetailsProvider provider = new ConfigFileAuthenticationDetailsProvider(configFile);
    ComputeClient computeClient = new ComputeClient(provider);
    VirtualNetworkClient vcnClient = new VirtualNetworkClient(provider);
    computeClient.setRegion(Region.US_PHOENIX_1);
    vcnClient.setRegion(Region.US_PHOENIX_1);
    // Account for multiple VNICs being attached to the instance
    Iterable<VnicAttachment> vnicAttachmentsIterable = computeClient.getPaginators().listVnicAttachmentsRecordIterator(ListVnicAttachmentsRequest.builder().compartmentId(compartmentId).instanceId(instanceId).build());
    List<String> vnicIds = new ArrayList<>();
    for (VnicAttachment va : vnicAttachmentsIterable) {
        vnicIds.add(va.getVnicId());
    }
    final Set<String> publicIps = new HashSet<>();
    for (String vnicId : vnicIds) {
        GetVnicResponse getVnicResponse = vcnClient.getVnic(GetVnicRequest.builder().vnicId(vnicId).build());
        if (getVnicResponse.getVnic().getPublicIp() != null) {
            publicIps.add(getVnicResponse.getVnic().getPublicIp());
        }
        /*
             * Handles the scenario where public IP addresses are assigned to
             * secondary private IPs on the VNIC. First we find all private IPs
             * associated with the VNIC and for each of those try and find the
             * public IP (if any) which has been associated with the private IP
             */
        Iterable<PrivateIp> privateIpsIterable = vcnClient.getPaginators().listPrivateIpsRecordIterator(ListPrivateIpsRequest.builder().vnicId(vnicId).build());
        for (PrivateIp privateIp : privateIpsIterable) {
            try {
                GetPublicIpByPrivateIpIdResponse getPublicIpResponse = vcnClient.getPublicIpByPrivateIpId(GetPublicIpByPrivateIpIdRequest.builder().getPublicIpByPrivateIpIdDetails(GetPublicIpByPrivateIpIdDetails.builder().privateIpId(privateIp.getId()).build()).build());
                publicIps.add(getPublicIpResponse.getPublicIp().getIpAddress());
            } catch (BmcException e) {
                // A 404 is expected if the private IP address does not have a public IP
                if (e.getStatusCode() != 404) {
                    System.out.println(String.format("Exception when retriving public IP for private IP %s (%s)", privateIp.getId(), privateIp.getIpAddress()));
                } else {
                    System.out.println(String.format("No public IP for private IP %s (%s)", privateIp.getId(), privateIp.getIpAddress()));
                }
            }
        }
    }
    for (String publicIp : publicIps) {
        System.out.println(publicIp);
    }
    computeClient.close();
    vcnClient.close();
}
Also used : BmcException(com.oracle.bmc.model.BmcException) AuthenticationDetailsProvider(com.oracle.bmc.auth.AuthenticationDetailsProvider) ConfigFileAuthenticationDetailsProvider(com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider) ArrayList(java.util.ArrayList) ComputeClient(com.oracle.bmc.core.ComputeClient) VnicAttachment(com.oracle.bmc.core.model.VnicAttachment) PrivateIp(com.oracle.bmc.core.model.PrivateIp) ConfigFileReader(com.oracle.bmc.ConfigFileReader) VirtualNetworkClient(com.oracle.bmc.core.VirtualNetworkClient) GetPublicIpByPrivateIpIdResponse(com.oracle.bmc.core.responses.GetPublicIpByPrivateIpIdResponse) GetVnicResponse(com.oracle.bmc.core.responses.GetVnicResponse) ConfigFileAuthenticationDetailsProvider(com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider) HashSet(java.util.HashSet)

Example 5 with BmcException

use of com.oracle.bmc.model.BmcException in project oci-java-sdk by oracle.

the class EventsServiceExample method deleteRule.

/**
 * Delete a Rule
 * @param ruleId OCID of the Rule to be deleted.
 */
private void deleteRule(final String ruleId) {
    final DeleteRuleRequest deleteRuleRequest = DeleteRuleRequest.builder().ruleId(ruleId).build();
    try {
        eventsClient.deleteRule(deleteRuleRequest);
        System.out.println("Rule " + ruleId + "was deleted");
    } catch (final BmcException e) {
        System.out.println("Failed to delete rule " + ruleId);
        throw e;
    }
}
Also used : BmcException(com.oracle.bmc.model.BmcException) DeleteRuleRequest(com.oracle.bmc.events.requests.DeleteRuleRequest)

Aggregations

BmcException (com.oracle.bmc.model.BmcException)37 Test (org.junit.Test)15 Response (javax.ws.rs.core.Response)9 GetObjectRequest (com.oracle.bmc.objectstorage.requests.GetObjectRequest)5 BmcRequest (com.oracle.bmc.requests.BmcRequest)5 IOException (java.io.IOException)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 WrappedInvocationBuilder (com.oracle.bmc.http.internal.WrappedInvocationBuilder)4 CreateMultipartUploadRequest (com.oracle.bmc.objectstorage.requests.CreateMultipartUploadRequest)4 ExecutorService (java.util.concurrent.ExecutorService)4 Invocation (javax.ws.rs.client.Invocation)4 ConfigFileReader (com.oracle.bmc.ConfigFileReader)3 AuthenticationDetailsProvider (com.oracle.bmc.auth.AuthenticationDetailsProvider)3 ConfigFileAuthenticationDetailsProvider (com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider)3 ObjectStorage (com.oracle.bmc.objectstorage.ObjectStorage)3 X509CertificateSupplier (com.oracle.bmc.auth.X509CertificateSupplier)2 AbortMultipartUploadRequest (com.oracle.bmc.objectstorage.requests.AbortMultipartUploadRequest)2 CommitMultipartUploadRequest (com.oracle.bmc.objectstorage.requests.CommitMultipartUploadRequest)2 PutObjectRequest (com.oracle.bmc.objectstorage.requests.PutObjectRequest)2 UploadPartRequest (com.oracle.bmc.objectstorage.requests.UploadPartRequest)2