Search in sources :

Example 66 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project keepass2android by PhilippC.

the class GoogleDriveFileStorage method convertException.

private Exception convertException(Exception e) {
    logDebug("Exception: " + e.toString());
    e.printStackTrace();
    if (UserRecoverableAuthIOException.class.isAssignableFrom(e.getClass())) {
        logDebug("clearing account data.");
        // this is not really nice because it removes data from the cache which might still be valid but we don't have the account name here...
        mAccountData.clear();
    }
    if (GoogleJsonResponseException.class.isAssignableFrom(e.getClass())) {
        GoogleJsonResponseException jsonEx = (GoogleJsonResponseException) e;
        if (jsonEx.getDetails().getCode() == 404)
            return new FileNotFoundException(jsonEx.getMessage());
    }
    return e;
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) FileNotFoundException(java.io.FileNotFoundException)

Example 67 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project teammates by TEAMMATES.

the class EmailAccount method getRegistrationKeyFromGmail.

/**
 * Retrieve registration key sent to Gmail inbox. After retrieving, marks the email as read.
 *
 * @return registration key (null if cannot be found).
 */
public static String getRegistrationKeyFromGmail(String username, String courseName, String courseId) throws IOException, MessagingException {
    Gmail service = new GmailServiceMaker(username).makeGmailService();
    ListMessagesResponse listMessagesResponse;
    while (true) {
        try {
            // Get last 5 emails received by the user as there may be other emails received. However, this may fail
            // unexpectedly if there are 5 additional emails received excluding the one from TEAMMATES.
            listMessagesResponse = service.users().messages().list(username).setMaxResults(5L).setQ("is:UNREAD").execute();
            break;
        } catch (GoogleJsonResponseException e) {
            if (e.getDetails().getCode() == HttpStatusCodes.STATUS_CODE_FORBIDDEN) {
                System.out.println(e.getDetails().getMessage());
                service = new GmailServiceMaker(username, true).makeGmailService();
            } else {
                throw e;
            }
        }
    }
    final List<Message> messageStubs = listMessagesResponse.getMessages();
    if (isEmpty(messageStubs)) {
        return null;
    }
    for (Message messageStub : messageStubs) {
        final Message message = service.users().messages().get(username, messageStub.getId()).setFormat("raw").execute();
        final MimeMessage email = convertFromMessageToMimeMessage(message);
        if (isStudentCourseJoinRegistrationEmail(email, courseName, courseId)) {
            final String body = getTextFromEmail(email);
            markMessageAsRead(service, username, messageStub);
            return getKey(body);
        }
    }
    return null;
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) ListMessagesResponse(com.google.api.services.gmail.model.ListMessagesResponse) MimeMessage(javax.mail.internet.MimeMessage) Message(com.google.api.services.gmail.model.Message) Gmail(com.google.api.services.gmail.Gmail) MimeMessage(javax.mail.internet.MimeMessage)

Example 68 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project cloudbreak by hortonworks.

the class GcpInstanceResourceBuilder method build.

@Override
public List<CloudResource> build(GcpContext context, long privateId, AuthenticatedContext auth, Group group, Image image, List<CloudResource> buildableResource, Map<String, String> customTags) throws Exception {
    InstanceTemplate template = group.getReferenceInstanceConfiguration().getTemplate();
    String projectId = context.getProjectId();
    Location location = context.getLocation();
    boolean noPublicIp = context.getNoPublicIp();
    Compute compute = context.getCompute();
    List<CloudResource> computeResources = context.getComputeResources(privateId);
    List<AttachedDisk> listOfDisks = new ArrayList<>();
    listOfDisks.addAll(getBootDiskList(computeResources, projectId, location.getAvailabilityZone()));
    listOfDisks.addAll(getAttachedDisks(computeResources, projectId, location.getAvailabilityZone()));
    Instance instance = new Instance();
    instance.setMachineType(String.format("https://www.googleapis.com/compute/v1/projects/%s/zones/%s/machineTypes/%s", projectId, location.getAvailabilityZone().value(), template.getFlavor()));
    instance.setName(buildableResource.get(0).getName());
    instance.setCanIpForward(Boolean.TRUE);
    instance.setNetworkInterfaces(getNetworkInterface(context.getNetworkResources(), computeResources, location.getRegion(), group, compute, projectId, noPublicIp));
    instance.setDisks(listOfDisks);
    Scheduling scheduling = new Scheduling();
    boolean preemptible = false;
    if (template.getParameter(PREEMPTIBLE, Boolean.class) != null) {
        preemptible = template.getParameter(PREEMPTIBLE, Boolean.class);
    }
    scheduling.setPreemptible(preemptible);
    instance.setScheduling(scheduling);
    Tags tags = new Tags();
    List<String> tagList = new ArrayList<>();
    Map<String, String> labels = new HashMap<>();
    String groupname = group.getName().toLowerCase().replaceAll("[^A-Za-z0-9 ]", "");
    tagList.add(groupname);
    Map<String, String> instanceTag = defaultCostTaggingService.prepareInstanceTagging();
    for (Entry<String, String> entry : instanceTag.entrySet()) {
        tagList.add(String.format("%s-%s", entry.getKey(), entry.getValue()));
        labels.put(entry.getKey(), entry.getValue());
    }
    tagList.add(GcpStackUtil.getClusterTag(auth.getCloudContext()));
    tagList.add(GcpStackUtil.getGroupClusterTag(auth.getCloudContext(), group));
    customTags.forEach((key, value) -> tagList.add(key + '-' + value));
    labels.putAll(customTags);
    tags.setItems(tagList);
    instance.setTags(tags);
    instance.setLabels(labels);
    Metadata metadata = new Metadata();
    metadata.setItems(new ArrayList<>());
    Items sshMetaData = new Items();
    sshMetaData.setKey("ssh-keys");
    sshMetaData.setValue(group.getInstanceAuthentication().getLoginUserName() + ':' + group.getInstanceAuthentication().getPublicKey());
    Items blockProjectWideSsh = new Items();
    blockProjectWideSsh.setKey("block-project-ssh-keys");
    blockProjectWideSsh.setValue("TRUE");
    Items startupScript = new Items();
    startupScript.setKey("startup-script");
    startupScript.setValue(image.getUserDataByType(group.getType()));
    metadata.getItems().add(sshMetaData);
    metadata.getItems().add(startupScript);
    metadata.getItems().add(blockProjectWideSsh);
    instance.setMetadata(metadata);
    Insert insert = compute.instances().insert(projectId, location.getAvailabilityZone().value(), instance);
    insert.setPrettyPrint(Boolean.TRUE);
    try {
        Operation operation = insert.execute();
        if (operation.getHttpErrorStatusCode() != null) {
            throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), buildableResource.get(0).getName());
        }
        return Collections.singletonList(createOperationAwareCloudResource(buildableResource.get(0), operation));
    } catch (GoogleJsonResponseException e) {
        throw new GcpResourceException(checkException(e), resourceType(), buildableResource.get(0).getName());
    }
}
Also used : Instance(com.google.api.services.compute.model.Instance) CloudInstance(com.sequenceiq.cloudbreak.cloud.model.CloudInstance) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Metadata(com.google.api.services.compute.model.Metadata) AttachedDisk(com.google.api.services.compute.model.AttachedDisk) Operation(com.google.api.services.compute.model.Operation) Insert(com.google.api.services.compute.Compute.Instances.Insert) Items(com.google.api.services.compute.model.Metadata.Items) Tags(com.google.api.services.compute.model.Tags) Scheduling(com.google.api.services.compute.model.Scheduling) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Compute(com.google.api.services.compute.Compute) GcpResourceException(com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException) CloudResource(com.sequenceiq.cloudbreak.cloud.model.CloudResource) InstanceTemplate(com.sequenceiq.cloudbreak.cloud.model.InstanceTemplate) Location(com.sequenceiq.cloudbreak.cloud.model.Location)

Example 69 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project cloudbreak by hortonworks.

the class GcpFirewallInternalResourceBuilder method build.

@Override
public CloudResource build(GcpContext context, AuthenticatedContext auth, Network network, Security security, CloudResource buildableResource) throws Exception {
    String projectId = context.getProjectId();
    Firewall firewall = new Firewall();
    Allowed allowed1 = new Allowed();
    allowed1.setIPProtocol("tcp");
    allowed1.setPorts(Collections.singletonList("1-65535"));
    Allowed allowed2 = new Allowed();
    allowed2.setIPProtocol("icmp");
    Allowed allowed3 = new Allowed();
    allowed3.setIPProtocol("udp");
    allowed3.setPorts(Collections.singletonList("1-65535"));
    firewall.setTargetTags(Collections.singletonList(GcpStackUtil.getClusterTag(auth.getCloudContext())));
    firewall.setAllowed(Arrays.asList(allowed1, allowed2, allowed3));
    firewall.setName(buildableResource.getName());
    if (isLegacyNetwork(network)) {
        Networks.Get networkRequest = context.getCompute().networks().get(projectId, getCustomNetworkId(network));
        com.google.api.services.compute.model.Network existingNetwork = networkRequest.execute();
        firewall.setSourceRanges(Collections.singletonList(existingNetwork.getIPv4Range()));
    } else if (isNewNetworkAndSubnet(network) || isNewSubnetInExistingNetwork(network)) {
        firewall.setSourceRanges(Collections.singletonList(network.getSubnet().getCidr()));
    } else {
        Get sn = context.getCompute().subnetworks().get(projectId, context.getLocation().getRegion().value(), getSubnetId(network));
        com.google.api.services.compute.model.Subnetwork existingSubnet = sn.execute();
        firewall.setSourceRanges(Collections.singletonList(existingSubnet.getIpCidrRange()));
    }
    firewall.setNetwork(String.format("https://www.googleapis.com/compute/v1/projects/%s/global/networks/%s", projectId, context.getParameter(GcpNetworkResourceBuilder.NETWORK_NAME, String.class)));
    Insert firewallInsert = context.getCompute().firewalls().insert(projectId, firewall);
    try {
        Operation operation = firewallInsert.execute();
        if (operation.getHttpErrorStatusCode() != null) {
            throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), buildableResource.getName());
        }
        return createOperationAwareCloudResource(buildableResource, operation);
    } catch (GoogleJsonResponseException e) {
        throw new GcpResourceException(checkException(e), resourceType(), buildableResource.getName());
    }
}
Also used : Networks(com.google.api.services.compute.Compute.Networks) Operation(com.google.api.services.compute.model.Operation) Insert(com.google.api.services.compute.Compute.Firewalls.Insert) Allowed(com.google.api.services.compute.model.Firewall.Allowed) Firewall(com.google.api.services.compute.model.Firewall) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Get(com.google.api.services.compute.Compute.Subnetworks.Get) GcpResourceException(com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException)

Example 70 with GoogleJsonResponseException

use of com.google.api.client.googleapis.json.GoogleJsonResponseException in project cloudbreak by hortonworks.

the class GcpNetworkResourceBuilder method build.

@Override
public CloudResource build(GcpContext context, AuthenticatedContext auth, Network network, Security security, CloudResource resource) throws Exception {
    if (!isExistingNetwork(network)) {
        Compute compute = context.getCompute();
        String projectId = context.getProjectId();
        com.google.api.services.compute.model.Network gcpNetwork = new com.google.api.services.compute.model.Network();
        gcpNetwork.setName(resource.getName());
        gcpNetwork.setAutoCreateSubnetworks(false);
        Insert networkInsert = compute.networks().insert(projectId, gcpNetwork);
        try {
            Operation operation = networkInsert.execute();
            if (operation.getHttpErrorStatusCode() != null) {
                throw new GcpResourceException(operation.getHttpErrorMessage(), resourceType(), resource.getName());
            }
            context.putParameter(NETWORK_NAME, resource.getName());
            return createOperationAwareCloudResource(resource, operation);
        } catch (GoogleJsonResponseException e) {
            throw new GcpResourceException(checkException(e), resourceType(), resource.getName());
        }
    }
    context.putParameter(NETWORK_NAME, resource.getName());
    return new Builder().cloudResource(resource).persistent(false).build();
}
Also used : Builder(com.sequenceiq.cloudbreak.cloud.model.CloudResource.Builder) Operation(com.google.api.services.compute.model.Operation) Insert(com.google.api.services.compute.Compute.Networks.Insert) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) Compute(com.google.api.services.compute.Compute) GcpStackUtil.isExistingNetwork(com.sequenceiq.cloudbreak.cloud.gcp.util.GcpStackUtil.isExistingNetwork) Network(com.sequenceiq.cloudbreak.cloud.model.Network) GcpResourceException(com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException)

Aggregations

GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)94 IOException (java.io.IOException)48 YouTube (com.google.api.services.youtube.YouTube)26 Credential (com.google.api.client.auth.oauth2.Credential)25 ArrayList (java.util.ArrayList)13 Operation (com.google.api.services.compute.model.Operation)12 Test (org.junit.Test)12 Compute (com.google.api.services.compute.Compute)11 Storage (com.google.api.services.storage.Storage)10 GcpResourceException (com.sequenceiq.cloudbreak.cloud.gcp.GcpResourceException)8 GcsOptions (org.apache.beam.sdk.extensions.gcp.options.GcsOptions)7 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)5 InputStreamContent (com.google.api.client.http.InputStreamContent)5 BackOff (com.google.api.client.util.BackOff)5 HashMap (java.util.HashMap)5 Objects (com.google.api.services.storage.model.Objects)4 GoogleCloudStorage (com.google.cloud.hadoop.gcsio.GoogleCloudStorage)4 HalException (com.netflix.spinnaker.halyard.core.error.v1.HalException)4 MediaHttpUploader (com.google.api.client.googleapis.media.MediaHttpUploader)3 MediaHttpUploaderProgressListener (com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener)3