Google Contacts angefangen

This commit is contained in:
2012-07-30 18:00:46 +02:00
parent 60e93c2a92
commit a21badb635
10 changed files with 2788 additions and 13 deletions
+13
View File
@@ -0,0 +1,13 @@
String s = "var in_call_list = new Array(new Array(\"19.07.2012 14:31:07\",\"01707118717\",\"\",\"00:00:00\"), new Array(\"18.07.2012 20:18:21\",\"0891247111672\",\"\",\"00:00:00\"), new Array(\"18.07.2012 17:54:26\",\"0891247111672\",\"\",\"00:00:00\"), new Array(\"18.07.2012 16:14:55\",\"03060926337\",\"1\",\"00:20:55\"), new Array(\"18.07.2012 15:32:18\",\"030835384891\",\"1\",\"00:02:31\"), new Array(\"18.07.2012 15:09:16\",\"03060926337\",\"1\",\"00:13:26\"), new Array(\"17.07.2012 15:55:23\",\"030468194451\",\"1\",\"00:00:40\"), new Array(\"17.07.2012 12:13:04\",\"016097941642\",\"\",\"00:00:00\"), new Array(\"17.07.2012 11:00:57\",\"02143056256\",\"1\",\"00:02:07\"), new Array(\"16.07.2012 20:16:42\",\"03053142218\",\"1\",\"00:01:09\"), new Array(\"16.07.2012 13:02:37\",\" \",\"\",\"00:00:00\"), new Array(\"16.07.2012 09:40:42\",\"03091701406\",\"1\",\"00:00:22\"));";
String t = s.substring(39);
String[] result = t.split("new Array\\(");
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
System.out.println(result[x].substring(7,11));
System.out.println(result[x].substring(result[x].lastIndexOf('"') - 8, result[x].lastIndexOf('"')));
System.out.println(result[x].substring(1));
System.out.println(result[x].substring(23));
System.out.println(result[x].substring(23, result[x].indexOf('"', 23)));
System.out.println();
}
+16
View File
@@ -4,6 +4,12 @@
<groupId>WebCallerID</groupId> <groupId>WebCallerID</groupId>
<artifactId>WebCallerID</artifactId> <artifactId>WebCallerID</artifactId>
<version>1.0.2</version> <version>1.0.2</version>
<repositories>
<repository>
<id>mandubian-mvn</id>
<url>http://mandubian-mvn.googlecode.com/svn/trunk/mandubian-mvn/repository</url>
</repository>
</repositories>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>log4j</groupId> <groupId>log4j</groupId>
@@ -25,5 +31,15 @@
<artifactId>jsap</artifactId> <artifactId>jsap</artifactId>
<version>2.1</version> <version>2.1</version>
</dependency> </dependency>
<dependency>
<groupId>com.google.gdata</groupId>
<artifactId>gdata-core-1.0</artifactId>
<version>1.36.0</version>
</dependency>
<dependency>
<groupId>com.google.gdata</groupId>
<artifactId>gdata-contacts-3.0</artifactId>
<version>1.36.0</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
@@ -23,6 +23,7 @@ import org.apache.log4j.Level;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout; import org.apache.log4j.PatternLayout;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException; import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult; import com.martiansoftware.jsap.JSAPResult;
@@ -56,10 +57,10 @@ public class CallerIdClient {
log.info("logging in to Speedport router"); log.info("logging in to Speedport router");
postUrl("https://speedport.ip/index/login.cgi", "Username=" + URLEncoder.encode("admin", "UTF-8") + "&" + "Password=" postUrl("https://speedport.ip/index/login.cgi", "Username=" + URLEncoder.encode("admin", "UTF-8") + "&" + "Password="
+ password); + password);
log.info("retrieving call list"); log.info("retrieving call list");
getUrl("https://speedport.ip/auth/hcti_status_telanrl.php?cookie=SessionID_R3," + cookie); getUrl("https://speedport.ip/auth/hcti_status_telanrl.php?cookie=SessionID_R3," + cookie);
log.info("logging out"); log.info("logging out");
postUrl("https://speedport.ip/auth/logout.cgi?RequestFile=/pub/top_beenden.php&cookie=SessionID_R3," + cookie, ""); postUrl("https://speedport.ip/auth/logout.cgi?RequestFile=/pub/top_beenden.php&cookie=SessionID_R3," + cookie, "");
} catch (Exception e) { } catch (Exception e) {
@@ -135,7 +136,9 @@ public class CallerIdClient {
if (cookie != null) { if (cookie != null) {
connection.setRequestProperty("Cookie", "SessionID_R3=" + cookie); connection.setRequestProperty("Cookie", "SessionID_R3=" + cookie);
} }
// connection.setRequestProperty("Referer", "https://speedport.ip/auth/hcti_status_telanrl.php?cookie=SessionID_R3," + cookie); // connection.setRequestProperty("Referer",
// "https://speedport.ip/auth/hcti_status_telanrl.php?cookie=SessionID_R3,"
// + cookie);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
if (payload.length() > 0) { if (payload.length() > 0) {
@@ -151,7 +154,7 @@ public class CallerIdClient {
} else { } else {
if (line.equals("4")) if (line.equals("4"))
log.error(" could not log in, Speedport adminstration account is currently in use"); log.error(" could not log in, Speedport adminstration account is currently in use");
else else
log.error(" received unexpected response: " + line); log.error(" received unexpected response: " + line);
} }
} }
@@ -190,12 +193,12 @@ public class CallerIdClient {
String pass = config.getString("e-mail password"); String pass = config.getString("e-mail password");
Properties props = System.getProperties(); Properties props = System.getProperties();
props.put("mail.smtp.ssl.enable", "true"); props.put("mail.smtp.ssl.enable", "true");
//props.put("mail.smtp.starttls.enable", "true"); // props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host); props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from); props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass); props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "465"); props.put("mail.smtp.port", "465");
//props.put("mail.smtp.port", "587"); // props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true"); props.put("mail.smtp.auth", "true");
String[] to = config.getStringArray("recipient"); String[] to = config.getStringArray("recipient");
@@ -216,9 +219,9 @@ public class CallerIdClient {
message.setSubject(TEXT_MAILPREFIX + number); message.setSubject(TEXT_MAILPREFIX + number);
message.setText(TEXT_MAILPREFIX + number + "\n" + time); message.setText(TEXT_MAILPREFIX + number + "\n" + time);
log.info("sending message for call from " + number + " at " + time); log.info("sending message for call from " + number + " at " + time);
Transport transport = session.getTransport("smtp"); Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass); transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients()); transport.sendMessage(message, message.getAllRecipients());
@@ -261,11 +264,19 @@ public class CallerIdClient {
.setGreedy(true); .setGreedy(true);
recipients.setHelp("e-mail addresses to send notifications to"); recipients.setHelp("e-mail addresses to send notifications to");
jsap.registerParameter(recipients); jsap.registerParameter(recipients);
FlaggedOption googleUsername = new FlaggedOption("google username").setStringParser(JSAP.STRING_PARSER).setShortFlag('u');
googleUsername.setHelp("the Google username for contact name resolution");
jsap.registerParameter(googleUsername);
FlaggedOption googlePassword = new FlaggedOption("google password").setStringParser(JSAP.STRING_PARSER).setShortFlag('p');
googleUsername.setHelp("the Google password for contact name resolution");
jsap.registerParameter(googlePassword);
Switch debugSwitch = new Switch("debug").setLongFlag("debug"); Switch debugSwitch = new Switch("debug").setLongFlag("debug");
debugSwitch.setHelp("print debug messages"); debugSwitch.setHelp("print debug messages");
jsap.registerParameter(debugSwitch); jsap.registerParameter(debugSwitch);
Switch helpSwitch = new Switch("help").setLongFlag("help").setShortFlag('?'); Switch helpSwitch = new Switch("help").setLongFlag("help").setShortFlag('?');
helpSwitch.setHelp("print help and exit"); helpSwitch.setHelp("print help and exit");
jsap.registerParameter(helpSwitch); jsap.registerParameter(helpSwitch);
@@ -285,11 +296,10 @@ public class CallerIdClient {
log.error("Usage: java -jar speedportcallerid.jar " + jsap.getUsage() + "\n\n" + jsap.getHelp()); log.error("Usage: java -jar speedportcallerid.jar " + jsap.getUsage() + "\n\n" + jsap.getHelp());
System.exit(-1002); System.exit(-1002);
} }
if (config.getBoolean("debug")) { if (config.getBoolean("debug")) {
log.setLevel(Level.DEBUG); log.setLevel(Level.DEBUG);
} } else {
else {
log.setLevel(Level.INFO); log.setLevel(Level.INFO);
} }
log.info("Log level set to " + log.getLevel()); log.info("Log level set to " + log.getLevel());
@@ -0,0 +1,116 @@
package de.tilman.callerId;
import java.io.IOException;
import java.net.URL;
import com.google.gdata.client.Query;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.data.extensions.PhoneNumber;
import com.google.gdata.util.ServiceException;
public class GoogleTest {
private final ContactsService service;
public GoogleTest() {
service = new ContactsService("<var>SpeedportCallerIdClient</var>");
try {
service.setUserCredentials("tilman.liero@gmail.com", "Gr4m80tt");
printAllContacts(service);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getContactName(String telephoneNumber) {
return "";
}
public static void printAllContacts(ContactsService myService) throws ServiceException, IOException {
// Request the feed
URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
// ContactFeed resultFeed = myService.getFeed(feedUrl, ContactFeed.class);
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(500);
ContactFeed resultFeed = myService.query(myQuery, ContactFeed.class);
// Print the results
System.out.println(resultFeed.getTitle().getPlainText());
int i = 0;
for (ContactEntry entry : resultFeed.getEntries()) {
System.out.println("Nr. " + ++i);
if (entry.hasName()) {
Name name = entry.getName();
if (name.hasFullName()) {
String fullNameToDisplay = name.getFullName().getValue();
if (name.getFullName().hasYomi()) {
fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
}
System.out.println("\\\t\\\t" + fullNameToDisplay);
}
if (name.hasNamePrefix()) {
System.out.println("\\\t\\\t" + name.getNamePrefix().getValue());
}
if (name.hasGivenName()) {
String givenNameToDisplay = name.getGivenName().getValue();
if (name.getGivenName().hasYomi()) {
givenNameToDisplay += " (" + name.getGivenName().getYomi() + ")";
}
System.out.println("\\\t\\\t" + givenNameToDisplay);
}
if (name.hasAdditionalName()) {
String additionalNameToDisplay = name.getAdditionalName().getValue();
if (name.getAdditionalName().hasYomi()) {
additionalNameToDisplay += " (" + name.getAdditionalName().getYomi() + ")";
}
System.out.println("\\\t\\\t" + additionalNameToDisplay);
}
if (name.hasFamilyName()) {
String familyNameToDisplay = name.getFamilyName().getValue();
if (name.getFamilyName().hasYomi()) {
familyNameToDisplay += " (" + name.getFamilyName().getYomi() + ")";
}
System.out.println("\\\t\\\t" + familyNameToDisplay);
}
if (name.hasNameSuffix()) {
System.out.println("\\\t\\\t" + name.getNameSuffix().getValue());
}
} else {
System.out.println("\t (no name found)");
}
System.out.println("Email addresses:");
for (Email email : entry.getEmailAddresses()) {
System.out.print(" " + email.getAddress());
if (email.getRel() != null) {
System.out.print(" rel:" + email.getRel());
}
if (email.getLabel() != null) {
System.out.print(" label:" + email.getLabel());
}
if (email.getPrimary()) {
System.out.print(" (primary) ");
}
System.out.print("\n");
}
System.out.println("Telephone Numbers:");
for (PhoneNumber phone : entry.getPhoneNumbers()) {
System.out.print(" " + phone.getPhoneNumber());
if (phone.getUri() != null) {
System.out.print(" uri:" + phone.getUri());
}
System.out.println();
}
}
}
public static void main(String[] args) {
new GoogleTest();
}
}
@@ -0,0 +1,619 @@
package de.tilman.callerid.example;
/* 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.
*/
import com.google.gdata.client.Query;
import com.google.gdata.client.Service;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.client.http.HttpGDataRequest;
import de.tilman.callerid.example.ContactsExampleParameters.Actions;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Link;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.contacts.ContactGroupEntry;
import com.google.gdata.data.contacts.ContactGroupFeed;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.NoLongerAvailableException;
import com.google.gdata.util.ServiceException;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Example command-line utility that demonstrates how to use the Google Data API
* Java client libraries for Contacts. The example allows to run all the basic
* contact related operations such as adding new contact, listing all contacts,
* updating existing contacts, deleting the contacts.
* <p/>
* Full documentation about the API can be found at:
* http://code.google.com/apis/contacts/
*
*
*
*
*/
public class ContactsExample {
private enum SystemGroup {
MY_CONTACTS("Contacts", "My Contacts"),
FRIENDS("Friends", "Friends"),
FAMILY("Family", "Family"),
COWORKERS("Coworkers", "Coworkers");
private final String systemGroupId;
private final String prettyName;
SystemGroup(String systemGroupId, String prettyName) {
this.systemGroupId = systemGroupId;
this.prettyName = prettyName;
}
static SystemGroup fromSystemGroupId(String id) {
for(SystemGroup group : SystemGroup.values()) {
if (id.equals(group.systemGroupId)) {
return group;
}
}
throw new IllegalArgumentException("Unrecognized system group id: " + id);
}
@Override
public String toString() {
return prettyName;
}
}
/**
* Base URL for the feed
*/
private final URL feedUrl;
/**
* Service used to communicate with contacts feed.
*/
private final ContactsService service;
/**
* Projection used for the feed
*/
private final String projection;
/**
* The ID of the last added contact or group.
* Used in case of script execution - you can add and remove contact just
* created.
*/
private static String lastAddedId;
/**
* Reference to the logger for setting verbose mode.
*/
private static final Logger httpRequestLogger =
Logger.getLogger(HttpGDataRequest.class.getName());
/**
* Contacts Example.
*
* @param parameters command line parameters
*/
public ContactsExample(ContactsExampleParameters parameters)
throws MalformedURLException, AuthenticationException {
projection = parameters.getProjection();
String url = parameters.getBaseUrl()
+ (parameters.isGroupFeed() ? "groups/" : "contacts/")
+ parameters.getUserName() + "/" + projection;
feedUrl = new URL(url);
service = new ContactsService("Google-contactsExampleApp-3");
String userName = parameters.getUserName();
String password = parameters.getPassword();
if (userName == null || password == null) {
return;
}
service.setUserCredentials(userName, password);
}
/**
* Deletes a contact or a group
*
* @param parameters the parameters determining contact to delete.
*/
private void deleteEntry(ContactsExampleParameters parameters)
throws IOException, ServiceException {
if (parameters.isGroupFeed()) {
// get the Group then delete it
ContactGroupEntry group = getGroupInternal(parameters.getId());
if (group == null) {
System.err.println("No Group found with id: " + parameters.getId());
return;
}
group.delete();
} else {
// get the contact then delete them
ContactEntry contact = getContactInternal(parameters.getId());
if (contact == null) {
System.err.println("No contact found with id: " + parameters.getId());
return;
}
contact.delete();
}
}
/**
* Updates a contact or a group. Presence of any property of a given kind
* (im, phone, mail, etc.) causes the existing properties of that kind to be
* replaced.
*
* @param parameters parameters storing updated contact values.
*/
public void updateEntry(ContactsExampleParameters parameters)
throws IOException, ServiceException {
if (parameters.isGroupFeed()) {
ContactGroupEntry group = buildGroup(parameters);
// get the group then update it
ContactGroupEntry canonicalGroup = getGroupInternal(parameters.getId());
canonicalGroup.setTitle(group.getTitle());
canonicalGroup.setContent(group.getContent());
// update fields
List<ExtendedProperty> extendedProperties =
canonicalGroup.getExtendedProperties();
extendedProperties.clear();
if (group.hasExtendedProperties()) {
extendedProperties.addAll(group.getExtendedProperties());
}
printGroup(canonicalGroup.update());
} else {
ContactEntry contact = buildContact(parameters);
// get the contact then update it
ContactEntry canonicalContact = getContactInternal(parameters.getId());
ElementHelper.updateContact(canonicalContact, contact);
printContact(canonicalContact.update());
}
}
/**
* Gets a contact by it's id.
*
* @param id the id of the contact.
* @return the ContactEntry or null if not found.
*/
private ContactEntry getContactInternal(String id)
throws IOException, ServiceException {
return service.getEntry(
new URL(id.replace("/base/", "/" + projection + "/")),
ContactEntry.class);
}
/**
* Gets a Group by it's id.
*
* @param id the id of the group.
* @return the GroupEntry or null if not found.
*/
private ContactGroupEntry getGroupInternal(String id)
throws IOException, ServiceException {
return service.getEntry(
new URL(id.replace("/base/", "/" + projection + "/")),
ContactGroupEntry.class);
}
/**
* Print the contents of a ContactEntry to System.err.
*
* @param contact The ContactEntry to display.
*/
private static void printContact(ContactEntry contact) {
System.err.println("Id: " + contact.getId());
if (contact.getTitle() != null) {
System.err.println("Contact name: " + contact.getTitle().getPlainText());
} else {
System.err.println("Contact has no name");
}
System.err.println("Last updated: " + contact.getUpdated().toUiString());
if (contact.hasDeleted()) {
System.err.println("Deleted:");
}
ElementHelper.printContact(System.err, contact);
Link photoLink = contact.getLink(
"http://schemas.google.com/contacts/2008/rel#photo", "image/*");
System.err.println("Photo link: " + photoLink.getHref());
String photoEtag = photoLink.getEtag();
System.err.println(" Photo ETag: "
+ (photoEtag != null ? photoEtag : "(No contact photo uploaded)"));
System.err.println("Self link: " + contact.getSelfLink().getHref());
System.err.println("Edit link: " + contact.getEditLink().getHref());
System.err.println("ETag: " + contact.getEtag());
System.err.println("-------------------------------------------\n");
}
/**
* Prints the contents of a GroupEntry to System.err
*
* @param groupEntry The GroupEntry to display
*/
private static void printGroup(ContactGroupEntry groupEntry) {
System.err.println("Id: " + groupEntry.getId());
System.err.println("Group Name: " + groupEntry.getTitle().getPlainText());
System.err.println("Last Updated: " + groupEntry.getUpdated());
System.err.println("Extended Properties:");
for (ExtendedProperty property : groupEntry.getExtendedProperties()) {
if (property.getValue() != null) {
System.err.println(" " + property.getName() + "(value) = " +
property.getValue());
} else if (property.getXmlBlob() != null) {
System.err.println(" " + property.getName() + "(xmlBlob) = " +
property.getXmlBlob().getBlob());
}
}
System.err.print("Which System Group: ");
if (groupEntry.hasSystemGroup()) {
SystemGroup systemGroup
= SystemGroup.fromSystemGroupId(groupEntry.getSystemGroup().getId());
System.err.println(systemGroup);
} else {
System.err.println("(Not a system group)");
}
System.err.println("Self Link: " + groupEntry.getSelfLink().getHref());
if (!groupEntry.hasSystemGroup()) {
// System groups are not modifiable, and thus don't have an edit link.
System.err.println("Edit Link: " + groupEntry.getEditLink().getHref());
}
System.err.println("-------------------------------------------\n");
}
/**
* Processes script consisting of sequence of parameter lines in the same
* form as command line parameters.
*
* @param example object controlling the execution
* @param parameters parameters passed from command line
*/
private static void processScript(ContactsExample example,
ContactsExampleParameters parameters) throws IOException,
ServiceException {
BufferedReader reader =
new BufferedReader(new FileReader(parameters.getScript()));
try {
String line;
while ((line = reader.readLine()) != null) {
ContactsExampleParameters newParams =
new ContactsExampleParameters(parameters, line);
processAction(example, newParams);
if (lastAddedId != null) {
parameters.setId(lastAddedId);
lastAddedId = null;
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
/**
* Performs action specified as action parameter.
*
* @param example object controlling the execution
* @param parameters parameters from command line or script
*/
private static void processAction(ContactsExample example,
ContactsExampleParameters parameters) throws IOException,
ServiceException {
Actions action = parameters.getAction();
System.err.println("Executing action: " + action);
switch (action) {
case LIST:
example.listEntries(parameters);
break;
case QUERY:
example.queryEntries(parameters);
break;
case ADD:
example.addEntry(parameters);
break;
case DELETE:
example.deleteEntry(parameters);
break;
case UPDATE:
example.updateEntry(parameters);
break;
default:
System.err.println("No such action");
}
}
/**
* Query entries (Contacts/Groups) according to parameters specified.
*
* @param parameters parameter for contact quest
*/
private void queryEntries(ContactsExampleParameters parameters)
throws IOException, ServiceException {
Query myQuery = new Query(feedUrl);
if (parameters.getUpdatedMin() != null) {
DateTime startTime = DateTime.parseDateTime(parameters.getUpdatedMin());
myQuery.setUpdatedMin(startTime);
}
if (parameters.getMaxResults() != null) {
myQuery.setMaxResults(parameters.getMaxResults().intValue());
}
if (parameters.getStartIndex() != null) {
myQuery.setStartIndex(parameters.getStartIndex());
}
if (parameters.isShowDeleted()) {
myQuery.setStringCustomParameter("showdeleted", "true");
}
if (parameters.getRequireAllDeleted() != null) {
myQuery.setStringCustomParameter("requirealldeleted",
parameters.getRequireAllDeleted());
}
if (parameters.getSortorder() != null) {
myQuery.setStringCustomParameter("sortorder", parameters.getSortorder());
}
if (parameters.getOrderBy() != null) {
myQuery.setStringCustomParameter("orderby", parameters.getOrderBy());
}
if (parameters.getGroup() != null) {
myQuery.setStringCustomParameter("group", parameters.getGroup());
}
try {
if (parameters.isGroupFeed()) {
ContactGroupFeed groupFeed = service.query(
myQuery, ContactGroupFeed.class);
for (ContactGroupEntry entry : groupFeed.getEntries()) {
printGroup(entry);
}
System.err.println("Total: " + groupFeed.getEntries().size()
+ " entries found");
} else {
ContactFeed resultFeed = service.query(myQuery, ContactFeed.class);
for (ContactEntry entry : resultFeed.getEntries()) {
printContact(entry);
}
System.err.println("Total: " + resultFeed.getEntries().size()
+ " entries found");
}
} catch (NoLongerAvailableException ex) {
System.err.println(
"Not all placehorders of deleted entries are available");
}
}
/**
* List Contacts or Group entries (no parameter are taken into account)
* Note! only 25 results will be returned - this is default.
*
* @param parameters
*/
private void listEntries(ContactsExampleParameters parameters)
throws IOException, ServiceException {
if (parameters.isGroupFeed()) {
ContactGroupFeed groupFeed =
service.getFeed(feedUrl, ContactGroupFeed.class);
System.err.println(groupFeed.getTitle().getPlainText());
for (ContactGroupEntry entry : groupFeed.getEntries()) {
printGroup(entry);
}
System.err.println("Total: " + groupFeed.getEntries().size() +
" groups found");
} else {
ContactFeed resultFeed = service.getFeed(feedUrl, ContactFeed.class);
// Print the results
System.err.println(resultFeed.getTitle().getPlainText());
for (ContactEntry entry : resultFeed.getEntries()) {
printContact(entry);
// Since 2.0, the photo link is always there, the presence of an actual
// photo is indicated by the presence of an ETag.
Link photoLink = entry.getLink(
"http://schemas.google.com/contacts/2008/rel#photo", "image/*");
if (photoLink.getEtag() != null) {
Service.GDataRequest request =
service.createLinkQueryRequest(photoLink);
request.execute();
InputStream in = request.getResponseStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
RandomAccessFile file = new RandomAccessFile(
"/tmp/" + entry.getSelfLink().getHref().substring(
entry.getSelfLink().getHref().lastIndexOf('/') + 1), "rw");
byte[] buffer = new byte[4096];
for (int read = 0; (read = in.read(buffer)) != -1;
out.write(buffer, 0, read)) {}
file.write(out.toByteArray());
file.close();
in.close();
request.end();
}
}
System.err.println("Total: " + resultFeed.getEntries().size()
+ " entries found");
}
}
/**
* Adds contact or group entry according to the parameters specified.
*
* @param parameters parameters for contact adding
*/
private void addEntry(ContactsExampleParameters parameters)
throws IOException, ServiceException {
if (parameters.isGroupFeed()) {
ContactGroupEntry addedGroup =
service.insert(feedUrl, buildGroup(parameters));
printGroup(addedGroup);
lastAddedId = addedGroup.getId();
} else {
ContactEntry addedContact =
service.insert(feedUrl, buildContact(parameters));
printContact(addedContact);
// Store id of the added contact so that scripts can use it in next steps
lastAddedId = addedContact.getId();
}
}
/**
* Build ContactEntry from parameters.
*
* @param parameters parameters
* @return A contact.
*/
private static ContactEntry buildContact(
ContactsExampleParameters parameters) {
ContactEntry contact = new ContactEntry();
ElementHelper.buildContact(contact, parameters.getElementDesc());
return contact;
}
/**
* Builds GroupEntry from parameters
*
* @param parameters ContactExamplParameters
* @return GroupEntry Object
*/
private static ContactGroupEntry buildGroup(
ContactsExampleParameters parameters) {
ContactGroupEntry groupEntry = new ContactGroupEntry();
ElementHelper.buildGroup(groupEntry, parameters.getElementDesc());
return groupEntry;
}
/**
* Displays usage information.
*/
private static void displayUsage() {
String usageInstructions =
"USAGE:\n"
+ " -----------------------------------------------------------\n"
+ " Basic command line usage:\n"
+ " ContactsExample [<options>] <authenticationInformation> "
+ "<--contactfeed|--groupfeed> "
+ "--action=<action> [<action options>] "
+ "(default contactfeed)\n"
+ " Scripting commands usage:\n"
+ " contactsExample [<options>] <authenticationInformation> "
+ "<--contactfeed|--groupfeed> --script=<script file> "
+ "(default contactFeed) \n"
+ " Print usage (this screen):\n"
+ " --help\n"
+ " -----------------------------------------------------------\n\n"
+ " Options: \n"
+ " --base-url=<url to connect to> "
+ "(default http://www.google.com/m8/feeds/) \n"
+ " --projection=[thin|full|property-KEY] "
+ "(default thin)\n"
+ " --verbose : dumps communication information\n"
+ " Authentication Information (obligatory on command line): \n"
+ " --username=<username email> --password=<password>\n"
+ " Actions: \n"
+ " * list list all contacts\n"
+ " * query query contacts\n"
+ " options:\n"
+ " --showdeleted : shows also deleted contacts\n"
+ " --updated-min=YYYY-MM-DDTHH:MM:SS : only updated "
+ "after the time specified\n"
+ " --requre-all-deleted=[true|false] : specifies "
+ "server behaviour in case of placeholders for deleted entries are"
+ "lost. Relevant only if --showdeleted and --updated-min also "
+ "provided.\n"
+ " --orderby=lastmodified : order by last modified\n"
+ " --sortorder=[ascending|descending] : sort order\n"
+ " --max-results=<n> : return maximum n results\n"
+ " --start-index=<n> : return results starting from "
+ "the starting index\n"
+ " --querygroupid=<groupid> : return results from the "
+ "group\n"
+ " * add add new contact\n"
+ " options:\n"
+ ElementHelper.getUsageString()
+ " * delete delete contact\n"
+ " options:\n"
+ " --id=<contact id>\n"
+ " * update updates contact\n"
+ " options:\n"
+ " --id=<contact id>\n"
+ ElementHelper.getUsageString()
;
System.err.println(usageInstructions);
}
/**
* Run the example program.
*
* @param args Command-line arguments.
*/
public static void main(String[] args) throws ServiceException, IOException {
ContactsExampleParameters parameters = new ContactsExampleParameters(args);
if (parameters.isVerbose()) {
httpRequestLogger.setLevel(Level.FINEST);
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.FINEST);
httpRequestLogger.addHandler(handler);
httpRequestLogger.setUseParentHandlers(false);
}
if (parameters.numberOfParameters() == 0 || parameters.isHelp()
|| (parameters.getAction() == null && parameters.getScript() == null)) {
displayUsage();
return;
}
if (parameters.getUserName() == null || parameters.getPassword() == null) {
System.err.println("Both username and password must be specified.");
return;
}
// Check that at most one of contactfeed and groupfeed has been provided
if (parameters.isContactFeed() && parameters.isGroupFeed()) {
throw new RuntimeException("Only one of contactfeed / groupfeed should" +
"be specified");
}
ContactsExample example = new ContactsExample(parameters);
if (parameters.getScript() != null) {
processScript(example, parameters);
} else {
processAction(example, parameters);
}
System.out.flush();
}
}
@@ -0,0 +1,284 @@
package de.tilman.callerid.example;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Keeps structured command line parameters for ContactsExample program.
*
*
*
*/
public class ContactsExampleParameters {
/**
* Actions that can be executed with the sample application.
* They are all lowercase because they are passed as parameters
* and then converted using valueOf() method.
*/
public enum Actions {
LIST,
QUERY,
ADD,
DELETE,
UPDATE;
}
private static final String DEFAULT_FEED = "https://www.google.com/m8/feeds/";
private static final String DEFAULT_PROJECTION = "thin";
/**
* Keeps map of parameter -> value.
* Note! Tree Map is used to keep sequence of fields.
*/
private SortedMap<String, String> parameterValueMap =
new TreeMap<String,String>();
/**
* List of command line parameters likely to be the description of an
* element.
* Those parameters are added to the list, what are not recognized as a valid
* command line argument (nor an action or option).
* These parameters are later parsed by {@link ElementParser} and processed by
* {@link ElementHelper}.
*/
private List<String> elementDesc = new LinkedList<String>();
/**
* Stores names of parameters.
*/
public enum ParameterNames {
SCRIPT("script"),
ACTION("action"),
BASE_URL("base-url"),
USERNAME("username"),
PASSWORD("password"),
CONTACTFEED("contactfeed"),
GROUPFEED("groupfeed"),
SHOWDELETED("showdeleted"),
REQUIRE_ALL_DELETED("require-all-deleted"),
UPDATED_MIN("updated-min"),
OREDERBY("orderby"),
SORTORDER("sortorder"),
MAX_RESULTS("max-results"),
START_INDEX("start-index"),
HELP("help"),
PROJECTION("projection"),
VERBOSE("verbose"),
ID("id"),
GROUP("querygroupid"),
;
private final String parameterName;
ParameterNames(String parameterName) {
this.parameterName = parameterName;
}
public String getParameterName() {
return parameterName;
}
}
/**
* Constructor used in case script parameter is used.
*
* @param commandLineParams command line parameters
* @param scriptLine line read from a file
*/
public ContactsExampleParameters(ContactsExampleParameters commandLineParams,
String scriptLine) {
parameterValueMap.putAll(commandLineParams.parameterValueMap);
elementDesc.addAll(commandLineParams.elementDesc);
fillFromArguments(scriptLine.split(" "));
}
/**
* Constructor used when no script is passed at command line
* only the command line parameters are used.
*
* @param arguments arguments in form of array
*/
public ContactsExampleParameters(String arguments[]) {
fillFromArguments(arguments);
}
/**
* Parse arguments.
*
* @param arguments arguments in form of array
*/
private void fillFromArguments(String[] arguments) {
for (String string : arguments) {
if (!string.startsWith("--")) {
throw new IllegalArgumentException("illegal parameter: " + string);
}
String param = string.substring(2);
String params[] = param.split("=", 2);
boolean found = false;
for (ParameterNames parameterName : ParameterNames.values()) {
String name = parameterName.getParameterName().toLowerCase();
if (name.equals(params[0])) {
if (params.length == 1) {
parameterValueMap.put(params[0], "");
} else {
parameterValueMap.put(params[0], params[1]);
}
found = true;
break;
}
}
if (!found) {
elementDesc.add(string);
}
}
verifyAllParameters();
}
/**
* Verify if we understand all parameters.
*
* @throws IllegalArgumentException in case there
* is a parameter which is not expected.
*/
private void verifyAllParameters() {
for (String parameter : parameterValueMap.keySet()) {
verifyParameter(parameter);
}
}
private void verifyParameter(String name) {
for (ParameterNames parameter : ParameterNames.values()) {
if (name.equals(parameter.getParameterName())) {
return;
}
}
throw new IllegalArgumentException(
"Parameter " + name + " is not correct.");
}
String getParameter(ParameterNames parameters) {
return parameterValueMap.get(parameters.getParameterName());
}
String getScript() {
return getParameter(ParameterNames.SCRIPT);
}
Actions getAction() {
String actionString = getParameter(ParameterNames.ACTION);
if (actionString == null) {
return null;
}
return Actions.valueOf(actionString.toUpperCase());
}
String getBaseUrl() {
String url = getParameter(ParameterNames.BASE_URL);
if (url == null) {
url = DEFAULT_FEED;
}
return url;
}
String getUserName() {
return getParameter(ParameterNames.USERNAME);
}
String getPassword() {
return getParameter(ParameterNames.PASSWORD);
}
boolean isContactFeed() {
return getParameter(ParameterNames.CONTACTFEED) != null;
}
boolean isGroupFeed() {
return getParameter(ParameterNames.GROUPFEED) != null;
}
boolean isShowDeleted() {
return getParameter(ParameterNames.SHOWDELETED) != null;
}
String getRequireAllDeleted() {
return getParameter(ParameterNames.REQUIRE_ALL_DELETED);
}
String getUpdatedMin() {
return getParameter(ParameterNames.UPDATED_MIN);
}
String getOrderBy() {
return getParameter(ParameterNames.OREDERBY);
}
String getSortorder() {
return getParameter(ParameterNames.SORTORDER);
}
Integer getMaxResults() {
String maxResString = getParameter(ParameterNames.MAX_RESULTS);
if (maxResString != null) {
Integer val = Integer.parseInt(maxResString);
if (val.intValue() < 1) {
throw new RuntimeException(
ParameterNames.MAX_RESULTS + " should be > 0" );
}
return val;
}
return null;
}
Integer getStartIndex() {
String startIndexString = getParameter(ParameterNames.START_INDEX);
if (startIndexString != null) {
Integer val = Integer.parseInt(startIndexString);
if (val.intValue() < 1) {
throw new RuntimeException(
ParameterNames.START_INDEX + " should be > 0" );
}
return val;
}
return null;
}
boolean isHelp() {
return (getParameter(ParameterNames.HELP) != null);
}
boolean isVerbose() {
return (getParameter(ParameterNames.VERBOSE) != null);
}
String getId() {
return getParameter(ParameterNames.ID);
}
void setId(String id) {
parameterValueMap.put(ParameterNames.ID.getParameterName(), id);
}
String getProjection() {
String projection = getParameter(ParameterNames.PROJECTION);
if (projection == null) {
projection = DEFAULT_PROJECTION;
}
return projection;
}
String getGroup() {
return getParameter(ParameterNames.GROUP);
}
List<String> getElementDesc() {
return elementDesc;
}
int numberOfParameters() {
return parameterValueMap.size();
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,67 @@
package de.tilman.callerid.example;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactGroupEntry;
import java.io.PrintStream;
/**
* Interface to define the common methods of the {@link ElementHelper}.
*
*
*/
public interface ElementHelperInterface {
/**
* Parses an element from the textual description, and sets or adds it to
* the contact entry.
*
* @param contact the contact the parsed element should be added or set.
* @param parser the parser used for the parsing of the description.
*
* @see ElementParser
*/
public void parse(ContactEntry contact, ElementParser parser);
/**
* Parses an element from the textual description, and sets or adds it to
* the group entry.
*
* @param group the group the parsed element should be added or set.
* @param parser the parser used for the parsing of the description.
*
* @throws UnsupportedOperationException in case the specific element
* can not be set on a ContactGroupEntry.
*
* @see ElementParser
*/
public void parseGroup(ContactGroupEntry group, ElementParser parser);
/**
* Prints the content of the element to a stream.
*
* @param out output stream.
* @param contact the contact containing the element to print.
*/
public void print(PrintStream out, ContactEntry contact);
/**
* Updates element of destination contact with data from source contact.
* If the source contact entry does not has the specific element, it should
* leave the destination contact entry as is, otherwise is should copy the
* element from the source to the destination contact entry.
*
* @param dest the destination contact entry.
* @param src the source contact entry.
*/
public void update(ContactEntry dest, ContactEntry src);
/**
* Returns the usage help text regarding the formating of an element
* description.
*
* @return the usage help text for the element description.
*/
public String getUsage();
}
@@ -0,0 +1,79 @@
package de.tilman.callerid.example;
import java.util.EnumMap;
import java.util.Map;
/**
* Parser to tokenize element descriptions.
* The general format of an element specification looks like:
* [<value>]|[<name_1>:<value_1>][,<name_2>:<value_2>]...[,<name_n>:<value_n>]
*
* For convenience a single unnamed value can be specified. It is treated as
* "value:<value>", and the parsed value can be accessed with the VALUE key.
*
*
*/
class ElementParser {
// Map of parsed property names and values.
private Map<PropertyName, String> propertyMap;
/**
* Constructor.
* Parses the element description, and fills the propertyMap.
*
* @param elementDesc the element description.
* @throws IllegalArgumentException on badly formated element description.
*/
ElementParser(String elementDesc) throws IllegalArgumentException {
propertyMap = new EnumMap<PropertyName, String>(PropertyName.class);
for (String propertyDesc : elementDesc.split(",")) {
String nameValuePair[] = propertyDesc.split(":", 2);
if (nameValuePair.length == 1) {
propertyMap.put(PropertyName.VALUE, propertyDesc);
} else if (nameValuePair.length == 2){
propertyMap.put(
PropertyName.valueOf(nameValuePair[0].toUpperCase()),
nameValuePair[1]);
} else {
throw new IllegalArgumentException("Badly formated property:"
+ propertyDesc);
}
}
}
/**
* Checks if the given property has a parsed in value.
*
* @param property the property.
* @return {@code true} if the given property has a parsed in value,
* otherwise {@code false}
*/
boolean has(PropertyName property) {
return propertyMap.containsKey(property);
}
/**
* Retrieves the parsed in value for the given property.
*
* @param property the property.
* @return the parsed in value for the given property, or {@code null} if
* the given property was not specified in the element description
* string.
*/
String get(PropertyName property) {
return propertyMap.get(property);
}
/**
* Convenience method to check the value of a boolean property.
*
* @param property the property.
* @return {@code true} if the parsed in value of the given property is "true"
* {@code false} in any other cases.
*/
boolean is(PropertyName property) {
String value = propertyMap.get(property);
return (value != null) && (value.toLowerCase().equals("true"));
}
}
@@ -0,0 +1,41 @@
package de.tilman.callerid.example;
/**
* The property names.
* The parser matches the arguments passed to the actual name of the enums.
*
*
*/
enum PropertyName {
VALUE,
TITLE,
PRIMARY,
PROTOCOL,
LABEL,
REL,
FILE,
TEXT,
HREF,
DELETED,
KEY,
FULL,
GIVEN,
FAMILY,
ADDITIONAL,
PREFIX,
SUFFIX,
URI,
DEPARTMENT,
DESCRIPTION,
SYMBOL,
WHERE,
WHEN,
CITY,
COUNTRY,
FORMATTED,
NEIGHBORHOOD,
POBOX,
POSTCODE,
REGION,
STREET,
}