Inital commit

This commit is contained in:
Tilman
2011-10-26 09:44:02 +02:00
commit 5971f4b417
1813 changed files with 737837 additions and 0 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,318 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.adminsettings;
import com.google.gdata.util.common.util.Base64;
import com.google.gdata.client.appsforyourdomain.adminsettings.AdminSettingsConstants;
import com.google.gdata.client.appsforyourdomain.adminsettings.DomainSettingsService;
import com.google.gdata.client.appsforyourdomain.adminsettings.DomainVerificationService;
import com.google.gdata.client.appsforyourdomain.adminsettings.EmailManagementService;
import com.google.gdata.client.appsforyourdomain.adminsettings.EncodeUtil;
import com.google.gdata.client.appsforyourdomain.adminsettings.SingleSignOnService;
import sample.util.SimpleCommandLineParser;
import com.google.gdata.data.appsforyourdomain.generic.GenericEntry;
import com.google.gdata.data.appsforyourdomain.generic.GenericFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A sample client for Admin Settings API. Consists of drivers to run these
* services: {@link DomainSettingsService} {@link SingleSignOnService}
* {@link DomainVerificationService} {@link EmailManagementService}
*
*
*
*/
public class AdminSettingsClient {
private static final Logger LOGGER = Logger.getLogger(AdminSettingsClient.class.getName());
/**
* run() does a demo run and performs all operations possible with the client
*
* @param adminEmail the email id of the administrator.
* @param password the administrator password.
* @param domainName the domain name to be configured.
*/
public static void runAccountSettings(String adminEmail, String password, String domainName) {
System.out.println("Intiating demo run");
try {
DomainSettingsService client =
new DomainSettingsService(adminEmail, password, domainName, "test");
System.out.println("Enter full path to logo file");
Scanner in = new Scanner(System.in);
String file = in.nextLine();
client.setDomainLogo(EncodeUtil.encodeBinaryFile(file));
String countryCode = client.getCountryCodeForDomain();
LOGGER.log(Level.INFO, "Retrieved CountryCode: " + countryCode);
String customerPIN = client.getCustomerPIN();
LOGGER.log(Level.INFO, "Retrieved customerPIN: " + customerPIN);
String defaultLanguage = client.getDefaultLanguage();
LOGGER.log(Level.INFO, "Retrieved defaultLanguage: " + defaultLanguage);
String domainCreationTime = client.getDomainCreationTime();
LOGGER.log(Level.INFO, "Retrieved domainCreationTime: " + domainCreationTime);
String domainEdition = client.getDomainEdition();
LOGGER.log(Level.INFO, "Retrieved domainEdition: " + domainEdition);
String domainSecondaryEmailAddress = client.getDomainSecondaryEmailAddress();
LOGGER.log(Level.INFO, "Retrieved domainSecondaryEmailAddress: "
+ domainSecondaryEmailAddress);
String domainVerificationStatus = client.getDomainVerificationStatus();
LOGGER.log(Level.INFO, "Retrieved domainVerificationStatus: " + domainVerificationStatus);
int maxUserCount = client.getMaxUserCount();
LOGGER.log(Level.INFO, "Retrieved maxUserCount: " + maxUserCount);
String organizationName = client.getOrganizationName();
LOGGER.log(Level.INFO, "Retrieved organizationName: " + organizationName);
String supportPin = client.getSupportPIN();
LOGGER.log(Level.INFO, "Retrieved supportPin: " + supportPin);
System.out.println("Enter a secondary email ID for your domain:");
String secondaryEmail = in.nextLine();
LOGGER.log(Level.INFO, "Changing secondary email address to admin email: " + secondaryEmail);
client.setDomainSecondaryEmailAddress(secondaryEmail);
LOGGER.log(Level.INFO, "Changed secondary email address to : "
+ client.getDomainSecondaryEmailAddress());
LOGGER.log(Level.INFO, "Changing organization name to newOrg:");
client.setOrganizationName("newOrg");
LOGGER.log(Level.INFO, "Changed organization name: " + client.getOrganizationName());
LOGGER.log(Level.INFO, "Changing default language to fr:");
client.setDefaultLanguage("fr");
LOGGER.log(Level.INFO, "Changed default language: " + client.getDefaultLanguage());
// Restore original values
client.setDefaultLanguage(defaultLanguage);
client.setDomainSecondaryEmailAddress(domainSecondaryEmailAddress);
client.setOrganizationName(organizationName);
} catch (AuthenticationException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (IllegalArgumentException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (ServiceException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (MalformedURLException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
/**
* A sample run for SSO settings API
*
* @param adminEmail the email id of the administrator.
* @param password the administrator password.
* @param domainName the domain name to be configured.
*/
public static void runSsoSettings(String adminEmail, String password, String domainName) {
try {
SingleSignOnService client =
new SingleSignOnService(adminEmail, password, domainName, "test");
final String key = Base64.encode(("-----BEGIN CERTIFICATE-----\n"
+ "MIIEbDCCA9WgAwIBAgIBCTANBgkqhkiG9w0BAQUFADCBjDELMAkGA1UEBhMCVVMx\n"
+ "ETAPBgNVBAgTCE5ldyBZb3JrMREwDwYDVQQHEwhOZXcgWW9yazEPMA0GA1UEChMG\n"
+ "R29vZ2xlMSQwIgYDVQQDFBtUaW0gRGllcmtzIENBIFtubyBzZWN1cml0eV0xIDAe\n"
+ "BgkqhkiG9w0BCQEWEWRpZXJrc0Bnb29nbGUuY29tMB4XDTA0MDQxNDIwMzM1NFoX\n"
+ "DTA1MDQxNDIwMzM1NFowQTEPMA0GA1UEChMGR29vZ2xlMRcwFQYDVQQLEw5TaW5n\n"
+ "bGUgU2lnbi1vbjEVMBMGA1UEAxMMTG9naW4gU2VydmVyMIIBtzCCASwGByqGSM44\n"
+ "BAEwggEfAoGBAKGpKYcoXxcgewIuAdDxT8QzSNI9I7Lja/LoueR1z7A/l0UWqZHO\n"
+ "6J8SyudgXFVxfkQEeYGbidsew2RMxvMl6pWMfqr/22eCqr9GPVkT7GVGqjAVdHVu\n"
+ "qJOPKSW7fQV3c82aj5g2qgkpwc1fUep8Cn1+Nz4ApCttVCSJD5kPtDTPAhUAo9jk\n"
+ "HrC8TH0kMFARmNbG5pizRS8CgYEAiB/TJmxCStDDMhDwo0ccnWgNo4oOQlMSeN46\n"
+ "Gb5YyVejeFBZSGni958ZcaaPW0Dg4VpbGxsQTSuF8P1BVY03fqimMd+dbRWSGgNy\n"
+ "YpkpdWBe21FnsSrnIrWnv/3K/7HMB7Xn4rEbhSvJF14I5TDuRN3lIOnIOKK6I5O9\n"
+ "QYfIfYoDgYQAAoGABPbEsbJS59Gj9556j9eAnGeLur56b98AGO7OFvYSoo9XcjoS\n"
+ "uYiFNhxu8MLzhkEqA6bqUif0mpl/d/VAXc74mdxaeg3vGb5MUGzdcr/mk9+32KYx\n"
+ "aX1hxn3UEN6WuypWe1eKuRVUzI/OepC88ib60XZHnkW9ByqqYXWdyGxW/G2jggEN\n"
+ "MIIBCTAJBgNVHRMEAjAAMCEGCWCGSAGG+EIBDQQUFhJHb29nbGUgLSBEaWVya3Mg\n"
+ "Q0EwHQYDVR0OBBYEFISoKKfKZlD6QIGqX60VCQA07sGLMIG5BgNVHSMEgbEwga6A\n"
+ "FK517Zhw+C2LH0rAjGRdEx61PYsIoYGSpIGPMIGMMQswCQYDVQQGEwJVUzERMA8G\n"
+ "A1UECBMITmV3IFlvcmsxETAPBgNVBAcTCE5ldyBZb3JrMQ8wDQYDVQQKEwZHb29n\n"
+ "bGUxJDAiBgNVBAMUG1RpbSBEaWVya3MgQ0EgW25vIHNlY3VyaXR5XTEgMB4GCSqG\n"
+ "SIb3DQEJARYRZGllcmtzQGdvb2dsZS5jb22CAQAwDQYJKoZIhvcNAQEFBQADgYEA\n"
+ "qwjvp27Xq1lp2ZyVWrGj8A3vuwUhsA2xGHvw4FTk4bCPwuuErugP/pwNl2582KNR\n"
+ "bjl1Vnz6zXkW1T4855EFWOZZkhIrvLGTRIoyQODCoW/Zd+3e7CfTvPdmJJNaVpD7\n"
+ "1RMPC45yjolVq4JLTT9/y6/+/5Nnn7oELnXRgDiMAR0=\n"
+ "-----END CERTIFICATE-----").getBytes());
LOGGER.log(Level.INFO, "Retrieving SSO Settings: \n"
+ client.getSsoSettings().getAllProperties());
LOGGER.log(Level.INFO, "Retrieving SSO Key: \n"
+ client.getSsoSigningKey().getAllProperties());
LOGGER.log(Level.INFO, "Updating SSO Key: \n"
+ client.updateSsoSigningKey(key).getAllProperties());
} catch (AuthenticationException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (IllegalArgumentException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (ServiceException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (MalformedURLException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
/**
*
* @param adminEmail the email id of the administrator.
* @param adminPassword the administrator password.
* @param domainName the domain name to be configured.
*/
public static void runDomainVerificationService(String adminEmail, String password,
String domainName) {
try {
DomainVerificationService client =
new DomainVerificationService(adminEmail, password, domainName, "test");
GenericEntry entry = client.retrieveCnameVerificationStatus();
LOGGER.log(Level.INFO, "Retrieving CNAME verification status: " + entry.getAllProperties());
entry = client.updateVerifiedStatus(entry, true);
LOGGER.log(Level.INFO, "Updated CNAME verfication status: " + entry.getAllProperties());
entry = client.retrieveMxVerificationStatus();
LOGGER.log(Level.INFO, "Retrieving MX verification status: " + entry.getAllProperties());
entry = client.updateVerifiedStatus(entry, true);
LOGGER.log(Level.INFO, "Updating MX verfication status: " + entry.getAllProperties());
} catch (AuthenticationException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (IllegalArgumentException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (ServiceException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (MalformedURLException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
/**
*
* @param adminEmail the email id of the administrator.
* @param adminPassword the administrator password.
* @param domainName the domain name to be configured.
*/
public static void runEmailManagementService(
String adminEmail, String password, String domainName) {
try {
EmailManagementService client =
new EmailManagementService(adminEmail, password, domainName, "test");
GenericEntry entry = client.retrieveOutboundGatewaySettings();
LOGGER.log(Level.INFO, "Outbound gateway settings" + entry.getAllProperties());
client.updateOutboundGatewaySettings(AdminSettingsConstants.TEST_EMAIL_ROUTE,
AdminSettingsConstants.TEST_SMTPMODE);
GenericFeed feed = client.retrieveEmailRoutingSettings();
List<GenericEntry> entries = feed.getEntries();
for (GenericEntry genericEntry : entries) {
LOGGER.log(Level.INFO, "Email Routing Settings" + genericEntry.getAllProperties());
LOGGER.log(Level.INFO, "Email Routing Settings" + genericEntry.getId());
// update settings
LOGGER.log(Level.INFO, "Updating Routing Settings");
genericEntry.removeProperty("routeEnabled");
genericEntry.addProperty("routeEnabled", String.valueOf(false));
genericEntry.update();
}
} catch (AuthenticationException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (IllegalArgumentException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (ServiceException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (MalformedURLException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
/**
* @param args
*/
public static void main(String[] args) {
SimpleCommandLineParser parser = new SimpleCommandLineParser(args);
String adminEmail = parser.getValue("admin_email", "email", "e");
String adminPassword = parser.getValue("admin_password", "pass", "p");
String domain = parser.getValue("domain", "domain", "d");
boolean help = parser.containsKey("help", "h");
if (help || (adminEmail == null) || (adminPassword == null) || (domain == null)) {
usage();
System.exit(1);
}
System.out.println("WARNING: This sample modifies the admin settings of a domain."
+ "Use a TEST domain only.\nDo you want to continue (y/n):");
Scanner in = new Scanner(System.in);
String continueDemo = in.next();
if (!String.valueOf(continueDemo).equalsIgnoreCase("y")) {
System.exit(1);
}
LOGGER.log(Level.INFO, "-----------------Domain Settings Demo-------------");
runAccountSettings(adminEmail, adminPassword, domain);
LOGGER.log(Level.INFO, "-------------------SSO Settings Demo--------------");
runSsoSettings(adminEmail, adminPassword, domain);
LOGGER.log(Level.INFO, "--------------Verification Settings Demo----------");
runDomainVerificationService(adminEmail, adminPassword, domain);
LOGGER.log(Level.INFO, "---------------Email Management Demo--------------");
runEmailManagementService(adminEmail, adminPassword, domain);
}
/*
* Prints the command line usage of this sample application.
*/
private static void usage() {
System.out.println("Usage: java AdminSettngsClient"
+ " --admin_email [email] --admin_password [pass] --domain [domain]");
System.out.println("\nA simple application that performs domain configuration \n"
+ "on the given domain using the provided admin username and password.\n"
+ "WARNING: Please use a test domain for the sample run.");
}
}
@@ -0,0 +1,249 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.audit;
import com.google.gdata.client.appsforyourdomain.audit.AccountInfo;
import com.google.gdata.client.appsforyourdomain.audit.AuditService;
import com.google.gdata.client.appsforyourdomain.audit.MailBoxDumpRequest;
import com.google.gdata.client.appsforyourdomain.audit.MailMonitor;
import com.google.gdata.data.appsforyourdomain.AppsForYourDomainErrorCode;
import com.google.gdata.data.appsforyourdomain.AppsForYourDomainException;
import com.google.gdata.data.appsforyourdomain.generic.GenericEntry;
import com.google.gdata.data.appsforyourdomain.generic.GenericFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A sample client for Google Apps Audit API service that helps you to audit
* user's emails, email drafts, and archived chats.
*
*
*
*/
public class AuditSampleClient {
private static Logger LOGGER = Logger.getLogger(AuditSampleClient.class.toString());
/**
* Google Apps Audit API sample run.
*
* Usage: java AuditSampleClient admin@example.com adminpassword domain
* srcUserName destUserName
*
*/
public static void main(String[] args) {
AuditService service = null;
try {
if (args.length != 5) {
System.out.println("Usage: java AuditSampleClient <admin@example.com> <adminpassword> "
+ "<domain> <srcUserName> <destUserName>");
System.out.println("A simple demo for Audit API features like managing email \n"
+ "monitors, mailbox dump requests, retrieving account info and uploading \n"
+ "domain key for encrypting files. The demo creates mail monitor for 'srcUserName' \n"
+ "with 'destUserName' as the auditor and uses 'srcUserName' as the test user for \n"
+ "the other listed operations above");
System.exit(1);
}
String adminEmail = args[0];
String adminPassword = args[1];
String domain = args[2];
String user = args[3];
String destUser = args[4];
//A sample base64 encoded PGP format key.
String sampleKey =
"LS0tLS1CRUdJTiBQR1AgUFVCTElDIEtFWSBCTE9DSy0tLS0tDQpWZXJzaW9uOiBHbn"
+ "VQRyB2MS40LjEwIChHTlUvTGludXgpDQoNCm1RRU5CRXJXYUQ0QkNBQ3QybmdmczYv"
+ "K1FPR1lieE5iYzNnTG5YSHRxcDdOVFRYTlc0U0pvKy9BMW9VWm9HeEENClF4NnpGWG"
+ "hRLzhNWFc2Nis4U1RTMVlxTkpPQVJGdGpiSUtQd2pyZGN1a2RQellWS0dacmUwUmF4"
+ "Q25NeUNWKzYNCkY0WU5RRDFVZWdIVHUyd0NHUjF1aVlPZkx4VWE3L2RvNnMzMVdSVE"
+ "g4dmJ0aVBZOS82b2JFSXhEakR6S0lxWU8NCnJ2UkRXcUFMQllrbE9rSjNIYmdmeWw0"
+ "MkVzbkxpQWhTK2RNczJQQ0RpMlgwWkpDUFo4ZVRqTHNkQXRxVlpKK1INCldDMUozVU"
+ "R1RmZtY3BzRFlSdFVMOXc2WU10bGFwQys5bW1KM0FCRUJBQUcwVjBSaGMyaGxjaUJV"
+ "WlhOMElDaFUNCmRHVnlNa0JrWVhOb1pYSXRhSGxrTFhSbGMzUXVZMjl0UG9rQk9BUV"
+ "RBUUlBSWdVQ1N0Wm9QZ0liRFFZTENRZ0gNCmsxOVFja1Rwd0Jkc2tFWXVtRnZtV3Zl"
+ "NVVYMlNWVjdmek9DMG5adGdGeHRaR2xKaEdtanNBM3J4RlRsYitJcmENCldaYXlYQ1"
+ "dZaUN6ZDdtOXo1L0t5R0QyR0ZUSy85NG1kbTI1TjZHWGgvYjM1cElGWlhCSS9yWmpy"
+ "WXJoWVJCRnUNCkd0ekdGSXc5QUFuRnlVekVVVVZmUFdVdEJlNXlITVc1NEM2MG5Iaz"
+ "V4WUlhNnFGaGlMcDRQWXFaQ3JZWDFpSXMNCmZSUk9GQT09DQo9U1RIcg0KLS0tLS1F"
+ "TkQgUEdQIFBVQkxJQyBLRVkgQkxPQ0stLS0tLQ==";
service = new AuditService(adminEmail, adminPassword, domain, "audit-test-" + domain);
LOGGER.log(Level.INFO, "\n-------------uploadPublicKey-------------");
GenericEntry sampleEntry = null;
sampleEntry = service.uploadPublicKey(sampleKey);
LOGGER.log(Level.INFO, "UploadedKey - " + sampleEntry.getAllProperties());
// retrieve all MailboxDump requests with fromDate query.
LOGGER.log(Level.INFO, "\n------retrieveAllMailboxDumpRequests with fromDate---- ");
Calendar c = Calendar.getInstance();
List<GenericEntry> entries = service.retrieveAllMailboxDumpRequests(c.getTime());
for (GenericEntry sampleEntry2 : entries) {
MailBoxDumpRequest request = new MailBoxDumpRequest(sampleEntry2);
LOGGER.log(Level.INFO, "All requests -" + sampleEntry2.getAllProperties().toString());
}
/*
* retrieve all MailboxDump requests without fromDate query. This will
* retrieve all requests made in the last 3 weeks.
*/
LOGGER.log(Level.INFO, "\n------------retrieveAllMailboxDumpRequests-------------");
entries = service.retrieveAllMailboxDumpRequests(null);
for (GenericEntry sampleEntry2 : entries) {
MailBoxDumpRequest request = new MailBoxDumpRequest(sampleEntry2);
LOGGER.log(Level.INFO, "All requests -" + sampleEntry2.getAllProperties().toString());
}
// Create MailboxDumpRequest
MailBoxDumpRequest request = new MailBoxDumpRequest();
request.setAdminEmailAddress(adminEmail);
c.add(Calendar.MONTH, -1);
request.setEndDate(c.getTime());
c.add(Calendar.MONTH, -1);
request.setBeginDate(c.getTime());
request.setPackageContent("FULL_MESSAGE");
request.setSearchQuery("in:chats");
request.setIncludeDeleted(false);
request.setUserEmailAddress(user + "@" + domain);
LOGGER.log(Level.INFO, "\n-------------createMailboxDumpRequest-------------");
sampleEntry = service.createMailboxDumpRequest(request);
LOGGER.log(Level.INFO, "\nCreated request - " + sampleEntry.getAllProperties().toString());
String createdId = sampleEntry.getProperty("requestId");
LOGGER.log(Level.INFO, "\n-------------retrieveMailboxDumpRequest-------------");
sampleEntry = service.retrieveMailboxDumpRequest(user, createdId);
LOGGER.log(Level.INFO, "\nRetrieved dump request - "
+ sampleEntry.getAllProperties().toString());
LOGGER.log(Level.INFO, "\n-------------deleteMailboxDumpRequest-------------");
boolean isDeleted = service.deleteMailboxDumpRequest(user, createdId);
LOGGER.log(Level.INFO, "Deleted mailbox dump request - " + isDeleted);
MailMonitor monitor = new MailMonitor();
c = Calendar.getInstance();
c.add(Calendar.MONTH, 1);
monitor.setBeginDate(c.getTime());
c.add(Calendar.MONTH, 1);
monitor.setEndDate(c.getTime());
monitor.setDestUserName(destUser);
monitor.setIncomingEmailMonitorLevel("FULL_MESSAGE");
monitor.setOutgoingEmailMonitorLevel("HEADER_ONLY");
monitor.setChatMonitorLevel("FULL_MESSAGE");
monitor.setDraftMonitorLevel("FULL_MESSAGE");
LOGGER.log(Level.INFO, "\n-------------createMailMonitor-------------");
LOGGER.log(Level.INFO, "\nCreating mail monitor for the user: " + user);
service.createMailMonitor(user, monitor);
// Retrieve all monitors for the user
LOGGER.log(Level.INFO, "\n-------------retrieveMonitors-------------");
LOGGER.log(Level.INFO, "\nRetrieving monitors for the user: " + user);
GenericFeed feed = service.retrieveMonitors(user);
for (GenericEntry entry : feed.getEntries()) {
monitor = new MailMonitor(entry);
LOGGER.log(Level.INFO, "Request Id: " + monitor.getRequestId());
LOGGER.log(Level.INFO, "Destination User: " + monitor.getDestUserName());
LOGGER.log(Level.INFO, "Monitor Begin Date: " + monitor.getBeginDate());
LOGGER.log(Level.INFO, "Monitor End Date: " + monitor.getEndDate());
LOGGER.log(Level.INFO, "Outgoing Email Monitor Level: "
+ monitor.getOutgoingEmailMonitorLevel());
LOGGER.log(Level.INFO, "Incoming Email Monitor Level: "
+ monitor.getIncomingEmailMonitorLevel());
LOGGER.log(Level.INFO, "Draft Email Monitor Level: " + monitor.getDraftMonitorLevel());
LOGGER.log(Level.INFO, "Chat Monitor Level: " + monitor.getChatMonitorLevel());
}
// Delete the monitor for the user
LOGGER.log(Level.INFO, "\n-------------deleteMonitor-------------");
LOGGER.log(Level.INFO, "Deleting monitor for the user...");
service.deleteMonitor(user, destUser);
//Account Info requests
LOGGER.log(Level.INFO, "\n-------------createAccountInfoRequest-------------");
sampleEntry = service.createAccountInfoRequest(user);
LOGGER.log(Level.INFO, sampleEntry.getAllProperties().toString());
AccountInfo info = new AccountInfo(sampleEntry);
LOGGER.log(Level.INFO, "\n-------------retrieveAccountInfoRequest-------------");
sampleEntry = service.retrieveAccountInfoRequest(user, info.getRequestId());
info = new AccountInfo(sampleEntry);
LOGGER.log(Level.INFO, info.getRequestId() + " : " + info.getStatus());
if (info.getStatus().equalsIgnoreCase("COMPLETED")) {
for ( String url : info.getFileUrls())
LOGGER.log(Level.INFO, "File: " + url);
}
// retrieve all account info requests from the given date.
LOGGER.log(Level.INFO, "\n------retrieveAllAccountInfoRequests with fromDate-----");
Calendar temp = Calendar.getInstance();
temp.add(Calendar.MONTH, -1);
entries = service.retrieveAllAccountInfoRequests(temp.getTime());
for (GenericEntry entry : entries) {
LOGGER.log(Level.INFO, entry.getAllProperties().toString());
}
/*
* retrieve all account info requests without fromDate query. This will
* retrieve all requests made in the last 3 weeks.
*/
LOGGER.log(Level.INFO, "\n-------------retrieveAllAccountInfoRequests-------------");
entries = service.retrieveAllAccountInfoRequests(null);
for (GenericEntry entry : entries) {
LOGGER.log(Level.INFO, entry.getAllProperties().toString());
}
LOGGER.log(Level.INFO, "\n-------------deleteAccountInfoRequest-------------");
try {
service.deleteAccountInfoRequest(user, info.getRequestId());
} catch (AppsForYourDomainException e) {
if (e.getErrorCode() == AppsForYourDomainErrorCode.InvalidValue) {
LOGGER.log(Level.INFO, e.getMessage());
} else {
e.printStackTrace();
}
}
LOGGER.log(Level.INFO, "End Audit API demo run");
} catch (AuthenticationException e) {
LOGGER.log(Level.SEVERE, "Authentication Error: " + e.getMessage(), e);
} catch (AppsForYourDomainException e) {
LOGGER.log(Level.SEVERE, "AppsForYourDomain Error: " + e.getMessage(), e);
} catch (MalformedURLException e) {
LOGGER.log(Level.SEVERE, "Malformed URL Error: " + e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Network I/O Error: " + e.getMessage(), e);
} catch (ServiceException e) {
LOGGER.log(Level.SEVERE, "Google Data Service Error: " + e.getMessage(), e);
}
}
}
@@ -0,0 +1,254 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings;
import com.google.gdata.client.appsforyourdomain.gmailsettings.GmailFilterService;
import sample.util.SimpleCommandLineParser;
import com.google.gdata.data.appsforyourdomain.generic.GenericEntry;
import com.google.gdata.data.appsforyourdomain.generic.GenericFeed;
import com.google.gdata.data.batch.BatchStatus;
import com.google.gdata.data.batch.BatchUtils;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This is the client library for the Google Apps Gmail Settings API. It
* shows how the GmailFilterService can be used to create filters into Gmail
* account.
*
*
*/
public class AppsForYourDomainGmailFilterClient {
private static final Logger LOGGER =
Logger.getLogger(AppsForYourDomainGmailFilterClient.class.getName());
private final String domain;
private final String destinationUser;
// Number of filters to insert.
private static final int ITEMS_TO_BATCH = 5;
private final GmailFilterService gmailFilterService;
// Change the value of these field for your own filter
private final String from = "me@google.com";
private final String to = "you@google.com";
private final String subject = "subject";
private final String hasTheWord = "has";
private final String doesNotHaveTheWord = "no";
private final String hasAttachment = "true";
private final String shouldMarkAsRead = "true";
private final String shouldArchive = "true";
private final String label = "label";
/**
* Constructs an AppsForYourDomainGmailFilterClient for the given domain
* using the given admin credentials.
*
* @param username The user name (not email) of a domain administrator.
* @param password The user's password on the domain.
* @param domain The domain in which filter is being created.
* @param destinationUser the user who owns the new filter.
*/
public AppsForYourDomainGmailFilterClient(String username, String password,
String domain, String destinationUser) throws Exception {
this.domain = domain;
if (destinationUser == null) {
this.destinationUser = username;
} else {
this.destinationUser = destinationUser;
}
// Set up the gmail filter service.
gmailFilterService = new GmailFilterService("exampleCo-exampleApp-1");
gmailFilterService.setUserCredentials(username + "@" + domain, password);
// Run the sample.
runSample();
}
/**
* Main driver for the sample.
* <ul>
* <li>Create an entry of Gmail filter and print the results </li>
* <li>Create an feed of Gmail filters and using batch to send the
* request</li>
* </ul>
*/
private void runSample() {
GenericEntry entry = new GenericEntry();
entry.addProperty("user", destinationUser);
entry.addProperty("key", domain);
entry.addProperty("from", from);
entry.addProperty("to", to);
entry.addProperty("subject", subject);
entry.addProperty("hasTheWord", hasTheWord);
entry.addProperty("doesNotHaveTheWord", doesNotHaveTheWord);
entry.addProperty("hasAttachment", hasAttachment);
entry.addProperty("shouldMarkAsRead", shouldMarkAsRead);
entry.addProperty("shouldArchive", shouldArchive);
entry.addProperty("label", label);
LOGGER.log(Level.INFO, "Inserting 1 gmail filter.");
GenericEntry[] entries = new GenericEntry[ITEMS_TO_BATCH];
for (int i = 0; i < ITEMS_TO_BATCH; i ++) {
GenericEntry newEntry = new GenericEntry();
newEntry.addProperty("user", destinationUser);
newEntry.addProperty("key", domain);
newEntry.addProperty("from", from);
newEntry.addProperty("to", to);
newEntry.addProperty("subject", subject);
newEntry.addProperty("hasTheWord", hasTheWord);
newEntry.addProperty("doesNotHaveTheWord", doesNotHaveTheWord);
newEntry.addProperty("hasAttachment", hasAttachment);
newEntry.addProperty("shouldMarkAsRead", shouldMarkAsRead);
newEntry.addProperty("shouldArchive", shouldArchive);
// Apply different label to different filter
newEntry.addProperty("label", String.valueOf(i));
entries[i] = newEntry;
}
try {
LOGGER.log(Level.INFO, "Inserting 1 Gmail filter.");
GenericEntry resultEntry = insertGmailFilter(entry);
LOGGER.log(Level.INFO, "Insert 1 filter succeeded.");
LOGGER.log(Level.INFO, "Batch inserting " + ITEMS_TO_BATCH +
" Gmail filters");
GenericFeed resultFeed = batchInsertGmailFilters(entries);
// Check for failure in the returned entries.
int failedInsertions = 0, successfulInsertions = 0;
for (GenericEntry returnedEntry : resultFeed.getEntries()) {
if (BatchUtils.isFailure(returnedEntry)) {
BatchStatus status = BatchUtils.getBatchStatus(returnedEntry);
LOGGER.log(Level.SEVERE, "Entry "
+ BatchUtils.getBatchId(returnedEntry) + " failed insertion: "
+ status.getCode() + " " + status.getReason());
failedInsertions++;
} else {
successfulInsertions++;
}
}
LOGGER.log(Level.INFO, "Batch insertion: "
+ Integer.toString(successfulInsertions) + " succeeded, "
+ Integer.toString(failedInsertions) + " failed.");
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Caught IOException: " + e.toString());
e.printStackTrace();
} catch (ServiceException e) {
LOGGER.log(Level.SEVERE, "Caught ServiceException: " + e.toString());
e.printStackTrace();
}
}
/**
* Inserts one Gmail filter entry.
*
* @param filter an {@link GenericEntry} objects that has all the Gmail filter
* properties set.
* @return an entry with the result of the operation.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the insert request failed due to system error.
*/
private GenericEntry insertGmailFilter(GenericEntry filter)
throws ServiceException, IOException {
return gmailFilterService.insert(domain, filter);
}
/**
* Insert one or more Gmail filter entries in a single batch operation. Using
* batch insertion is helpful in reducing HTTP overhead.
*
* @param filters one or more {@link GenericEntry} objects containing Gmail
* filter properties.
* @return a feed with the result of each operation in a separate
* {@link GenericEntry} object.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the insert request failed due to system error.
*/
private GenericFeed batchInsertGmailFilters(GenericEntry ... filters)
throws ServiceException, IOException {
GenericFeed feed = new GenericFeed();
for (int i = 0; i < filters.length; i++) {
BatchUtils.setBatchId(filters[i], Integer.toString(i));
feed.getEntries().add(filters[i]);
}
return gmailFilterService.batch(domain, feed);
}
/**
* Prints the command line usage of this sample application.
*/
private static void usage() {
System.out.println("Usage: java AppsForYourDomainGmailFilterClient"
+ " --username <username> --password <password> --domain <domain>\n"
+ " --destination_user <destination_user>");
System.out.println();
System.out.println("A simple application that demonstrates how to create"
+ " filters to a Google Apps email account. Authenticates using the"
+ " provided login credentials, then create sample filters to the"
+ " specified destination account.");
System.out.println();
System.out.println("Specify username and destination_user as just the name,"
+ " not email address. For example, to create filter to joe@example.com"
+ " use these options: --username joe --password your_password"
+ " --domain example.com");
}
/**
* Main entry point. Parses arguments and creates and invokes the
* AppsForYourDomainGmailFilterClient.
*
* Usage: java AppsForYourDomainGmailFilterClient --username &lt;user&gt;
* --password &lt;pass&gt; --domain &lt;domain&gt;
* --destination_user &lt;destination_user&gt;
*/
public static void main(String[] arg) throws Exception {
SimpleCommandLineParser parser = new SimpleCommandLineParser(arg);
// Parse command-line flags
String username = parser.getValue("username");
String password = parser.getValue("password");
String domain = parser.getValue("domain");
String destinationUser = parser.getValue("destination_user");
boolean help = parser.containsKey("help");
if (help || (username == null) || (password == null) || (domain == null)) {
usage();
System.exit(1);
}
new AppsForYourDomainGmailFilterClient(username, password, domain,
destinationUser);
}
}
@@ -0,0 +1,156 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings;
/**
* Contains constants used by the GMail Settings API sample clients.
*/
public final class Constants {
/**
*/
private Constants() {}
public static final int FILTER_FROM_MAX_LENGTH = 400;
public static final int FILTER_TO_MAX_LENGTH = 400;
public static final int FILTER_SUBJECT_MAX_LENGTH = 1000;
public static final int FILTER_HAS_THE_WORD_MAX_LENGTH = 1000;
public static final int FILTER_DOES_NOT_HAVE_THE_WORD_MAX_LENGTH = 1000;
public static final String[] FORWARDING_ACTION = {"KEEP", "ARCHIVE", "DELETE"};
public static final String[] GENERAL_ALLOWED_PAGE_SIZES = {"25", "50", "100"};
public static final int LABEL_MIN_LENGTH = 1;
public static final int LABEL_MAX_LENGTH = 40;
public static final String[] LANGUAGE_VALID_KEY = {
"ar", // Arabic
"bn", // Bengali
"bg", // Bulgarian
"ca", // Catalan
"zh-CN", // Chinese (Simplified)
"zh-TW", // Chinese (Traditional)
"hr", // Croatian
"cs", // Czech
"da", // Danish
"nl", // Dutch
"en-US", // English (United States)
"en-GB", // English (United Kingdom)
"et", // Estonian
"fi", // Finnish
"fr", // French
"de", // German
"el", // Greek
"gu", // Gujarati
"iw", // Hebrew
"hi", // Hindi
"hu", // Hungarian
"is", // Icelandic
"in", // Indonesian
"it", // Italian
"ja", // Japanese
"kn", // Kannada
"ko", // Korean
"lv", // Latvian
"lt", //Lithuanian
"ms", // Malay
"ml", // Malayalam
"mr", // Marathi
"no", // Norwegian
"or", // Oriya
"fa", // Persian
"pl", // Polish
"pt-BR", // Portuguese (Brazil)
"pt-PT", // Portuguese (Portugal)
"ro", // Romanian
"ru", // Russian
"sr", // Serbian
"sk", // Slovak
"sl", // Slovenian
"es", // Spanish
"sv", // Swedish
"tl", // Tagalog
"ta", // Tamil
"te", // Telugu
"th", // Thai
"tr", // Turkish
"uk", // Ukrainian
"ur", // Urdu
"vi" // Vietnamese
};
public static final String[] POP_ENABLE_FOR = {"ALL_MAIL", "MAIL_FROM_NOW_ON"};
public static final String[] POP_ACTION = {"KEEP", "ARCHIVE", "DELETE"};
public static final int SENDAS_NAME_MIN_LENGTH = 1;
public static final int SENDAS_NAME_MAX_LENGTH = 250;
public static final int SIGNATURE_MIN_LENGTH = 0;
public static final int SIGNATURE_MAX_LENGTH = 1000;
public static final int VACATION_SUBJECT_MIN_LENGTH = 0;
public static final int VACATION_SUBJECT_MAX_LENGTH = 500;
public static final int VACATION_MESSAGE_MIN_LENGTH = 0;
public static final int VACATION_MESSAGE_MAX_LENGTH = 100 * 1024;
public static final String DEFAULT_DOMAIN = "";
public static final String DEFAULT_USERNAME = "";
public static final String DEFAULT_PASSWORD = "";
public static final String PROTOCOL = "https";
public static final String APPS_APIS_DOMAIN = "apps-apis.google.com";
public static final String APPS_APIS_URL = "/a/feeds/emailsettings/2.0";
public static final String FROM = "from";
public static final String TO = "to";
public static final String SUBJECT = "subject";
public static final String HAS_THE_WORD = "hasTheWord";
public static final String DOESNT_HAVE_THE_WORD = "doesNotHaveTheWord";
public static final String HAS_ATTACHMENT = "hasAttachment";
public static final String SHOULD_MARK_AS_READ = "shouldMarkAsRead";
public static final String SHOULD_ARCHIVE = "shouldArchive";
public static final String LABEL = "label";
public static final String ADDRESS = "address";
public static final String NAME = "name";
public static final String REPLY_TO = "replyTo";
public static final String IS_DEFAULT = "isDefault";
public static final String MAKE_DEFAULT = "makeDefault";
public static final String VERIFIED = "verified";
public static final String UNREAD_COUNT = "unreadCount";
public static final String VISIBILITY = "visibility";
public static final String ENABLE = "enable";
public static final String ENABLE_FOR = "enableFor";
public static final String ACTION = "action";
public static final String MESSAGE = "message";
public static final String CONTACTS_ONLY = "contactsOnly";
public static final String TRUE = "true";
public static final String FALSE = "false";
public static final String SIGNATURE = "signature";
public static final String LANGUAGE = "language";
public static final String PAGE_SIZE = "pageSize";
public static final String SHORTCUTS = "shortcuts";
public static final String ARROWS = "arrows";
public static final String SNIPPETS = "snippets";
public static final String UNICODE = "unicode";
public static final String IMAP = "imap";
public static final String POP = "pop";
public static final String FORWARD_TO = "forwardTo";
public static final String FORWARDING = "forwarding";
public static final String SEND_AS = "sendas";
public static final String VACATION = "vacation";
}
@@ -0,0 +1,74 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings;
/**
* Contains default values for the GMail Settings API sample clients.
*/
public final class Defaults {
/**
* Prevents the class from being instantiated.
*/
private Defaults() {}
public static final String FILTER_FROM = "me@google.com";
public static final String FILTER_TO = "you@google.com";
public static final String FILTER_SUBJECT = "subject";
public static final String FILTER_HAS_THE_WORD = "has";
public static final String FILTER_DOES_NOT_HAVE_THE_WORD = "no";
public static final boolean FILTER_HAS_ATTACHMENT = true;
public static final boolean FILTER_SHOULD_MARK_AS_READ = true;
public static final boolean FILTER_SHOULD_ARCHIVE = true;
public static final String FILTER_LABEL = "label";
public static final String SEND_AS_NAME = "test-alias";
public static final String SEND_AS_ADDRESS = "johndoe@example.com";
public static final String SEND_AS_REPLY_TO = "reply-to@someplace.com";
public static final boolean SEND_AS_MAKE_DEFAULT = false;
public static final String LABEL = "label";
public static final boolean FORWARDING_ENABLE = true;
public static final String FORWARDING_FORWARD_TO = "test@admin-api.com";
public static final String FORWARDING_ACTION = "ARCHIVE";
public static final boolean FORWARDING_MAKE_DEFAULT = false;
public static final boolean POP_ENABLE = true;
public static final String POP_ENABLE_FOR = "MAIL_FROM_NOW_ON";
public static final String POP_ACTION = "ARCHIVE";
public static final boolean IMAP_ENABLE = true;
public static final boolean VACATION_ENABLE = true;
public static final String VACATION_SUBJECT = "I'm on vacation";
public static final String VACATION_MESSAGE = "Actually I'm just testing the vacation " +
"responder";
public static final boolean VACATION_CONTACTS_ONLY = true;
public static final String SIGNATURE = "<Insert witty signature here>";
public static final String GENERAL_PAGE_SIZE = "50";
public static final boolean GENERAL_ENABLE_SHORTCUTS = true;
public static final boolean GENERAL_ENABLE_ARROWS = true;
public static final boolean GENERAL_ENABLE_SNIPPETS = true;
public static final boolean GENERAL_ENABLE_UNICODE = true;
public static final String LANGUAGE = "en-US";
public static final boolean WEBCLIP_ENABLE = true;
}
@@ -0,0 +1,287 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings;
import sample.util.SimpleCommandLineParser;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* This is the command line client for the Google Apps Gmail Settings API.
*/
public class GmailSettingsClient {
/**
* Prevents the class from being instantiated.
*/
private GmailSettingsClient() {}
/**
* Prints the command line usage of this sample application.
*/
private static void printUsageAndExit() {
System.out.println("Usage: java GmailSettingsClient"
+ " --username <username> --password <password> --domain <domain>\n"
+ " --setting <setting> [--disable]"
+ " [--get true --destination_user <destination_user>] ");
System.out.println();
System.out.println("A simple application that demonstrates how to get or"
+ " change Gmail settings in a Google Apps email account."
+ " Authenticates using the provided login credentials, then retrieves"
+ " or modifies the settings of the specified account.");
System.out.println();
System.out.println("Specify username and destination_user as just the name,"
+ " not the email address. For example, to change settings for"
+ " joe@example.com use these options: --username joe --password"
+ " your_password --domain example.com");
System.out.println();
System.out.println("**For changing settings...");
System.out.println("Select which setting to change with the setting flag."
+ " For example, to change the POP3 settings, use --setting pop"
+ " (allowed values are filter, sendas, label, forwarding, pop, imap,"
+ " vacation, signature, general, language, and webclip.)");
System.out.println();
System.out.println("By default the selected setting will be enabled, "
+ "but with the --disable flag it will be disabled.");
System.out.println();
System.out.println("**For retrieving settings...");
System.out.println("To retrieve settings, use the --get=true option and"
+ " mandatorily specify a single --destination_user."
+ " For example, to get the signature settings, use"
+ " --get true --settings signature --destination_user joe"
+ " (allowed values are label, sendas, forwarding, pop, imap, vacation,"
+ " and signature).");
System.out.println();
System.exit(1);
}
/**
* Main entry point. Parses arguments and creates and invokes the
* GmailSettingsClient
*
* Usage: java GmailSettingsClient --username &lt;user&gt;
* --password &lt;pass&gt; --domain &lt;domain&gt; --setting &lt;setting&gt;
* [--get true --destination_user &lt;destination_user&gt;] [--disable]
*
* &lt;setting&gt; should be one of:
* <ul>
* <li>filter</li>
* <li>sendas<li>
* <li>label</li>
* <li>forwarding</li>
* <li>pop</li>
* <li>imap</li>
* <li>vacation</li>
* <li>signature</li>
* <li>general</li>
* <li>language</li>
* <li>webclip</li>
* </ul>
*/
public static void main(String[] arg) {
SimpleCommandLineParser parser = new SimpleCommandLineParser(arg);
// Parse command-line flags
String username = parser.getValue("username");
String password = parser.getValue("password");
String domain = parser.getValue("domain");
String destinationUser = parser.getValue("destination_user");
String setting = parser.getValue("setting");
String get = parser.getValue("get");
boolean help = parser.containsKey("help");
boolean enable = !parser.containsKey("disable");
boolean doGet = (get != null && get.equalsIgnoreCase("true"));
if (help || (username == null) || (password == null) || (domain == null)
|| (setting == null) || (doGet && destinationUser == null)) {
printUsageAndExit();
}
// --setting flag is quite accepting - case-insensitive and startsWith
// mean that not just "pop" but also "POP3" works
setting = setting.trim().toLowerCase();
try {
GmailSettingsService settings = new GmailSettingsService("exampleCo-exampleApp-1", domain,
username, password);
List<String> users = new ArrayList<String>();
users.add(destinationUser);
if (setting.startsWith("filter")) {
if (doGet) {
System.out.println("Retrieving filter settings is not supported.\n");
printUsageAndExit();
} else {
settings.createFilter(users,
Defaults.FILTER_FROM,
Defaults.FILTER_TO,
Defaults.FILTER_SUBJECT,
Defaults.FILTER_HAS_THE_WORD,
Defaults.FILTER_DOES_NOT_HAVE_THE_WORD,
Defaults.FILTER_HAS_ATTACHMENT,
Defaults.FILTER_SHOULD_MARK_AS_READ,
Defaults.FILTER_SHOULD_ARCHIVE,
Defaults.FILTER_LABEL);
}
} else if (setting.startsWith("sendas")) {
if (doGet) {
List<Map<String, String>> sendAsSettings = settings.retrieveSendAs(destinationUser);
int count = 0;
for (Map<String, String> sendAsSetting : sendAsSettings) {
System.out.println("sendAs setting " + ++count + ":");
Set<Entry<String, String>> entries = sendAsSetting.entrySet();
for (Entry<String, String> entry : entries)
System.out.println("\t" + entry.getKey() + ": " + entry.getValue());
}
} else {
settings.createSendAs(users, Defaults.SEND_AS_NAME, Defaults.SEND_AS_ADDRESS,
Defaults.SEND_AS_REPLY_TO, Defaults.SEND_AS_MAKE_DEFAULT);
}
} else if (setting.startsWith("label")) {
if (doGet) {
List<Map<String, String>> labels = settings.retrieveLabels(destinationUser);
int count = 0;
for (Map<String, String> label : labels) {
System.out.println("label " + ++count + ":");
Set<Entry<String, String>> entries = label.entrySet();
for (Entry<String, String> entry : entries)
System.out.println("\t" + entry.getKey() + ": " + entry.getValue());
}
} else {
settings.createLabel(users, Defaults.LABEL);
}
} else if (setting.startsWith("forwarding")) {
if (doGet) {
Map<String, String> forwarding = settings.retrieveForwarding(destinationUser);
System.out.println("forwarding settings:");
for (Entry<String, String> entry : forwarding.entrySet())
System.out.println("\t" + entry.getKey() + ": " + entry.getValue());
} else {
settings.changeForwarding(users, Defaults.FORWARDING_ENABLE,
Defaults.FORWARDING_FORWARD_TO, Defaults.FORWARDING_ACTION);
}
} else if (setting.startsWith("pop")) {
if (doGet) {
Map<String, String> pop = settings.retrievePop(destinationUser);
System.out.println("pop settings:");
for (Entry<String, String> entry : pop.entrySet())
System.out.println("\t" + entry.getKey() + ": " + entry.getValue());
} else {
settings.changePop(
users, Defaults.POP_ENABLE, Defaults.POP_ENABLE_FOR, Defaults.POP_ACTION);
}
} else if (setting.startsWith("imap")) {
if (doGet) {
boolean imap = settings.retrieveImap(destinationUser);
System.out.println("imap settings:");
System.out.println("\tenabled: " + imap);
} else {
settings.changeImap(users, Defaults.IMAP_ENABLE);
}
} else if (setting.startsWith("vacation")) {
if (doGet) {
Map<String, String> vacation = settings.retrieveVacation(destinationUser);
System.out.println("vacation settings:");
for (Entry<String, String> entry : vacation.entrySet())
System.out.println("\t" + entry.getKey() + ": " + entry.getValue());
} else {
settings.changeVacation(users, Defaults.VACATION_ENABLE, Defaults.VACATION_SUBJECT,
Defaults.VACATION_MESSAGE, Defaults.VACATION_CONTACTS_ONLY);
}
} else if (setting.startsWith("signature")) {
if (doGet) {
String signature = settings.retrieveSignature(destinationUser);
System.out.println("signature:");
System.out.println("\tvalue: " + signature);
} else {
settings.changeSignature(users, Defaults.SIGNATURE);
}
} else if (setting.startsWith("general")) {
if (doGet) {
System.out.println("Retrieving general settings is not supported.\n");
printUsageAndExit();
} else {
settings.changeGeneral(users,
Defaults.GENERAL_PAGE_SIZE,
Defaults.GENERAL_ENABLE_SHORTCUTS,
Defaults.GENERAL_ENABLE_ARROWS,
Defaults.GENERAL_ENABLE_SNIPPETS,
Defaults.GENERAL_ENABLE_UNICODE);
}
} else if (setting.startsWith("language")) {
if (doGet) {
System.out.println("Retrieving language settings is not supported.\n");
printUsageAndExit();
} else {
settings.changeLanguage(users, Defaults.LANGUAGE);
}
} else if (setting.startsWith("webclip")) {
if (doGet) {
System.out.println("Retrieving webclip settings is not supported.\n");
printUsageAndExit();
} else {
settings.changeWebClip(users, Defaults.WEBCLIP_ENABLE);
}
} else {
printUsageAndExit();
}
} catch (AuthenticationException e) {
System.err.println(e);
} catch (IllegalArgumentException e) {
System.err.println(e);
} catch (ServiceException e) {
System.err.println(e);
} catch (MalformedURLException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
}
@@ -0,0 +1,816 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings;
import com.google.gdata.client.appsforyourdomain.AppsForYourDomainService;
import com.google.gdata.data.appsforyourdomain.generic.GenericEntry;
import com.google.gdata.data.appsforyourdomain.generic.GenericFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This is the client library for the Google Apps Gmail Settings API. It
* shows how to use the services for creating Gmail filters, send-as aliases, or
* labels or changing Gmail forwarding, POP3, IMAP, vacation-responder,
* signature, web clip or general settings.
*/
public class GmailSettingsService extends AppsForYourDomainService {
protected static final Logger logger =
Logger.getLogger(GmailSettingsService.class.getName());
protected final String domain;
/**
* Constructs a GmailSettingsService for the given domain using the given
* admin credentials.
*
* @param applicationName the name of the application making the modifications.
* @param domain the domain in which settings will be modified.
* @param username the user name (not email) of a domain administrator.
* @param password the user's password on the domain.
* @throws AuthenticationException the Exception thrown when invalid
* credentials are supplied.
*/
public GmailSettingsService(String applicationName, String domain,
String username, String password) throws AuthenticationException {
super(applicationName, Constants.PROTOCOL, Constants.APPS_APIS_DOMAIN);
this.domain = domain;
new GenericFeed().declareExtensions(getExtensionProfile());
this.setUserCredentials(username + "@" + domain, password);
}
/**
* Retrieve the specified Gmail settings as a GenericFeed
*
* @param username the user name for which to get the settings.
* @param setting the setting field to get.
* @return a GenericEntry of requested settings
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the retrieve request failed due to system
* error.
*/
public GenericFeed retrieveSettingsFeed(String username, String setting)
throws IOException, ServiceException {
URL singleUrl =
new URL(
Constants.PROTOCOL + "://" + Constants.APPS_APIS_DOMAIN + Constants.APPS_APIS_URL + "/"
+ domain + "/" + username + "/" + setting);
return getFeed(singleUrl, GenericFeed.class);
}
/**
* Retrieve the specified Gmail settings as a GenericEntry
*
* @param username the user name for which to get the settings.
* @param setting the setting field to get.
* @return a GenericEntry of requested settings
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the retrieve request failed due to system
* error.
*/
public GenericEntry retrieveSettingsEntry(String username, String setting)
throws IOException, ServiceException {
URL singleUrl =
new URL(
Constants.PROTOCOL + "://" + Constants.APPS_APIS_DOMAIN + Constants.APPS_APIS_URL + "/"
+ domain + "/" + username + "/" + setting);
return getEntry(singleUrl, GenericEntry.class);
}
/**
* Inserts a new Gmail settings entity - eg a filter.
*
* @param username the user name of a domain administrator.
* @param entry an {@link GenericEntry} object containing all the properties
* of the new entity.
* @return an entry with the result of the operation.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws ServiceException if the insert request failed due to system error.
*/
public GenericEntry insertSettings(String username, GenericEntry entry,
String setting) throws IOException, MalformedURLException,
ServiceException {
URL singleUrl = new URL(Constants.PROTOCOL + "://" +
Constants.APPS_APIS_DOMAIN + Constants.APPS_APIS_URL + "/" + domain +
"/" + username + "/" + setting);
return insert(singleUrl, entry);
}
/**
* Update Gmail settings.
*
* @param username the user name of a domain administrator.
* @param entry a {@link GenericEntry} object containing the new Gmail
* settings.
* @return an entry with the result of the operation.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the insert request failed due to system error.
*/
public GenericEntry updateSettings(String username, GenericEntry entry,
String setting) throws IOException, MalformedURLException,
ServiceException {
URL singleUrl = new URL(Constants.PROTOCOL + "://" +
Constants.APPS_APIS_DOMAIN + Constants.APPS_APIS_URL + "/" + domain +
"/" + username + "/" + setting);
return update(singleUrl, entry);
}
/**
* Creates a filter.
*
* @param users a list of the users to create the filter for.
* @param from the email must come from this address in order to be filtered.
* @param to the email must be sent to this address in order to be filtered.
* @param subject a string the email must have in it's subject line to be
* filtered.
* @param hasTheWord a string the email can have anywhere in it's subject or
* body.
* @param doesNotHaveTheWord a string that the email cannot have anywhere in
* its subject or body.
* @param hasAttachment a boolean representing whether or not the email
* contains an attachment. Values are "true" or "false".
* @param shouldMarkAsRead a boolean field that represents automatically
* moving the message to. "Archived" state if it matches the specified
* filter criteria.
* @param shouldArchive a boolean field that represents automatically moving
* the message to. "Archived" state if it matches the specified filter
* criteria.
* @param label a string that represents the name of the label to apply if a
* message matches the specified filter criteria.
* @throws IllegalArgumentException if no users are passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws ServiceException if the insert request failed due to system error.
*/
public void createFilter(List<String> users, String from, String to,
String subject, String hasTheWord, String doesNotHaveTheWord,
boolean hasAttachment, boolean shouldMarkAsRead, boolean shouldArchive,
String label) throws IllegalArgumentException, ServiceException,
MalformedURLException, IOException {
if (users.size() == 0) {
throw new IllegalArgumentException();
}
GenericEntry entry = new GenericEntry();
entry.addProperty(Constants.FROM, from);
entry.addProperty(Constants.TO, to);
entry.addProperty(Constants.SUBJECT, subject);
entry.addProperty(Constants.HAS_THE_WORD, hasTheWord);
entry.addProperty(Constants.DOESNT_HAVE_THE_WORD, doesNotHaveTheWord);
entry.addProperty(Constants.HAS_ATTACHMENT, String.valueOf(hasAttachment));
entry.addProperty(Constants.SHOULD_MARK_AS_READ, String.valueOf(shouldMarkAsRead));
entry.addProperty(Constants.SHOULD_ARCHIVE, String.valueOf(shouldArchive));
entry.addProperty(Constants.LABEL, label);
for (String user : users) {
logger.log(Level.INFO, "Creating filter ( " +
"from: " + from +
", to: " + to +
", subject: " + subject +
", hasTheWord: " + hasTheWord +
", doesNotHaveTheWord: " + doesNotHaveTheWord +
", hasAttachment: " + hasAttachment +
", shouldMarkAsRead: " + shouldMarkAsRead +
", shouldArchive: " + shouldArchive +
", label: " + label +
" ) for user " + user + " ...");
insertSettings(user, entry, "filter");
logger.log(Level.INFO, "Successfully created filter.");
}
}
/**
* Retrieves the send-as alias settings
*
* @param user
* @return a list of send-as aliases
* @throws IllegalArgumentException if the user hasn't been passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the retrieve request failed due to system
* error.
*/
public List<Map<String, String>> retrieveSendAs(String user)
throws IllegalArgumentException, IOException, ServiceException {
if (user == null || user.length() == 0) {
throw new IllegalArgumentException();
}
logger.log(Level.INFO, "Getting send-as settings for user " + user + " ...");
GenericFeed sendAsFeed = retrieveSettingsFeed(user, Constants.SEND_AS);
if (sendAsFeed != null) {
List<Map<String, String>> sendAs = new ArrayList<Map<String, String>>();
List<GenericEntry> sendAsEntries = sendAsFeed.getEntries();
for (GenericEntry sendAsEntry : sendAsEntries) {
Map<String, String> sendAsMap = new HashMap<String, String>();
sendAsMap.put(Constants.ADDRESS, sendAsEntry.getProperty(Constants.ADDRESS));
sendAsMap.put(Constants.NAME, sendAsEntry.getProperty(Constants.NAME));
sendAsMap.put(Constants.REPLY_TO, sendAsEntry.getProperty(Constants.REPLY_TO));
sendAsMap.put(Constants.IS_DEFAULT, sendAsEntry.getProperty(Constants.IS_DEFAULT));
sendAsMap.put(Constants.VERIFIED, sendAsEntry.getProperty(Constants.VERIFIED));
sendAs.add(sendAsMap);
}
return sendAs;
}
return null;
}
/**
* Creates a send-as alias.
*
* @param users a list of the users to create the send-as alias for.
* @param name the name which e-mails sent using the alias are from.
* @param address the e-mail address which e-mails sent using the alias are
* from.
* @param replyTo (Optional) if set, this address will be included as the
* reply-to address in e-mails sent using the alias.
* @param makeDefault (Optional) if set to true, this user will have this
* send-as alias selected by default from now on.
* @throws IllegalArgumentException if no users are passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws ServiceException if the insert request failed due to system error.
*/
public void createSendAs(List<String> users, String name, String address,
String replyTo, boolean makeDefault) throws IllegalArgumentException,
ServiceException, MalformedURLException, IOException {
if (users.size() == 0) {
throw new IllegalArgumentException();
}
GenericEntry entry = new GenericEntry();
entry.addProperty(Constants.NAME, name);
entry.addProperty(Constants.ADDRESS, address);
entry.addProperty(Constants.REPLY_TO, replyTo);
entry.addProperty(Constants.MAKE_DEFAULT, String.valueOf(makeDefault));
for (String user : users) {
logger.log(Level.INFO, "Creating send-as alias ( " +
"name: " + name +
", address: " + address +
", replyTo: " + replyTo +
", makeDefault: " + makeDefault +
" ) for user " + user + " ...");
insertSettings(user, entry, "sendas");
logger.log(Level.INFO, "Successfully created send-as alias.");
}
}
/**
* Retrieves all mail labels
*
* @param user
* @return List of mail labels
* @throws IllegalArgumentException if the user hasn't been passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the retrieve request failed due to system
* error.
*/
public List<Map<String, String>> retrieveLabels(String user)
throws IllegalArgumentException, IOException, ServiceException {
if (user == null || user.length() == 0) {
throw new IllegalArgumentException();
}
logger.log(Level.INFO, "Getting mail labels for user " + user + " ...");
GenericFeed labelsFeed = retrieveSettingsFeed(user, Constants.LABEL);
if (labelsFeed != null) {
List<Map<String, String>> labels = new ArrayList<Map<String, String>>();
List<GenericEntry> labelEntries = labelsFeed.getEntries();
for (GenericEntry labelEntry : labelEntries) {
Map<String, String> labelMap = new HashMap<String, String>();
labelMap.put(Constants.LABEL, labelEntry.getProperty(Constants.LABEL));
labelMap.put(Constants.UNREAD_COUNT, labelEntry.getProperty(Constants.UNREAD_COUNT));
labelMap.put(Constants.VISIBILITY, labelEntry.getProperty(Constants.VISIBILITY));
labels.add(labelMap);
}
return labels;
}
return null;
}
/**
* Creates a label.
*
* @param users a list of the users to create the label for.
* @param label a string that represents the name of the label.
* @throws IllegalArgumentException if no users are passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws ServiceException if the insert request failed due to system error.
*/
public void createLabel(List<String> users, String label)
throws IllegalArgumentException, ServiceException, MalformedURLException,
IOException {
if (users.size() == 0) {
throw new IllegalArgumentException();
}
GenericEntry entry = new GenericEntry();
entry.addProperty(Constants.LABEL, label);
for (String user : users) {
logger.log(Level.INFO, "Creating label ( label: " + label + " ) for user "
+ user + " ...");
insertSettings(user, entry, Constants.LABEL);
logger.log(Level.INFO, "Successfully created label.");
}
}
/**
* Retrieves mail forwarding settings
*
* @param user
* @return The value of forwarding settings
* @throws IllegalArgumentException if the user hasn't been passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the retrieve request failed due to system
* error.
*/
public Map<String, String> retrieveForwarding(String user)
throws IllegalArgumentException, IOException, ServiceException {
if (user == null || user.length() == 0) {
throw new IllegalArgumentException();
}
logger.log(Level.INFO, "Getting forwarding settings for user " + user + " ...");
GenericEntry forwardingEntry = retrieveSettingsEntry(user, Constants.FORWARDING);
if (forwardingEntry != null) {
Map<String, String> forwarding = new HashMap<String, String>();
forwarding.put(Constants.ENABLE, forwardingEntry.getProperty(Constants.ENABLE));
forwarding.put(Constants.FORWARD_TO, forwardingEntry.getProperty(Constants.FORWARD_TO));
forwarding.put(Constants.ACTION, forwardingEntry.getProperty(Constants.ACTION));
return forwarding;
}
return null;
}
/**
* Changes forwarding settings.
*
* @param users a list of the users to change the forwarding for.
* @param enable whether to enable forwarding of incoming mail.
* @param forwardTo the email will be forwarded to this address.
* @param action what Gmail should do with its copy of the e-mail after
* forwarding it on.
* @throws IllegalArgumentException if no users are passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws ServiceException if the insert request failed due to system error.
*/
public void changeForwarding(List<String> users, boolean enable,
String forwardTo, String action) throws IllegalArgumentException,
ServiceException, MalformedURLException, IOException {
if (users.size() == 0) {
throw new IllegalArgumentException();
}
GenericEntry entry = new GenericEntry();
if (enable) {
entry.addProperty(Constants.ENABLE, Constants.TRUE);
entry.addProperty(Constants.FORWARD_TO, forwardTo);
entry.addProperty(Constants.ACTION, action);
} else {
entry.addProperty(Constants.ENABLE, Constants.FALSE);
}
for (String user : users) {
if (enable) {
logger.log(Level.INFO, "Updating forwarding settings ( " +
"enable: true" +
", forwardTo: " + forwardTo +
", action: " + action +
" ) for user" +
user + " ...");
} else {
logger.log(Level.INFO, "Updating forwarding settings ( enable: false ) " +
"for user" + user + " ...");
}
updateSettings(user, entry, Constants.FORWARDING);
logger.log(Level.INFO, "Successfully updated forwarding settings.");
}
}
/**
* Retrieves POP3 settings
*
* @param user
* @return The POP settings
* @throws IllegalArgumentException if the user hasn't been passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the retrieve request failed due to system
* error.
*/
public Map<String, String> retrievePop(String user)
throws IllegalArgumentException, IOException, ServiceException {
if (user == null || user.length() == 0) {
throw new IllegalArgumentException();
}
logger.log(Level.INFO, "Getting POP settings for user " + user + " ...");
GenericEntry popEntry = retrieveSettingsEntry(user, Constants.POP);
if (popEntry != null) {
Map<String, String> pop = new HashMap<String, String>();
pop.put(Constants.ENABLE, popEntry.getProperty(Constants.ENABLE));
pop.put(Constants.ACTION, popEntry.getProperty(Constants.ACTION));
return pop;
}
return null;
}
/**
* Changes POP3 settings.
*
* @param users a list of the users to change the POP3 settings for.
* @param enable whether to enable POP3 access.
* @param enableFor whether to enable POP3 for all mail, or mail from now on.
* @param action what Gmail should do with its copy of the e-mail after it is
* retrieved using POP.
* @throws IllegalArgumentException if no users are passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws ServiceException if the insert request failed due to system error.
*/
public void changePop(List<String> users, boolean enable, String enableFor,
String action) throws IllegalArgumentException, ServiceException,
MalformedURLException, IOException {
if (users.size() == 0) {
throw new IllegalArgumentException();
}
GenericEntry entry = new GenericEntry();
if (enable) {
entry.addProperty(Constants.ENABLE, Constants.TRUE);
entry.addProperty(Constants.ENABLE_FOR, enableFor);
entry.addProperty(Constants.ACTION, action);
} else {
entry.addProperty(Constants.ENABLE, Constants.FALSE);
}
for (String user : users) {
if (enable) {
logger.log(Level.INFO, "Updating POP3 settings ( " +
"enable: true" +
", enableFor: " + enableFor +
", action: " + action +
" ) for user " + user + " ...");
} else {
logger.log(Level.INFO, "Updating POP3 settings ( enable: false ) for " +
"user " + user + " ...");
}
updateSettings(user, entry, Constants.POP);
logger.log(Level.INFO, "Successfully updated POP3 settings.");
}
}
/**
* Retrieves IMAP settings
*
* @param user
* @return A boolean indicating whether IMAP settings are enabled
* @throws IllegalArgumentException if the user hasn't been passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the retrieve request failed due to system
* error.
*/
public boolean retrieveImap(String user)
throws IllegalArgumentException, IOException, ServiceException {
if (user == null || user.length() == 0) {
throw new IllegalArgumentException();
}
logger.log(Level.INFO, "Getting IMAP settings for user " + user + " ...");
GenericEntry imapEntry = retrieveSettingsEntry(user, Constants.IMAP);
if (imapEntry != null && imapEntry.getProperty(Constants.ENABLE).equals(Constants.TRUE))
return true;
return false;
}
/**
* Changes IMAP settings.
*
* @param users a list of the users to change the IMAP settings for.
* @param enable whether to enable IMAP access.
* @throws IllegalArgumentException if no users are passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws ServiceException if the insert request failed due to system error.
*/
public void changeImap(List<String> users, boolean enable)
throws IllegalArgumentException, ServiceException, MalformedURLException,
IOException {
if (users.size() == 0) {
throw new IllegalArgumentException();
}
GenericEntry entry = new GenericEntry();
entry.addProperty(Constants.ENABLE, String.valueOf(enable));
for (String user : users) {
logger.log(Level.INFO, "Updating IMAP settings ( enable: " + enable + " ) " +
"for user " + user + " ...");
updateSettings(user, entry, Constants.IMAP);
logger.log(Level.INFO, "Successfully updated IMAP settings.");
}
}
/**
* Retrieves vacation settings
*
* @param user
* @return The vacation auto-responder settings
* @throws IllegalArgumentException if the user hasn't been passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the retrieve request failed due to system
* error.
*/
public Map<String, String> retrieveVacation(String user)
throws IllegalArgumentException, IOException, ServiceException {
if (user == null || user.length() == 0) {
throw new IllegalArgumentException();
}
logger.log(Level.INFO, "Getting vacation settings for user " + user + " ...");
GenericEntry vacationEntry = retrieveSettingsEntry(user, Constants.VACATION);
if (vacationEntry != null) {
Map<String, String> vacation = new HashMap<String, String>();
vacation.put(Constants.ENABLE, vacationEntry.getProperty(Constants.ENABLE));
vacation.put(Constants.SUBJECT, vacationEntry.getProperty(Constants.SUBJECT));
vacation.put(Constants.MESSAGE, vacationEntry.getProperty(Constants.MESSAGE));
vacation.put(Constants.CONTACTS_ONLY, vacationEntry.getProperty(Constants.CONTACTS_ONLY));
return vacation;
}
return null;
}
/**
* Changes vacation-responder settings.
*
* @param users a list of the users to change the vacation-responder for.
* @param enable whether to enable the vacation responder.
* @param subject the subject line of the vacation responder autoresponse.
* @param message the message body of the vacation responder autoresponse.
* @param contactsOnly whether to only send the autoresponse to known contacts.
* @throws IllegalArgumentException if no users are passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws ServiceException if the insert request failed due to system error.
*/
public void changeVacation(List<String> users, boolean enable, String subject,
String message, boolean contactsOnly) throws IllegalArgumentException,
ServiceException, MalformedURLException, IOException {
if (users.size() == 0) {
throw new IllegalArgumentException();
}
GenericEntry entry = new GenericEntry();
if (enable) {
entry.addProperty(Constants.ENABLE, Constants.TRUE);
entry.addProperty(Constants.SUBJECT, subject);
entry.addProperty(Constants.MESSAGE, message);
entry.addProperty(Constants.CONTACTS_ONLY, String.valueOf(contactsOnly));
} else {
entry.addProperty(Constants.ENABLE, Constants.FALSE);
}
for (String user : users) {
if (enable) {
logger.log(Level.INFO, "Updating vacation-responder settings ( " +
"enable: " + enable +
", subject: " + subject +
", message: " + message +
", contactsOnly: " + contactsOnly +
" ) for user " +
user + " ...");
} else {
logger.log(Level.INFO, "Updating vacation-responder settings ( " +
"enable: false ) for user " + user + " ...");
}
updateSettings(user, entry, Constants.VACATION);
logger.log(Level.INFO, "Successfully updated vacation-responder settings.");
}
}
/**
* Retrieves signature
*
* @param user
* @return The signature
* @throws IllegalArgumentException if the user hasn't been passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the retrieve request failed due to system
* error.
*/
public String retrieveSignature(String user)
throws IllegalArgumentException, IOException, ServiceException {
if (user == null || user.length() == 0) {
throw new IllegalArgumentException();
}
logger.log(Level.INFO, "Getting signature settings for user " + user + " ...");
GenericEntry signatureEntry = retrieveSettingsEntry(user, Constants.SIGNATURE);
if (signatureEntry != null)
return signatureEntry.getProperty(Constants.SIGNATURE);
return null;
}
/**
* Changes signature.
*
* @param users a list of the users to change the signature for.
* @param signature the signature to be appended to outgoing messages. Don't
* want a signature? Set the signature to "" (empty string).
* @throws IllegalArgumentException if no users are passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws ServiceException if the insert request failed due to system error.
*/
public void changeSignature(List<String> users, String signature)
throws IllegalArgumentException, ServiceException, MalformedURLException,
IOException {
if (users.size() == 0) {
throw new IllegalArgumentException();
}
GenericEntry entry = new GenericEntry();
entry.addProperty(Constants.SIGNATURE, signature);
for (String user : users) {
logger.log(Level.INFO, "Updating signature ( signature: " + signature +
" ) for user " + user + " ...");
updateSettings(user, entry, Constants.SIGNATURE);
logger.log(Level.INFO, "Successfully updated signature.");
}
}
/**
* Changes general settings.
*
* @param users a list of the users to change the general settings for.
* @param pageSize the number of conversations to be shown per page.
* @param enableShortcuts whether to enable keyboard shortcuts
* @param enableArrows whether to display arrow-shaped personal indicators
* next to emails that were sent specifically to the user. (> and >>).
* @param enableSnippets whether to display snippets of messages in the inbox
* and when searching.
* @param enableUnicode whether to use UTF-8 (unicode) encoding for all
* outgoing messages, instead of the default text encoding.
* @throws IllegalArgumentException if no users are passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws ServiceException if the insert request failed due to system error.
*/
public void changeGeneral(List<String> users, String pageSize,
boolean enableShortcuts, boolean enableArrows, boolean enableSnippets,
boolean enableUnicode) throws IllegalArgumentException, ServiceException,
MalformedURLException, IOException {
if (users.size() == 0) {
throw new IllegalArgumentException();
}
GenericEntry entry = new GenericEntry();
entry.addProperty(Constants.PAGE_SIZE, pageSize);
entry.addProperty(Constants.SHORTCUTS, String.valueOf(enableShortcuts));
entry.addProperty(Constants.ARROWS, String.valueOf(enableArrows));
entry.addProperty(Constants.SNIPPETS, String.valueOf(enableSnippets));
entry.addProperty(Constants.UNICODE, String.valueOf(enableUnicode));
for (String user : users) {
logger.log(Level.INFO, "Updating general settings ( " +
"pageSize: " + pageSize +
", shortcuts: " + enableShortcuts +
", arrows: " + enableArrows +
", snippets: " + enableSnippets +
", unicode: " + enableUnicode +
" ) for user " + user +
" ...");
updateSettings(user, entry, "general");
logger.log(Level.INFO, "Successfully updated general settings.");
}
}
/**
* Changes language settings.
*
* @param users a list of the users to change the language for.
* @param language Gmail's display language.
* @throws IllegalArgumentException if no users are passed in.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws ServiceException if the insert request failed due to system error.
*/
public void changeLanguage(List<String> users, String language)
throws IllegalArgumentException, ServiceException, MalformedURLException,
IOException {
if (users.size() == 0) {
throw new IllegalArgumentException();
}
GenericEntry entry = new GenericEntry();
entry.addProperty(Constants.LANGUAGE, language);
for (String user : users) {
logger.log(Level.INFO, "Updating language settings ( language: " +
language + " ) for user " + user + " ...");
updateSettings(user, entry, Constants.LANGUAGE);
logger.log(Level.INFO, "Successfully updated language settings.");
}
}
/**
* Change web clip settings.
*
* @param users a list of the users to change the web clip settings for.
* @param enable whether to enable web clip.
* @throws IllegalArgumentException if no users are passed in.
* @throws ServiceException if an error occurs while communicating with the
* GData service.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws IOException if the insert request failed due to system error.
*/
public void changeWebClip(List<String> users, boolean enable)
throws IllegalArgumentException, ServiceException, MalformedURLException,
IOException {
if (users.size() == 0) {
throw new IllegalArgumentException();
}
GenericEntry entry = new GenericEntry();
entry.addProperty(Constants.ENABLE, String.valueOf(enable));
for (String user : users) {
logger.log(Level.INFO, "Updating web clip settings ( enable: " + enable +
" ) for user " + user + " ...");
updateSettings(user, entry, "webclip");
logger.log(Level.INFO, "Successfully updated web clip settings.");
}
}
}
@@ -0,0 +1,25 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings;
/**
* Exception to be thrown when an operation on an invalid user is attempted.
*/
public class InvalidUserException extends Exception {
public InvalidUserException() {};
public InvalidUserException(String msg) { super(msg); }
}
@@ -0,0 +1,68 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.GmailSettingsService;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* This is the example GUI client for the Google Apps Gmail Settings API.
*/
public class GmailSettingsClient {
public static final String APP_TITLE = "GUI Gmail Settings Client";
public static final String ERROR_AUTHENTICATION_REQUIRED = "You must authenticate first.";
protected static final int DEFAULT_APP_HEIGHT = 350;
protected static final int DEFAULT_APP_WIDTH = 600;
protected static final int DEFAULT_PANE_DIVIDER_LOCATION = 150;
public static GmailSettingsService settings;
public static UsersPanel users;
/**
* Prevents the class from being instantiated.
*/
private GmailSettingsClient() {}
/**
* Entry point for Graphical GMail Settings Client.
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JFrame frame = new JFrame(APP_TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(DEFAULT_APP_WIDTH, DEFAULT_APP_HEIGHT);
users = new UsersPanel();
TabbedPane settingTabs = new TabbedPane();
JSplitPane splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, users, settingTabs);
splitpane.setDividerLocation(DEFAULT_PANE_DIVIDER_LOCATION);
frame.add(splitpane);
frame.setVisible(true);
}
});
}
}
@@ -0,0 +1,71 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import javax.swing.JPanel;
/**
* Stores some common information for the tabs.
*/
public class Tab extends JPanel {
protected String name;
protected String tooltip;
/**
* @param name The name to assign to the tab.
* @param tooltip The tooltip to be used for the tab.
*/
public Tab(String name, String tooltip) {
setName(name);
setTooltip(tooltip);
}
/**
* @Return the name of the tab
*/
@Override
public String getName() {
return this.name;
}
/**
* Sets the name of the tab.
*
* @param name The name to assign to the tab.
*/
@Override
public void setName(String name) {
this.name = name;
}
/**
* @return The current value for tooltip.
*/
public String getTooltip() {
return this.tooltip;
}
/**
* Sets the tooltop for the tab.
*
* @param tooltip The tooltip to be used for the tab.
*/
public void setTooltip(String tooltip) {
this.tooltip = tooltip;
}
}
@@ -0,0 +1,107 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Constants;
import sample.appsforyourdomain.gmailsettings.GmailSettingsService;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
/**
* Tab containing all the authentication information.
*/
public class TabAuthentication extends Tab {
protected SpringLayout layout;
protected JLabel domainLabel;
protected JTextField domain;
protected JLabel usernameLabel;
protected JTextField username;
protected JLabel passwordLabel;
protected JPasswordField password;
protected JButton submit;
/**
* Setup all the components on the tab.
*/
public TabAuthentication() {
super("Authentication", "Authenticate with a server");
layout = new SpringLayout();
setLayout(layout);
domainLabel = new JLabel("Domain: ");
domain = new JTextField(12);
domain.setText(Constants.DEFAULT_DOMAIN);
usernameLabel = new JLabel("Admin username: ");
username = new JTextField(12);
username.setText(Constants.DEFAULT_USERNAME);
passwordLabel = new JLabel("Admin password: ");
password = new JPasswordField(12);
password.setText(Constants.DEFAULT_PASSWORD);
submit = new JButton("Update");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
GmailSettingsClient.settings = new GmailSettingsService(GmailSettingsClient.APP_TITLE,
domain.getText(), username.getText(), new String (password.getPassword()));
GmailSettingsClient.users.refresh(domain.getText(), username.getText(),
new String (password.getPassword()));
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, domainLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, domainLabel, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, domain, 5, SpringLayout.EAST, domainLabel);
layout.putConstraint(SpringLayout.NORTH, domain, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, usernameLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, usernameLabel, 5, SpringLayout.SOUTH, domain);
layout.putConstraint(SpringLayout.WEST, username, 5, SpringLayout.EAST, usernameLabel);
layout.putConstraint(SpringLayout.NORTH, username, 5, SpringLayout.SOUTH, domain);
layout.putConstraint(SpringLayout.WEST, passwordLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, passwordLabel, 5, SpringLayout.SOUTH, username);
layout.putConstraint(SpringLayout.WEST, password, 5, SpringLayout.EAST, passwordLabel);
layout.putConstraint(SpringLayout.NORTH, password, 5, SpringLayout.SOUTH, username);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, password);
add(domainLabel);
add(domain);
add(usernameLabel);
add(username);
add(passwordLabel);
add(password);
add(submit);
}
}
@@ -0,0 +1,182 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Defaults;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
/**
* Tab containing all the filter information.
*/
public class TabFilter extends Tab {
protected SpringLayout layout;
protected JLabel fromLabel;
protected JTextField from;
protected JLabel toLabel;
protected JTextField to;
protected JLabel subjectLabel;
protected JTextField subject;
protected JLabel hasTheWordLabel;
protected JTextField hasTheWord;
protected JLabel doesNotHaveTheWordLabel;
protected JTextField doesNotHaveTheWord;
protected JCheckBox hasAttachment;
protected JCheckBox shouldMarkAsRead;
protected JCheckBox shouldArchive;
protected JLabel labelLabel;
protected JTextField label;
protected JButton submit;
/**
* Setup all the components on the tab.
*/
public TabFilter() {
super("Filters", "");
layout = new SpringLayout();
setLayout(layout);
fromLabel = new JLabel("From: ");
from = new JTextField(Defaults.FILTER_FROM, 25);
toLabel = new JLabel("To: ");
to = new JTextField(Defaults.FILTER_TO, 25);
subjectLabel = new JLabel("Subject: ");
subject = new JTextField(Defaults.FILTER_SUBJECT, 25);
hasTheWordLabel = new JLabel("Has the word: ");
hasTheWord = new JTextField(Defaults.FILTER_HAS_THE_WORD, 25);
doesNotHaveTheWordLabel = new JLabel("Does not have the word: ");
doesNotHaveTheWord = new JTextField(Defaults.FILTER_DOES_NOT_HAVE_THE_WORD, 25);
hasAttachment = new JCheckBox("Has attachment:", Defaults.FILTER_HAS_ATTACHMENT);
shouldMarkAsRead = new JCheckBox("Should mark as read:", Defaults.FILTER_SHOULD_MARK_AS_READ);
shouldArchive = new JCheckBox("Should archive:", Defaults.FILTER_SHOULD_ARCHIVE);
labelLabel = new JLabel("Label: ");
label = new JTextField(Defaults.FILTER_LABEL, 25);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (GmailSettingsClient.settings == null) {
JOptionPane.showMessageDialog(null, GmailSettingsClient.ERROR_AUTHENTICATION_REQUIRED,
GmailSettingsClient.APP_TITLE, JOptionPane.ERROR_MESSAGE);
return;
}
try {
GmailSettingsClient.settings.createFilter(GmailSettingsClient.users.
getSelectedUsers(), from.getText(), to.getText(), subject.getText(),
hasTheWord.getText(), doesNotHaveTheWord.getText(), hasAttachment.isSelected(),
shouldMarkAsRead.isSelected(), shouldArchive.isSelected(), label.getText());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, fromLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, fromLabel, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, from, 5, SpringLayout.EAST, fromLabel);
layout.putConstraint(SpringLayout.NORTH, from, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, toLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, toLabel, 5, SpringLayout.SOUTH, from);
layout.putConstraint(SpringLayout.WEST, to, 5, SpringLayout.EAST, toLabel);
layout.putConstraint(SpringLayout.NORTH, to, 5, SpringLayout.SOUTH, from);
layout.putConstraint(SpringLayout.WEST, subjectLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, subjectLabel, 5, SpringLayout.SOUTH, to);
layout.putConstraint(SpringLayout.WEST, subject, 5, SpringLayout.EAST, subjectLabel);
layout.putConstraint(SpringLayout.NORTH, subject, 5, SpringLayout.SOUTH, to);
layout.putConstraint(SpringLayout.WEST, hasTheWordLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, hasTheWordLabel, 5, SpringLayout.SOUTH, subject);
layout.putConstraint(SpringLayout.WEST, hasTheWord, 5, SpringLayout.EAST, hasTheWordLabel);
layout.putConstraint(SpringLayout.NORTH, hasTheWord, 5, SpringLayout.SOUTH, subject);
layout.putConstraint(SpringLayout.WEST, doesNotHaveTheWordLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, doesNotHaveTheWordLabel, 5, SpringLayout.SOUTH,
hasTheWord);
layout.putConstraint(SpringLayout.WEST, doesNotHaveTheWord, 5, SpringLayout.EAST,
doesNotHaveTheWordLabel);
layout.putConstraint(SpringLayout.NORTH, doesNotHaveTheWord, 5, SpringLayout.SOUTH, hasTheWord);
layout.putConstraint(SpringLayout.WEST, hasAttachment, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, hasAttachment, 5, SpringLayout.SOUTH,
doesNotHaveTheWord);
layout.putConstraint(SpringLayout.WEST, shouldMarkAsRead, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, shouldMarkAsRead, 5, SpringLayout.SOUTH,
hasAttachment);
layout.putConstraint(SpringLayout.WEST, shouldArchive, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, shouldArchive, 5, SpringLayout.SOUTH,
shouldMarkAsRead);
layout.putConstraint(SpringLayout.WEST, labelLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, labelLabel, 5, SpringLayout.SOUTH, shouldArchive);
layout.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.EAST, labelLabel);
layout.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.SOUTH, shouldArchive);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, label);
add(fromLabel);
add(from);
add(toLabel);
add(to);
add(subjectLabel);
add(subject);
add(hasTheWordLabel);
add(hasTheWord);
add(doesNotHaveTheWordLabel);
add(doesNotHaveTheWord);
add(hasAttachment);
add(shouldMarkAsRead);
add(shouldArchive);
add(labelLabel);
add(label);
add(submit);
}
}
@@ -0,0 +1,117 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Constants;
import sample.appsforyourdomain.gmailsettings.Defaults;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
/**
* Tab containing the forwarding information.
*/
public class TabForwarding extends Tab {
protected SpringLayout layout;
protected JCheckBox enable;
protected JLabel forwardToLabel;
protected JTextField forwardTo;
protected JLabel actionLabel;
protected JComboBox action;
protected JButton submit;
/**
* Setup all the components on the tab.
*/
public TabForwarding() {
super("Forwarding", "");
layout = new SpringLayout();
setLayout(layout);
enable = new JCheckBox("Enable:", Defaults.FORWARDING_ENABLE);
forwardToLabel = new JLabel("Forward To: ");
forwardTo = new JTextField(Defaults.FORWARDING_FORWARD_TO, 25);
actionLabel = new JLabel("Action: ");
action = new JComboBox(Constants.FORWARDING_ACTION);
action.setSelectedItem(Defaults.FORWARDING_ACTION);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (GmailSettingsClient.settings == null) {
JOptionPane.showMessageDialog(null, GmailSettingsClient.ERROR_AUTHENTICATION_REQUIRED,
GmailSettingsClient.APP_TITLE, JOptionPane.ERROR_MESSAGE);
return;
}
try {
GmailSettingsClient.settings.changeForwarding(GmailSettingsClient.users.
getSelectedUsers(), enable.isSelected(), forwardTo.getText(),
action.getSelectedItem().toString());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, enable, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, enable, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, forwardToLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, forwardToLabel, 5, SpringLayout.SOUTH, enable);
layout.putConstraint(SpringLayout.WEST, forwardTo, 5, SpringLayout.EAST, forwardToLabel);
layout.putConstraint(SpringLayout.NORTH, forwardTo, 5, SpringLayout.SOUTH, enable);
layout.putConstraint(SpringLayout.WEST, actionLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, actionLabel, 5, SpringLayout.SOUTH, forwardTo);
layout.putConstraint(SpringLayout.WEST, action, 5, SpringLayout.EAST, actionLabel);
layout.putConstraint(SpringLayout.NORTH, action, 5, SpringLayout.SOUTH, forwardTo);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, action);
add(enable);
add(forwardToLabel);
add(forwardTo);
add(actionLabel);
add(action);
add(submit);
}
}
@@ -0,0 +1,127 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Constants;
import sample.appsforyourdomain.gmailsettings.Defaults;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SpringLayout;
/**
* Tab containing all the general information.
*/
public class TabGeneral extends Tab {
protected SpringLayout layout;
protected JLabel pageSizeLabel;
protected JComboBox pageSize;
protected JCheckBox enableShortcuts;
protected JCheckBox enableArrows;
protected JCheckBox enableSnippets;
protected JCheckBox enableUnicode;
protected JButton submit;
/**
* Setup all the components on the tab.
*/
public TabGeneral() {
super("General", "");
layout = new SpringLayout();
setLayout(layout);
pageSizeLabel = new JLabel("Page size: ");
pageSize = new JComboBox(Constants.GENERAL_ALLOWED_PAGE_SIZES);
enableShortcuts = new JCheckBox("Enable shortcuts:", Defaults.GENERAL_ENABLE_SHORTCUTS);
enableArrows = new JCheckBox("Enable arrows:", Defaults.GENERAL_ENABLE_ARROWS);
enableSnippets = new JCheckBox("Enable snippets:", Defaults.GENERAL_ENABLE_SNIPPETS);
enableUnicode = new JCheckBox("Enable unicode:", Defaults.GENERAL_ENABLE_UNICODE);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (GmailSettingsClient.settings == null) {
JOptionPane.showMessageDialog(null, GmailSettingsClient.ERROR_AUTHENTICATION_REQUIRED,
GmailSettingsClient.APP_TITLE, JOptionPane.ERROR_MESSAGE);
return;
}
try {
GmailSettingsClient.settings.changeGeneral(GmailSettingsClient.users.
getSelectedUsers(), pageSize.getSelectedItem().toString(),
enableShortcuts.isSelected(), enableArrows.isSelected(),
enableSnippets.isSelected(),
enableUnicode.isSelected());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, pageSizeLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, pageSizeLabel, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, pageSize, 5, SpringLayout.EAST, pageSizeLabel);
layout.putConstraint(SpringLayout.NORTH, pageSize, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, enableShortcuts, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, enableShortcuts, 5, SpringLayout.SOUTH, pageSize);
layout.putConstraint(SpringLayout.WEST, enableArrows, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, enableArrows, 5, SpringLayout.SOUTH, enableShortcuts);
layout.putConstraint(SpringLayout.WEST, enableSnippets, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, enableSnippets, 5, SpringLayout.SOUTH, enableArrows);
layout.putConstraint(SpringLayout.WEST, enableUnicode, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, enableUnicode, 5, SpringLayout.SOUTH, enableSnippets);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, enableUnicode);
add(pageSizeLabel);
add(pageSize);
add(enableShortcuts);
add(enableArrows);
add(enableSnippets);
add(enableUnicode);
add(submit);
}
}
@@ -0,0 +1,87 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Defaults;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.SpringLayout;
/**
* Tab containing all the IMAP information.
*/
public class TabImap extends Tab {
protected SpringLayout layout;
protected JCheckBox imapEnabled;
protected JButton submit;
/**
* Setup all the components on the tab.
*/
public TabImap() {
super("Imap", "");
layout = new SpringLayout();
setLayout(layout);
imapEnabled = new JCheckBox("Enable IMAP:", Defaults.IMAP_ENABLE);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (GmailSettingsClient.settings == null) {
JOptionPane.showMessageDialog(null, GmailSettingsClient.ERROR_AUTHENTICATION_REQUIRED,
GmailSettingsClient.APP_TITLE, JOptionPane.ERROR_MESSAGE);
return;
}
try {
GmailSettingsClient.settings.changeImap(GmailSettingsClient.users.
getSelectedUsers(), imapEnabled.isSelected());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, imapEnabled, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, imapEnabled, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, imapEnabled);
add(imapEnabled);
add(submit);
}
}
@@ -0,0 +1,94 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Defaults;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
/**
* Tab containing all the label information.
*/
public class TabLabel extends Tab {
protected SpringLayout layout;
protected JLabel labelLabel;
protected JTextField label;
protected JButton submit;
/**
* Setup all the components on the tab.
*/
public TabLabel() {
super("Label", "");
layout = new SpringLayout();
setLayout(layout);
labelLabel = new JLabel("Label: ");
label = new JTextField(Defaults.LABEL, 25);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (GmailSettingsClient.settings == null) {
JOptionPane.showMessageDialog(null,
GmailSettingsClient.ERROR_AUTHENTICATION_REQUIRED,
GmailSettingsClient.APP_TITLE, JOptionPane.ERROR_MESSAGE);
return;
}
try {
GmailSettingsClient.settings.createLabel(GmailSettingsClient.users.
getSelectedUsers(), label.getText());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, labelLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, labelLabel, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.EAST, labelLabel);
layout.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, label);
add(labelLabel);
add(label);
add(submit);
}
}
@@ -0,0 +1,95 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Constants;
import sample.appsforyourdomain.gmailsettings.Defaults;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SpringLayout;
/**
* Tab containing all the language information.
*/
public class TabLanguage extends Tab {
protected SpringLayout layout;
protected JLabel languagesLabel;
protected JComboBox languages;
protected JButton submit;
/**
* Setup all the components on the tab.
*/
public TabLanguage() {
super("Language", "");
layout = new SpringLayout();
setLayout(layout);
languagesLabel = new JLabel("Languages: ");
languages = new JComboBox(Constants.LANGUAGE_VALID_KEY);
languages.setSelectedItem(Defaults.LANGUAGE);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (GmailSettingsClient.settings == null) {
JOptionPane.showMessageDialog(null, GmailSettingsClient.ERROR_AUTHENTICATION_REQUIRED,
GmailSettingsClient.APP_TITLE, JOptionPane.ERROR_MESSAGE);
return;
}
try {
GmailSettingsClient.settings.changeLanguage(GmailSettingsClient.users.
getSelectedUsers(), languages.getSelectedItem().toString());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, languagesLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, languagesLabel, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, languages, 5, SpringLayout.EAST, languagesLabel);
layout.putConstraint(SpringLayout.NORTH, languages, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, languages);
add(languagesLabel);
add(languages);
add(submit);
}
}
@@ -0,0 +1,117 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Constants;
import sample.appsforyourdomain.gmailsettings.Defaults;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SpringLayout;
/**
* Tab containing all the POP information.
*/
public class TabPop extends Tab {
protected SpringLayout layout;
protected JCheckBox enable;
protected JLabel enableForLabel;
protected JComboBox enableFor;
protected JLabel actionLabel;
protected JComboBox action;
protected JButton submit;
/**
* Setup all the components on the tab.
*/
public TabPop() {
super("Pop","");
layout = new SpringLayout();
setLayout(layout);
enable = new JCheckBox("Enable:",Defaults.POP_ENABLE);
enableForLabel = new JLabel("Enable for: ");
enableFor = new JComboBox(Constants.POP_ENABLE_FOR);
enableFor.setSelectedItem(Defaults.POP_ENABLE_FOR);
actionLabel = new JLabel("Action: ");
action = new JComboBox(Constants.POP_ACTION);
action.setSelectedItem(Defaults.POP_ACTION);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (GmailSettingsClient.settings == null) {
JOptionPane.showMessageDialog(null, GmailSettingsClient.ERROR_AUTHENTICATION_REQUIRED,
GmailSettingsClient.APP_TITLE, JOptionPane.ERROR_MESSAGE);
return;
}
try {
GmailSettingsClient.settings.changePop(GmailSettingsClient.users.
getSelectedUsers(), enable.isSelected(), enableFor.getSelectedItem().toString(),
action.getSelectedItem().toString());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, enable, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, enable, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, enableForLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, enableForLabel, 5, SpringLayout.SOUTH, enable);
layout.putConstraint(SpringLayout.WEST, enableFor, 5, SpringLayout.EAST, enableForLabel);
layout.putConstraint(SpringLayout.NORTH, enableFor, 5, SpringLayout.SOUTH, enable);
layout.putConstraint(SpringLayout.WEST, actionLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, actionLabel, 5, SpringLayout.SOUTH, enableFor);
layout.putConstraint(SpringLayout.WEST, action, 5, SpringLayout.EAST, actionLabel);
layout.putConstraint(SpringLayout.NORTH, action, 5, SpringLayout.SOUTH, enableFor);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, action);
add(enable);
add(enableForLabel);
add(enableFor);
add(actionLabel);
add(action);
add(submit);
}
}
@@ -0,0 +1,126 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Defaults;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
/**
* Tab containing all the send as information.
*/
public class TabSendAs extends Tab {
protected SpringLayout layout;
protected JLabel nameLabel;
protected JTextField nameField;
protected JLabel addressLabel;
protected JTextField address;
protected JLabel replyToLabel;
protected JTextField replyTo;
protected JCheckBox makeDefault;
protected JButton submit;
/**
* Setup all the components on the tab.
*/
public TabSendAs() {
super("Send As", "");
layout = new SpringLayout();
setLayout(layout);
nameLabel = new JLabel("Name: ");
nameField = new JTextField(Defaults.SEND_AS_NAME, 25);
addressLabel = new JLabel("Address: ");
address = new JTextField(Defaults.SEND_AS_ADDRESS, 25);
replyToLabel = new JLabel("Send As: ");
replyTo = new JTextField(Defaults.SEND_AS_REPLY_TO, 25);
makeDefault = new JCheckBox("Make Default:", Defaults.SEND_AS_MAKE_DEFAULT);
submit = new JButton("Set Send As");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (GmailSettingsClient.settings == null) {
JOptionPane.showMessageDialog(null, GmailSettingsClient.ERROR_AUTHENTICATION_REQUIRED,
GmailSettingsClient.APP_TITLE, JOptionPane.ERROR_MESSAGE);
return;
}
try {
GmailSettingsClient.settings.createSendAs(GmailSettingsClient.users.
getSelectedUsers(), nameField.getText(), address.getText(), replyTo.getText(),
makeDefault.isSelected());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, nameLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, nameLabel, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, nameField, 5, SpringLayout.EAST, nameLabel);
layout.putConstraint(SpringLayout.NORTH, nameField, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, addressLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, addressLabel, 5, SpringLayout.SOUTH, nameField);
layout.putConstraint(SpringLayout.WEST, address, 5, SpringLayout.EAST, addressLabel);
layout.putConstraint(SpringLayout.NORTH, address, 5, SpringLayout.SOUTH, nameField);
layout.putConstraint(SpringLayout.WEST, replyToLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, replyToLabel, 5, SpringLayout.SOUTH, address);
layout.putConstraint(SpringLayout.WEST, replyTo, 5, SpringLayout.EAST, replyToLabel);
layout.putConstraint(SpringLayout.NORTH, replyTo, 5, SpringLayout.SOUTH, address);
layout.putConstraint(SpringLayout.WEST, makeDefault, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, makeDefault, 5, SpringLayout.SOUTH, replyTo);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, makeDefault);
add(nameLabel);
add(nameField);
add(addressLabel);
add(address);
add(replyToLabel);
add(replyTo);
add(makeDefault);
add(submit);
}
}
@@ -0,0 +1,96 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Defaults;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SpringLayout;
/**
* Tab containing all the signature information.
*/
public class TabSignature extends Tab {
protected SpringLayout layout;
protected JLabel signatureLabel;
protected JTextArea signature;
protected JScrollPane signaturePane;
protected JButton submit;
/**
* Setup all the components on the tab.
*/
public TabSignature() {
super("Signature", "Change a users's signature.");
layout = new SpringLayout();
setLayout(layout);
signatureLabel = new JLabel("Signature: ");
signature = new JTextArea(Defaults.SIGNATURE, 4, 25);
signaturePane = new JScrollPane(signature);
submit = new JButton("Set Signature");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (GmailSettingsClient.settings == null) {
JOptionPane.showMessageDialog(null, GmailSettingsClient.ERROR_AUTHENTICATION_REQUIRED,
GmailSettingsClient.APP_TITLE, JOptionPane.ERROR_MESSAGE);
return;
}
try {
GmailSettingsClient.settings.changeSignature(GmailSettingsClient.users.
getSelectedUsers(), signature.getText());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, signatureLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, signatureLabel, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, signaturePane, 5, SpringLayout.EAST, signatureLabel);
layout.putConstraint(SpringLayout.NORTH, signaturePane, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, signaturePane);
add(signatureLabel);
add(signaturePane);
add(submit);
}
}
@@ -0,0 +1,122 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Defaults;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
/**
* Tab containing all the vacation information.
*/
public class TabVacation extends Tab {
protected SpringLayout layout;
protected JCheckBox enable;
protected JLabel subjectLabel;
protected JTextField subject;
protected JLabel messageLabel;
protected JTextField message;
protected JLabel contactsOnlyLabel;
protected JCheckBox contactsOnly;
protected JButton submit;
/**
* Setup all the components on the tab.
*/
public TabVacation() {
super("Vacation Responder", "");
layout = new SpringLayout();
setLayout(layout);
enable = new JCheckBox("Enable:", Defaults.VACATION_ENABLE);
subjectLabel = new JLabel("Subject: ");
subject = new JTextField(Defaults.VACATION_SUBJECT, 25);
messageLabel = new JLabel("Message: ");
message = new JTextField(Defaults.VACATION_MESSAGE, 25);
contactsOnly = new JCheckBox("Contacts only:", Defaults.VACATION_CONTACTS_ONLY);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (GmailSettingsClient.settings == null) {
JOptionPane.showMessageDialog(null, GmailSettingsClient.ERROR_AUTHENTICATION_REQUIRED,
GmailSettingsClient.APP_TITLE, JOptionPane.ERROR_MESSAGE);
return;
}
try {
GmailSettingsClient.settings.changeVacation(GmailSettingsClient.users.
getSelectedUsers(), enable.isSelected(), subject.getText(), message.getText(),
contactsOnly.isSelected());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, enable, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, enable, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, subjectLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, subjectLabel, 5, SpringLayout.SOUTH, enable);
layout.putConstraint(SpringLayout.WEST, subject, 5, SpringLayout.EAST, subjectLabel);
layout.putConstraint(SpringLayout.NORTH, subject, 5, SpringLayout.SOUTH, enable);
layout.putConstraint(SpringLayout.WEST, messageLabel, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, messageLabel, 5, SpringLayout.SOUTH, subject);
layout.putConstraint(SpringLayout.WEST, message, 5, SpringLayout.EAST, messageLabel);
layout.putConstraint(SpringLayout.NORTH, message, 5, SpringLayout.SOUTH, subject);
layout.putConstraint(SpringLayout.WEST, contactsOnly, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, contactsOnly, 5, SpringLayout.SOUTH, message);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, contactsOnly);
add(enable);
add(subjectLabel);
add(subject);
add(messageLabel);
add(message);
add(contactsOnly);
add(submit);
}
}
@@ -0,0 +1,82 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import sample.appsforyourdomain.gmailsettings.Defaults;
import com.google.gdata.util.ServiceException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.SpringLayout;
/**
* Tab containing all the web clip information.
*/
public class TabWebClip extends Tab {
protected SpringLayout layout;
protected JCheckBox webClipEnabled;
protected JButton submit;
public TabWebClip() {
super("WebClip", "");
layout = new SpringLayout();
setLayout(layout);
webClipEnabled = new JCheckBox("Enable Web clip:", Defaults.WEBCLIP_ENABLE);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (GmailSettingsClient.settings == null) {
JOptionPane.showMessageDialog(null, GmailSettingsClient.ERROR_AUTHENTICATION_REQUIRED,
GmailSettingsClient.APP_TITLE, JOptionPane.ERROR_MESSAGE);
return;
}
try {
GmailSettingsClient.settings.changeWebClip(GmailSettingsClient.users.getSelectedUsers(),
webClipEnabled.isSelected());
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
});
layout.putConstraint(SpringLayout.WEST, webClipEnabled, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, webClipEnabled, 5, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.WEST, submit, 5, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, submit, 15, SpringLayout.SOUTH, webClipEnabled);
add(webClipEnabled);
add(submit);
}
}
@@ -0,0 +1,82 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import javax.swing.JTabbedPane;
/**
* Handles adding all the tabs needed.
*/
public class TabbedPane extends JTabbedPane {
protected Tab authenticationTab;
protected Tab signatureTab;
protected Tab labelTab;
protected Tab filtersTab;
protected Tab sendasTab;
protected Tab popTab;
protected Tab forwardingTab;
protected Tab imapTab;
protected Tab vacationTab;
protected Tab languageTab;
protected Tab generalTab;
protected Tab webClipTab;
/**
* Create an instance of all tabs required, and add them to the pane.
*/
public TabbedPane() {
super(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
authenticationTab = new TabAuthentication();
signatureTab = new TabSignature();
labelTab = new TabLabel();
filtersTab = new TabFilter();
sendasTab = new TabSendAs();
popTab = new TabPop();
forwardingTab = new TabForwarding();
imapTab = new TabImap();
vacationTab = new TabVacation();
languageTab = new TabLanguage();
generalTab = new TabGeneral();
webClipTab = new TabWebClip();
addTab(authenticationTab);
addTab(signatureTab);
addTab(labelTab);
addTab(filtersTab);
addTab(sendasTab);
addTab(popTab);
addTab(forwardingTab);
addTab(imapTab);
addTab(vacationTab);
addTab(languageTab);
addTab(generalTab);
addTab(webClipTab);
this.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
}
/**
* Helper method for adding tabs to the pane.
*
* @param tab The tab to be added to the JTabbedPane
*/
protected void addTab(Tab tab) {
super.addTab(tab.getName(), null, tab, tab.getTooltip());
}
}
@@ -0,0 +1,140 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.gmailsettings.gui;
import com.google.gdata.client.appsforyourdomain.AppsForYourDomainQuery;
import com.google.gdata.client.appsforyourdomain.UserService;
import com.google.gdata.data.Link;
import com.google.gdata.data.appsforyourdomain.provisioning.UserEntry;
import com.google.gdata.data.appsforyourdomain.provisioning.UserFeed;
import com.google.gdata.util.ServiceException;
import java.awt.GridLayout;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
/**
* Panel that uses the provisioning API to display all the users from a domain.
*/
public class UsersPanel extends JPanel {
protected JList users;
protected DefaultListModel usersListModel;
protected JScrollPane usersPane;
/**
* Sets up the panel.
*/
public UsersPanel() {
usersListModel = new DefaultListModel();
users = new JList();
users.setModel(usersListModel);
usersPane = new JScrollPane(users);
setLayout(new GridLayout(1, 1));
add(usersPane);
}
/**
* @return Returns a list of all the users that were selected in the panel.
*/
public List<String> getSelectedUsers() {
Object[] tmp = users.getSelectedValues();
List<String> susers = new ArrayList<String>();
for (int i = 0; i < tmp.length; i++) {
susers.add(tmp[i].toString());
}
return susers;
}
/**
* Refreshes the panel to display the users.
*
* @param domain The domain in which settings will be modified.
* @param username The user name (not email) of a domain administrator.
* @param password The user's password on the domain.
*/
public void refresh(String domain, String username, String password) {
try {
UserFeed usersFeed = getUsers(domain, username, password);
usersListModel.clear();
Iterator<UserEntry> userIterator = usersFeed.getEntries().iterator();
while (userIterator.hasNext()) {
usersListModel.addElement(userIterator.next().getLogin().getUserName());
}
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
} catch (ServiceException e) {
JOptionPane.showMessageDialog(null, e, GmailSettingsClient.APP_TITLE,
JOptionPane.ERROR_MESSAGE);
}
}
/**
* Retrieves the first 100 users from the domain.
*
* @param domain The domain in which settings will be modified.
* @param username The user name (not email) of a domain administrator.
* @param password The user's password on the domain.
* @return UserFeed containing all the user accounts in the domain.
* @throws MalformedURLException if the batch feed URL cannot be constructed.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the insert request failed due to system error.
*/
protected UserFeed getUsers(String domain, String username, String password)
throws MalformedURLException, IOException, ServiceException {
String domainUrlBase = null;
UserFeed allUsers = null;
UserService userService = new UserService(GmailSettingsClient.APP_TITLE);
userService.setUserCredentials(username + "@" + domain, password);
domainUrlBase = "https://www.google.com/a/feeds/" + domain + "/";
URL retrieveUrl = new URL(domainUrlBase + "user/2.0/");
AppsForYourDomainQuery query = new AppsForYourDomainQuery(retrieveUrl);
query.setStartUsername(null);
allUsers = new UserFeed();
UserFeed currentPage;
Link nextLink;
do {
currentPage = userService.query(query, UserFeed.class);
allUsers.getEntries().addAll(currentPage.getEntries());
nextLink = currentPage.getLink(Link.Rel.NEXT, Link.Type.ATOM);
if (nextLink != null) {
retrieveUrl = new URL(nextLink.getHref());
}
} while (nextLink != null);
return allUsers;
}
}
@@ -0,0 +1,532 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.labs.provisioning;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.gdata.client.appsforyourdomain.AppsPropertyService;
import com.google.gdata.data.Link;
import com.google.gdata.data.appsforyourdomain.AppsForYourDomainException;
import com.google.gdata.data.appsforyourdomain.generic.GenericEntry;
import com.google.gdata.data.appsforyourdomain.generic.GenericFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
/**
* This is a sample client with helper methods that demonstrates the usage of
* Organization Management APIs. These APIs help you create organization units
* and manage your units/users.
*
* An OrgUnit path is the URL-encoding (e.g., using URLEncoder.encode) of an
* OrgUnit's lineage, concatenated together with the slash ('/') character.
* E.g.,
*
* path = URLEncode.encode(parentName, "UTF-8") + "/" +
* URLEncode.encode(childName, "UTF-8");
*
*
*
*/
public class OrgManagementSampleClient {
public enum OrgUnitProperty {
NAME, DESCRIPTION, PARENT_ORG_UNIT_PATH, BLOCK_INHERTANCE, USERS_TO_MOVE
}
private AppsPropertyService service;
private String domain = null;
public static Logger LOGGER = Logger.getLogger(OrgManagementSampleClient.class.getName());
/**
* Parameterized constructor for authentication.
*
* @param adminEmail Domain administrator's email address
* @param password admin account password
* @param domain the primary domain name
* @param appName application identifier
* @throws AuthenticationException If an authentication error occurs.
*/
public OrgManagementSampleClient(String adminEmail, String password, String domain,
String appName)
throws AuthenticationException {
this(domain, appName);
service.setUserCredentials(adminEmail, password);
}
/**
* Parameterized constructor for authentication.
*
* @param domain the primary domain name
* @param appName application identifier
* @throws AuthenticationException If an authentication error occurs.
*/
public OrgManagementSampleClient(String domain, String appName) throws AuthenticationException {
service = new AppsPropertyService(appName);
this.domain = domain;
}
/**
* A utility method to create an OrgPath from a list of OrgUnits with parent
* as first list item, first child as second item and so on.
*
* @param orgUnits
* @return a OrgUnitPath from a given list of OrgUnit names.
* @throws UnsupportedEncodingException
*/
public String createOrgPathFromOrgUnits(List<String> orgUnits)
throws UnsupportedEncodingException {
StringBuilder path = new StringBuilder();
for (String orgUnit : orgUnits) {
if (path.length() != 0) {
path.append('/');
}
path.append(URLEncoder.encode(orgUnit, "UTF-8"));
}
return path.toString();
}
/**
* Retrieves the customer Id that will be used for all other operations.
*
* @param domain
* @return a GenericEntry
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public GenericEntry retrieveCustomerId(String domain) throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
GenericEntry entry =
service.getEntry(new URL("https://apps-apis.google.com/a/feeds/customer/2.0/customerId"),
GenericEntry.class);
return entry;
}
/**
* Create a new organization unit under the given parent.
*
* @param customerId the unique Id of the customer retrieved through customer
* feed.
* @param orgUnitName the new organization name.
* @param parentOrgUnitPath the path of the parent organization unit where '/'
* denotes the root of the organization hierarchy. For any OrgUnits to
* be created directly under root, specify '/' as parent path.
* @param description a description for the organization unit created.
* @param blockInheritance if true, blocks inheritance of policies from parent
* units.
* @return a GenericEntry instance of the newly created org unit.
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public GenericEntry createOrganizationUnit(String customerId, String orgUnitName,
String parentOrgUnitPath, String description, boolean blockInheritance)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
GenericEntry entry = new GenericEntry();
entry.addProperty("parentOrgUnitPath", parentOrgUnitPath);
entry.addProperty("description", description);
entry.addProperty("name", orgUnitName);
entry.addProperty("blockInheritance", String.valueOf(blockInheritance));
entry =
service.insert(new URL("https://apps-apis.google.com/a/feeds/orgunit/2.0/" + customerId),
entry);
return entry;
}
/**
* Retrieves an organization unit from the customer's domain.
*
* @param customerId
* @param orgUnitPath the path of the unit to be retrieved for e.g /corp
* @return a GenericEntry instance.
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public GenericEntry retrieveOrganizationUnit(String customerId, String orgUnitPath)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
GenericEntry entry =
service.getEntry(new URL("https://apps-apis.google.com/a/feeds/orgunit/2.0/" + customerId
+ "/" + orgUnitPath), GenericEntry.class);
return entry;
}
/**
* Retrieves all organization units for the given customer account.
*
* @param customerId
* @return a List of organization unit entries
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public List<GenericEntry> retrieveAllOrganizationUnits(String customerId)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
return retrieveAllPages(new URL("https://apps-apis.google.com/a/feeds/orgunit/2.0/"
+ customerId + "?get=all"));
}
/**
* Utility method that follows the next link and retrieves all pages of a
* feed.
*
* @param feedUrl Url of the feed.
* @return a List of GenericEntries in the feed queried.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
private List<GenericEntry> retrieveAllPages(URL feedUrl) throws IOException, ServiceException {
List<GenericEntry> allEntries = new ArrayList<GenericEntry>();
try {
do {
GenericFeed feed = service.getFeed(feedUrl, GenericFeed.class);
allEntries.addAll(feed.getEntries());
feedUrl = (feed.getNextLink() == null) ? null : new URL(feed.getNextLink().getHref());
} while (feedUrl != null);
} catch (ServiceException se) {
AppsForYourDomainException ae = AppsForYourDomainException.narrow(se);
throw (ae != null) ? ae : se;
}
return allEntries;
}
/**
* Retrieves all the child units of the given organization unit.
*
* @param customerId
* @param orgUnitPath
* @return a List of GenericEntry instances.
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public List<GenericEntry> retrieveChildOrganizationUnits(String customerId, String orgUnitPath)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
return retrieveAllPages(new URL("https://apps-apis.google.com/a/feeds/orgunit/2.0/"
+ customerId + "?get=children&orgUnitPath=" + URLEncoder.encode(orgUnitPath, "UTF-8")));
}
/**
* Deletes the given organization unit. The unit must not have any OrgUsers or
* any child OrgUnits to be deleted.
*
* @param customerId
* @param orgUnitPath
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public void deleteOrganizationUnit(String customerId, String orgUnitPath)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
service.delete(new URL("https://apps-apis.google.com/a/feeds/orgunit/2.0/" + customerId + "/"
+ orgUnitPath));
}
/**
* Updates the given organization attributes. USERS_TO_MOVE is a comma
* separated list of email addresses that are to be moved across orgUnits
*
* @param customerId
* @param orgUnitPath
* @param attributes a map of <code>OrgUnitProperty</code> and value to be
* updated.
* @return the updated GenericEntry
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public GenericEntry updateOrganizationUnit(String customerId, String orgUnitPath,
Map<OrgUnitProperty, String> attributes) throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
GenericEntry entry = new GenericEntry();
for (Map.Entry<OrgUnitProperty, String> mapEntry : attributes.entrySet()) {
String value = mapEntry.getValue();
if (value == null || value.length() == 0) {
continue;
}
switch (mapEntry.getKey()) {
case NAME:
entry.addProperty("name", value);
break;
case PARENT_ORG_UNIT_PATH:
entry.addProperty("parentUnitPath", value);
break;
case DESCRIPTION:
entry.addProperty("description", value);
break;
case BLOCK_INHERTANCE:
entry.addProperty("blockInheritance", value);
break;
case USERS_TO_MOVE:
entry.addProperty("usersToMove", value);
break;
default:
break;
}
}
return service.update(new URL("https://apps-apis.google.com/a/feeds/orgunit/2.0/" + customerId
+ "/" + orgUnitPath), entry);
}
/**
* Updates the organization of the given user in a given organization.
*
* @param customerId
* @param orgUserEmail the email address of the user
* @param oldOrgUnitPath optional: the old organization unit path. If
* specified, validates the OrgUser's current path.
* @param newOrgUnitPath the new organization unit path.
* @return a GenericEntry with the updated organization user.
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public GenericEntry updateOrganizationUser(String customerId, String orgUserEmail,
String oldOrgUnitPath, String newOrgUnitPath) throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
GenericEntry entry = new GenericEntry();
if (oldOrgUnitPath != null && oldOrgUnitPath.length() != 0) {
entry.addProperty("oldOrgUnitPath", oldOrgUnitPath);
}
entry.addProperty("orgUnitPath", newOrgUnitPath);
return service.update(new URL("https://apps-apis.google.com/a/feeds/orguser/2.0/" + customerId
+ "/" + orgUserEmail), entry);
}
/**
* Retrieves the details of a given organization user.
*
* @param customerId
* @param orgUserEmail the email address of the organization user.
* @return a GenericEntry instance
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public GenericEntry retrieveOrganizaionUser(String customerId, String orgUserEmail)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
return service.getEntry(new URL("https://apps-apis.google.com/a/feeds/orguser/2.0/"
+ customerId + "/" + orgUserEmail), GenericEntry.class);
}
/**
* Retrieves the first page of OrgUnit entries. For subsequent pages, use
* <code>retrieveNextPage</code>.
*
* @param customerId
* @return a GenericFeed with a single page of entries.
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public GenericFeed retrieveFirstPageOfOrganizationUsers(String customerId)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
return service.getFeed(new URL("https://apps-apis.google.com/a/feeds/orguser/2.0/" + customerId
+ "?get=all"), GenericFeed.class);
}
/**
* Retrieves a single page of entries given an atom:link.
*
* @param next the next atom:link which can be obtained from a feed
* <code>GenericFeed.getNextLink()</code>
* @return a GenericFeed with a single page of entries.
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public GenericFeed retrieveNextPage(Link next) throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
return service.getFeed(new URL(next.getHref()), GenericFeed.class);
}
/**
* Retrieves all the users from all the organizations of the customer. If you
* have more than a few hundred of OrgUsers, you should use pagination methods
* - <code>retrieveFirstPageOfOrganizationUsers</code> and
* <code>retrieveNextPage</code>
*
* @param customerId
* @return a List of GenericEntry instances
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public List<GenericEntry> retrieveAllOrganizationUsers(String customerId)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
return retrieveAllPages(new URL("https://apps-apis.google.com/a/feeds/orguser/2.0/"
+ customerId + "?get=all"));
}
/**
* Retrieves the first page of OrgUser entries in a given OrgUnit. For
* subsequent pages, use
* <code>retrieveNextPage(GenericFeed.getNextLink())</code>.
*
* @param customerId
* @param orgUnitPath
* @return a GenericFeed with a single page of entries.
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public GenericFeed retrieveFirstPageOfOrganizationUsersByOrgUnit(String customerId,
String orgUnitPath) throws AppsForYourDomainException, MalformedURLException, IOException,
ServiceException {
return service.getFeed(new URL("https://apps-apis.google.com/a/feeds/orguser/2.0/" + customerId
+ "?get=children&orgUnitPath=" + URLEncoder.encode(orgUnitPath, "UTF-8")),
GenericFeed.class);
}
/**
* Retrieves all the users under a given organization unit. If you have more
* than a few hundred of OrgUsers, you should use pagination methods -
* <code>retrieveFirstPageOfOrganizationUsersByOrgUnit</code> and
* <code>retrieveNextPage</code>
*
* @param customerId
* @param orgUnitPath
* @return a List of organization users.
* @throws AppsForYourDomainException
* @throws MalformedURLException
* @throws IOException
* @throws ServiceException
*/
public List<GenericEntry> retrieveAllOrganizationUsersByOrgUnit(String customerId,
String orgUnitPath) throws AppsForYourDomainException, MalformedURLException, IOException,
ServiceException {
return retrieveAllPages(new URL("https://apps-apis.google.com/a/feeds/orguser/2.0/"
+ customerId + "?get=children&orgUnitPath=" + URLEncoder.encode(orgUnitPath, "UTF-8")));
}
/**
* @param args
* @throws AuthenticationException
*/
public static void main(String[] args) throws AuthenticationException {
try {
if (args.length != 4) {
System.out
.println("Usage: java OrgManagementSampleClient <admin@example.com> <adminpassword> "
+ "<domain> <testUserEmail>");
System.exit(1);
}
String adminEmail = args[0];
String adminPassword = args[1];
String domain = args[2];
String user = args[3];
String customerId = null;
OrgManagementSampleClient client =
new OrgManagementSampleClient(adminEmail, adminPassword, domain, "org-api-sample-"
+ domain);
GenericEntry entry = null;
GenericFeed feed = null;
entry = client.retrieveCustomerId(customerId);
customerId = entry.getProperty("customerId");
LOGGER.log(Level.INFO, "Retrieved Customer ID - " + customerId);
entry =
client.createOrganizationUnit(customerId, "system", "/", "System Organization", false);
LOGGER.log(Level.INFO, "Created new OrgUnit - " + entry.getAllProperties());
entry = client.retrieveOrganizationUnit(customerId, "system");
LOGGER.log(Level.INFO, "Retrieved OrgUnit - " + entry.getAllProperties());
List<GenericEntry> allUnits = client.retrieveAllOrganizationUnits(customerId);
LOGGER.log(Level.INFO, "Retrieved all OrgUnits - " + allUnits.size());
allUnits = client.retrieveChildOrganizationUnits(customerId, "/");
LOGGER.log(Level.INFO, "Retrieved all child units - " + allUnits.size());
LOGGER.log(Level.INFO, "Updating OrgUnit 'system'");
Map<OrgUnitProperty, String> attributes = new HashMap<OrgUnitProperty, String>();
attributes.put(OrgUnitProperty.DESCRIPTION, "testchanged");
entry = client.updateOrganizationUnit(customerId, "system", attributes);
LOGGER.log(Level.INFO, "Updated OrgUnit description - " + entry.getAllProperties());
client.retrieveOrganizaionUser(customerId, user);
LOGGER.log(Level.INFO, "Retrieved OrgUser - " + entry.getAllProperties());
entry = client.updateOrganizationUser(customerId, user, "/", "system");
LOGGER.log(Level.INFO, "Updated OrgUser - " + entry.getAllProperties());
// For pagination, use retrieveFirstPageOfOrganizationUsers() and
// retrieveNextPage(feed.getNextLink())
List<GenericEntry> allUsers = client.retrieveAllOrganizationUsers(customerId);
LOGGER.log(Level.INFO, "Retrieved User count: " + allUsers.size());
allUsers = client.retrieveAllOrganizationUsersByOrgUnit(customerId, "system");
LOGGER.log(Level.INFO, "Retrieved User count: " + allUsers.size());
LOGGER.log(Level.INFO, "OrgPath construction - "
+ client.createOrgPathFromOrgUnits(Arrays.asList("parent", "firstChild",
"childOfFirstChild")));
// cleanup
client.updateOrganizationUser(customerId, user, "system", "/");
// cleanup
client.deleteOrganizationUnit(customerId, "system");
} catch (AppsForYourDomainException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,503 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.labs.provisioning;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.gdata.client.appsforyourdomain.AppsPropertyService;
import com.google.gdata.data.Link;
import com.google.gdata.data.appsforyourdomain.AppsForYourDomainException;
import com.google.gdata.data.appsforyourdomain.generic.GenericEntry;
import com.google.gdata.data.appsforyourdomain.generic.GenericFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
/**
* Sample client that uses multi-domain feeds to create users, aliases in one of
* the user's domains.
*
*
*
*/
public class ProvisioningApiMultiDomainSampleClient {
private AppsPropertyService service;
private String domain = null;
public enum UserProperty {
USER_EMAIL, PASSWORD, FIRST_NAME, LAST_NAME, HASH_FUNCTION, ADMIN, SUSPENDED,
CHANGE_PASSWORD_AT_NEXT_LOGIN, QUOTA, IP_WHITELIST
}
public static Logger LOGGER =
Logger.getLogger(ProvisioningApiMultiDomainSampleClient.class.getName());
/**
* Parameterized constructor for authentication.
*
* @param adminEmail Domain administrator's email address
* @param password admin account password
* @param domain the primary domain name
* @param appName application identifier
* @throws AuthenticationException If an authentication error occurs.
*/
public ProvisioningApiMultiDomainSampleClient(String adminEmail, String password, String domain,
String appName) throws AuthenticationException {
this(domain, appName);
service.setUserCredentials(adminEmail, password);
}
/**
* Constructor for credential-less services - OAuth.
*/
public ProvisioningApiMultiDomainSampleClient(String domain, String appName) {
service = new AppsPropertyService(appName);
this.domain = domain;
}
/**
* Creates an alias email for the user identified by the given email address.
*
* @param aliasEmail The alias email to create for the given user.
* @param userEmail User's primary email address.
* @return the newly created alias GenericEntry instance.
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public GenericEntry createAlias(String aliasEmail, String userEmail)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
GenericEntry entry = new GenericEntry();
entry.addProperty("userEmail", userEmail);
entry.addProperty("aliasEmail", aliasEmail);
return service.insert(new URL("https://apps-apis.google.com/a/feeds/alias/2.0/" + domain),
entry);
}
/**
* Retrieves the alias entry for the given email alias.
*
* @param aliasEmail the user email alias.
* @return GenericEntry
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public GenericEntry retrieveAlias(String aliasEmail) throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
return service.getEntry(new URL("https://apps-apis.google.com/a/feeds/alias/2.0/" + domain
+ "/" + aliasEmail), GenericEntry.class);
}
/**
* Utility method that follows the next link and retrieves all pages of a
* feed.
*
* @param feedUrl Url of the feed.
* @return a List of GenericEntries in the feed queried.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
private List<GenericEntry> retrieveAllPages(URL feedUrl) throws IOException, ServiceException {
List<GenericEntry> allEntries = new ArrayList<GenericEntry>();
try {
do {
GenericFeed feed = service.getFeed(feedUrl, GenericFeed.class);
allEntries.addAll(feed.getEntries());
feedUrl = (feed.getNextLink() == null) ? null : new URL(feed.getNextLink().getHref());
} while (feedUrl != null);
} catch (ServiceException se) {
AppsForYourDomainException ae = AppsForYourDomainException.narrow(se);
throw (ae != null) ? ae : se;
}
return allEntries;
}
/**
* Retrieves all email aliases created in the customer domain. If you have more than
* a few hundred aliases, you must use <code>retrieveFirstPageOfAliases</code> and
* <code>retrieveNextPage</code>.
*
* @return a List of GenericEntry objects.
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public List<GenericEntry> retrieveAllAliases() throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
return retrieveAllPages(new URL("https://apps-apis.google.com/a/feeds/alias/2.0/" + domain));
}
/**
* Retrieves first page of email aliases created in the customer domain. To
* retrieve subsequent pages, use <code>retrieveNextPage</code> with
* <code>GenericFeed.getNextLink()</code>
*
* @return a List of GenericEntry objects.
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public GenericFeed retrieveFirstPageOfAliases() throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
return service.getFeed(new URL("https://apps-apis.google.com/a/feeds/alias/2.0/" + domain),
GenericFeed.class);
}
/**
* Retrieves all aliases created for the user identified by the given email
* address.
*
* @param userEmail
* @return a List of GenericEntry objects
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public List<GenericEntry> retrieveAllUserAliases(String userEmail)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
return retrieveAllPages(new URL("https://apps-apis.google.com/a/feeds/alias/2.0/" + domain
+ "/" + userEmail));
}
/**
* Deletes the given alias.
*
* @param aliasEmail
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public void deleteAlias(String aliasEmail) throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
service.delete(new URL("https://apps-apis.google.com/a/feeds/alias/2.0/" + domain + "/"
+ aliasEmail));
}
/**
* Creates a new user with the given email address in the customer domain.
*
* @param email User email of the new account.
* @param password
* @param firstName
* @param lastName
* @return a GenericEntry instance of the newly created user.
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public GenericEntry createUser(String email, String password, String firstName, String lastName)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
GenericEntry entry = new GenericEntry();
entry.addProperty("userEmail", email);
entry.addProperty("password", password);
entry.addProperty("firstName", firstName);
entry.addProperty("lastName", lastName);
return service
.insert(new URL("https://apps-apis.google.com/a/feeds/user/2.0/" + domain), entry);
}
/**
* Creates a user with one or more optional attributes set.
*
* @param email
* @param password
* @param firstName
* @param lastName
* @param optionalAttributes a hashmap of user property
* <code>UserProperty</code> and values.
* @return a GenericEntry instance of the newly created user.
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public GenericEntry createUser(String email, String password, String firstName, String lastName,
Map<UserProperty, String> optionalAttributes) throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
GenericEntry entry = new GenericEntry();
entry.addProperty("userEmail", email);
entry.addProperty("password", password);
entry.addProperty("firstName", firstName);
entry.addProperty("lastName", lastName);
for (Map.Entry<UserProperty, String> mapEntry : optionalAttributes.entrySet()) {
String value = mapEntry.getValue();
if (value == null || value.length() == 0) {
continue;
}
switch (mapEntry.getKey()) {
case HASH_FUNCTION:
entry.addProperty("name", value);
break;
case ADMIN:
entry.addProperty("isAdmin", value);
break;
case SUSPENDED:
entry.addProperty("isSuspended", value);
break;
case CHANGE_PASSWORD_AT_NEXT_LOGIN:
entry.addProperty("isChangePasswordAtNextLogin", value);
break;
case QUOTA:
entry.addProperty("quotaInGb", value);
break;
case IP_WHITELIST:
entry.addProperty("ipWhitelisted", value);
break;
default:
break;
}
}
return service
.insert(new URL("https://apps-apis.google.com/a/feeds/user/2.0/" + domain), entry);
}
/**
*
* @param email
* @return a GenricEntry instance
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public GenericEntry retrieveUser(String email) throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
return service.getEntry(new URL("https://apps-apis.google.com/a/feeds/user/2.0/" + domain + "/"
+ email), GenericEntry.class);
}
/**
* Retrieves a feed of all users in the customer domain. If you have more than
* a few hundred users, you must use <code>retrieveFirstPageOfUsers</code> and
* <code>retrieveNextPage</code>.
*
* @return a list of GenericEntry objects
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public List<GenericEntry> retrieveAllUsers() throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
return retrieveAllPages(new URL("https://apps-apis.google.com/a/feeds/user/2.0/" + domain));
}
/**
* Retrieves the first page of users. To retrieve subsequent pages, use
* <code>retrieveNextPage</code> with <code>GenericFeed.getNextLink()</code>
*
* @return a page of user entries.
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public GenericFeed retrieveFirstPageOfUsers() throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
return service.getFeed(new URL("https://apps-apis.google.com/a/feeds/user/2.0/" + domain),
GenericFeed.class);
}
/**
* Retrieves a single page of entries given an atom:link.
*
* @param next the next atom:link which can be obtained from a feed
* <code>GenericFeed.getNextLink()</code>
* @return a GenericFeed with a single page of entries.
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public GenericFeed retrieveNextPage(Link next) throws AppsForYourDomainException,
MalformedURLException, IOException, ServiceException {
return service.getFeed(new URL(next.getHref()), GenericFeed.class);
}
/**
* Updates the given user attributes.
*
* @param email
* @param updatedAttributes a key-Value map of attributes to be updated
* @return updated GenericEntry
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public GenericEntry updateUser(String email, Map<String, String> updatedAttributes)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
GenericEntry entry = new GenericEntry();
entry.addProperties(updatedAttributes);
return service.update(new URL("https://apps-apis.google.com/a/feeds/user/2.0/" + domain + "/"
+ email), entry);
}
/**
* deletes the given user account from the customer domain.
*
* @param email
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public void deleteUser(String email) throws AppsForYourDomainException, MalformedURLException,
IOException, ServiceException {
service
.delete(new URL("https://apps-apis.google.com/a/feeds/user/2.0/" + domain + "/" + email));
}
/**
* changes the primary email address of the user to the given email address
*
* @param oldEmailAddress
* @param newEmailAddress
* @return the updated GenericEntry
* @throws AppsForYourDomainException If a Provisioning API specific error
* occurs.
* @throws ServiceException If a generic GData framework error occurs.
* @throws IOException If an error occurs communicating with the GData
* service.
*/
public GenericEntry updateEmailAddress(String oldEmailAddress, String newEmailAddress)
throws AppsForYourDomainException, MalformedURLException, IOException, ServiceException {
GenericEntry entry = new GenericEntry();
entry.addProperty("userEmail", oldEmailAddress);
entry.addProperty("newEmail", newEmailAddress);
return service.update(new URL("https://apps-apis.google.com/a/feeds/user/userEmail/2.0/"
+ domain + "/" + oldEmailAddress), entry);
}
/**
* The main driver for the sample.
*
* @param args java ProvisioningApiMultiDomainSampleClient [admin@example.com]
* [adminpassword] [primarydomain] [secondarydomain]
*/
public static void main(String[] args) {
if (args.length != 4) {
System.out
.println("Usage: java ProvisioningApiMultiDomainSampleClient <admin@example.com> "
+ "<adminpassword> <primarydomain> <secondarydomain>");
System.exit(1);
}
String adminEmail = args[0];
String adminPassword = args[1];
String primaryDomain = args[2];
String secondaryDomain = args[3];
try {
ProvisioningApiMultiDomainSampleClient client =
new ProvisioningApiMultiDomainSampleClient(adminEmail, adminPassword, primaryDomain,
"multidomain-api-sample-" + primaryDomain);
long time = System.currentTimeMillis();
String userEmail = "test-" + time + "@" + secondaryDomain;
GenericEntry entry = client.createUser(userEmail, "p@ssw0rd", "firstName", "lastName");
LOGGER.log(Level.INFO, "Created user - " + entry.getProperty("userEmail"));
entry = client.retrieveUser(userEmail);
LOGGER.log(Level.INFO, "Retrieved user - " + entry.getProperty("userEmail"));
// create user with optional attributes
Map<UserProperty, String> optionalAttributes = new HashMap<UserProperty, String>();
optionalAttributes.put(UserProperty.ADMIN, String.valueOf(true));
optionalAttributes.put(UserProperty.SUSPENDED, String.valueOf(false));
optionalAttributes.put(UserProperty.HASH_FUNCTION, "MD5");
entry =
client.createUser("test2-" + time + "@" + secondaryDomain,
"0f359740bd1cda994f8b55330c86d845", "firstName", "lastName", optionalAttributes);
LOGGER.log(Level.INFO, "Created user with optional attributes- "
+ entry.getProperty("userEmail"));
Map<String, String> updatedAttributes = new HashMap<String, String>();
updatedAttributes.put("lastName", "Smith");
updatedAttributes.put("isSuspended", "true");
entry = client.updateUser(userEmail, updatedAttributes);
LOGGER.log(Level.INFO, "Updated user - " + entry.getProperty("lastName"));
List<GenericEntry> users = client.retrieveAllUsers();
LOGGER.log(Level.INFO, "Retrieved all users - " + users.size());
// Alias operations
String aliasEmail = "alias-" + time + "@" + secondaryDomain;
entry = client.createAlias(aliasEmail, userEmail);
LOGGER.log(Level.INFO, "Created alias - " + entry.getProperty("aliasEmail"));
entry = client.retrieveAlias(aliasEmail);
LOGGER.log(Level.INFO, "Retrieved alias - " + entry.getProperty("aliasEmail"));
List<GenericEntry> aliases = client.retrieveAllAliases();
LOGGER.log(Level.INFO, "Retrieved all aliases - " + users.size());
// cleanup
client.deleteAlias(aliasEmail);
LOGGER.log(Level.INFO, "Deleted - " + aliasEmail);
client.deleteUser(userEmail);
LOGGER.log(Level.INFO, "Deleted - " + userEmail);
client.deleteUser("test2-" + time + "@" + secondaryDomain);
} catch (AuthenticationException e) {
e.printStackTrace();
} catch (AppsForYourDomainException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ServiceException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,310 @@
/* Copyright (c) 2008 Google 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.appsforyourdomain.migration;
import com.google.gdata.client.appsforyourdomain.migration.MailItemService;
import sample.util.SimpleCommandLineParser;
import com.google.gdata.data.appsforyourdomain.migration.Label;
import com.google.gdata.data.appsforyourdomain.migration.MailItemEntry;
import com.google.gdata.data.appsforyourdomain.migration.MailItemFeed;
import com.google.gdata.data.appsforyourdomain.migration.MailItemProperty;
import com.google.gdata.data.appsforyourdomain.migration.Rfc822Msg;
import com.google.gdata.data.batch.BatchStatus;
import com.google.gdata.data.batch.BatchUtils;
import com.google.gdata.util.ServiceException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This is the client library for the Google Apps Email Migration API. It
* shows how the MailItemService can be used to migrate mail into GMail.
*/
public class AppsForYourDomainMigrationClient {
private static final Logger LOGGER =
Logger.getLogger(AppsForYourDomainMigrationClient.class.getName());
// Number of email messages to insert.
private static final int ITEMS_TO_BATCH = 5;
// The mail message to migrate.
private static String rfcTxt =
"Received: by 10.143.160.15 with HTTP; Mon, 16 Jul 2007 10:12:26 -0700 (P"
+ "DT)\r\n"
+ "Message-ID: <c8acb6980707161012i5d395392p5a6d8d14a8582613@mail."
+ "gmail.com>\r\n"
+ "Date: Mon, 16 Jul 2007 10:12:26 -0700\r\n"
+ "From: \"Mr. Serious\" <serious@domain.com>\r\n"
+ "To: \"Mr. Admin\" <admin@domain.com>\r\n"
+ "Subject: Subject \r\n"
+ "MIME-Version: 1.0\r\n"
+ "Content-Type: text/plain; charset=ISO-8859-1; format=flowed\r\n"
+ "Content-Transfer-Encoding: 7bit\r\n"
+ "Content-Disposition: inline\r\n"
+ "Delivered-To: admin@domain.com\r\n"
+ "\r\n"
+ "This is a message delivered via the Email Migration API\r\n"
+ "\r\n";
private static final String MIGRATED_LABEL = "Migrated Email";
private final String domain;
private final String destinationUser;
private final MailItemService mailItemService;
/**
* Constructs an AppsForYourDomainMigrationClient for the given domain using
* the given admin credentials.
*
* @param username The username (not email) of a domain user or administrator
* @param password The user's password on the domain
* @param domain The domain in which mail is being migrated
* @param destinationUser the destination user to whom mail should be migrated
*/
public AppsForYourDomainMigrationClient(String username, String password,
String domain, String destinationUser) throws Exception {
this.domain = domain;
if (destinationUser == null) {
this.destinationUser = username;
} else {
this.destinationUser = destinationUser;
}
// Set up the mail item service.
mailItemService = new MailItemService("exampleCo-exampleApp-1");
mailItemService.setUserCredentials(username + "@" + domain, password);
// Run the sample.
runSample();
}
/**
* Main driver for the sample; migrates a batch feed of email messages
* and prints the results.
*/
private void runSample() {
// Create labels for mail items to be inserted.
List<String> labels = new ArrayList<String>();
labels.add(MIGRATED_LABEL);
// Set properties for mail items to be inserted. We want all these
// mail items to be unread and sent to the inbox (in addition to being
// labeled).
List<MailItemProperty> properties = new ArrayList<MailItemProperty>();
properties.add(MailItemProperty.UNREAD);
properties.add(MailItemProperty.INBOX);
MailItemEntry[] entries = new MailItemEntry[ITEMS_TO_BATCH];
for (int i = 0; i < entries.length; i++) {
entries[i] = setupMailItem(rfcTxt, properties, labels);
}
// Send several emails in a batch.
LOGGER.log(Level.INFO, "Inserting " + Integer.toString(ITEMS_TO_BATCH)
+ " mail items in a batch.");
try {
MailItemFeed feed = batchInsertMailItems(entries);
// Check for failure in the returned entries.
int failedInsertions = 0, successfulInsertions = 0;
for (MailItemEntry returnedEntry : feed.getEntries()) {
if (BatchUtils.isFailure(returnedEntry)) {
BatchStatus status = BatchUtils.getBatchStatus(returnedEntry);
LOGGER.log(Level.SEVERE, "Entry "
+ BatchUtils.getBatchId(returnedEntry) + " failed insertion: "
+ status.getCode() + " " + status.getReason());
failedInsertions++;
} else {
successfulInsertions++;
}
}
LOGGER.log(Level.INFO, "Batch insertion: "
+ Integer.toString(successfulInsertions) + " succeeded, "
+ Integer.toString(failedInsertions) + " failed.");
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Caught IOException: " + e.toString());
e.printStackTrace();
} catch (ServiceException e) {
LOGGER.log(Level.SEVERE, "Caught ServiceException: " + e.toString());
e.printStackTrace();
}
}
/**
* Inserts one or more MailItem entries in a single batch operation. Using
* batch insertion is helpful in reducing HTTP overhead.
*
* @param mailItems one or more {@link MailItemEntry} objects
* @return a feed with the result of each operation in a separate
* {@link MailItemEntry} object.
* @throws IOException if an error occurs while communicating with the GData
* service.
* @throws ServiceException if the insert request failed due to system error.
*/
private MailItemFeed batchInsertMailItems(MailItemEntry ... mailItems)
throws ServiceException, IOException {
LOGGER.log(Level.INFO, "Batch inserting " + Integer.toString(
mailItems.length) + " mailItems");
MailItemFeed feed = new MailItemFeed();
for (int i = 0; i < mailItems.length; i++) {
BatchUtils.setBatchId(mailItems[i], Integer.toString(i));
feed.getEntries().add(mailItems[i]);
}
return mailItemService.batch(domain, destinationUser, feed);
}
/**
* Helper method to read a file and return its contents as a text string,
* with lines separated by "\r\n" (CR+LF) style newlines.
* @param location the path to the file
* @return the String contents of the file
* @throws IOException if an error occurs reading the file
*/
private static String readFile(String location) throws IOException {
FileInputStream is = new FileInputStream(new File(location));
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer fileContents = new StringBuffer();
String newLine = br.readLine();
while (newLine != null) {
fileContents.append(newLine);
fileContents.append("\r\n");
newLine = br.readLine();
}
br.close();
return fileContents.toString();
}
/**
* Helper method to set up a new MailItemEntry with the given values.
*
* @param rfcText the RFC822 text of the message
* @param properties a list of properties to be applied to the message
* @param labels a list of labels the message should have when inserted into
* Gmail
* @return the {@code MailItemEntry} set up with the message, labels and
* properties
*/
private MailItemEntry setupMailItem(String rfcText,
List<MailItemProperty> properties, List<String> labels) {
// Unique subject and message id are required so that GMail does not
// suppress duplicate messages
String randomFactor = Integer.toString(100000 +
(new Random()).nextInt(900000));
rfcText = rfcText.replace("Subject: Subject",
"Subject: Unique Subject " + randomFactor);
rfcText = rfcText.replace("Message-ID: <", "Message-ID: <" + randomFactor);
Rfc822Msg rfcMsg = new Rfc822Msg(rfcText);
// create MailItemEntry with appropriate data
MailItemEntry mailItem = new MailItemEntry();
mailItem.setRfc822Msg(rfcMsg);
for (String label : labels) {
mailItem.addLabel(new Label(label));
}
for (MailItemProperty property : properties) {
mailItem.addMailProperty(property);
}
return mailItem;
}
/**
* Prints the command line usage of this sample application.
*/
private static void usage() {
System.out.println("Usage: java AppsForYourDomainMigrationClient"
+ " --username <username> --password <password> --domain <domain>\n"
+ " [--destination_user <destination_user>] [--data_file <file>]");
System.out.println();
System.out.println("A simple application that demonstrates how to migrate"
+ " email mesages to a Google Apps email account. Authenticates using"
+ " the provided login credentials, then migrates a sample message to"
+ " your own account (if you are a user) or to the specified"
+ " destination account (if you are a domain administrator).");
System.out.println();
System.out.println("If --data_file is specified, an RFC822 message will be"
+ " read from the given file; otherwise, a sample message will be"
+ "used.");
System.out.println();
System.out.println("Specify username and destination_user as just the name,"
+ " not email address. For example, to migrate mail to joe@example.com"
+ " use these options: --username joe --password your_password"
+ " --domain example.com");
}
/**
* Main entry point. Parses arguments and creates and invokes the
* AppsForYourDomainMigrationClient.
*
* Usage: java AppsForYourDomainMigrationClient --username &lt;user&gt;
* --password &lt;pass&gt; --domain &lt;domain&gt;
* [--destination_user &lt;destination_user&gt;] [--data_file &lt;file&gt;]
*/
public static void main(String[] arg) throws Exception {
SimpleCommandLineParser parser = new SimpleCommandLineParser(arg);
// Parse command-line flags
String username = parser.getValue("username");
String password = parser.getValue("password");
String domain = parser.getValue("domain");
String destinationUser = parser.getValue("destination_user");
String emailFileName = parser.getValue("data_file");
boolean help = parser.containsKey("help");
if (help || (username == null) || (password == null)
|| (domain == null)) {
usage();
System.exit(1);
}
// If the user supplied a filename, read the email data from it.
if (emailFileName != null) {
// Read email text
LOGGER.log(Level.INFO, "Reading email data from file");
rfcTxt = readFile(emailFileName);
LOGGER.log(Level.INFO, "Finished reading email data");
}
new AppsForYourDomainMigrationClient(username, password, domain,
destinationUser);
}
}
@@ -0,0 +1,35 @@
AppsForYourDomainMigrationClient: A simple application that
demonstrates how to migrate email messages to a Google Apps
email account.
To migrate mail as a Google Apps user, invoke as follows:
java AppsForYourDomainMigrationClient --username <user>
--password <password> --domain <domain>
For example:
java AppsForYourDomainMigrationClient --username jdoe
--password mypass --domain example.com
To migrate mail as a Google Apps administrator, also specify
the destination mailbox (username) for the mail upload:
java AppsForYourDomainMigrationClient --username <user>
--password <password> --domain <domain>
--destination_user <username>
For example:
java AppsForYourDomainMigrationClient --username admin
--password mypass --domain example.com --destination_user jdoe
By default, the sample application will migrate a simple,
example email message. You can also specify a message on disk,
assuming it is already in the RFC822 standard format, by passing
the --data_file argument:
java AppsForYourDomainMigrationClient --username jdoe
--password mypass --domain example.com
--data_file /home/jdoe/my_rfc822_message.txt