diff --git a/WebCallerID/Scrapbook.jpage b/WebCallerID/Scrapbook.jpage new file mode 100644 index 0000000..0529800 --- /dev/null +++ b/WebCallerID/Scrapbook.jpage @@ -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; xWebCallerID WebCallerID 1.0.2 + + + mandubian-mvn + http://mandubian-mvn.googlecode.com/svn/trunk/mandubian-mvn/repository + + log4j @@ -25,5 +31,15 @@ jsap 2.1 + + com.google.gdata + gdata-core-1.0 + 1.36.0 + + + com.google.gdata + gdata-contacts-3.0 + 1.36.0 + \ No newline at end of file diff --git a/WebCallerID/src/main/java/de/tilman/callerId/CallerIdClient.java b/WebCallerID/src/main/java/de/tilman/callerId/CallerIdClient.java index 8a0c7ba..dc66529 100755 --- a/WebCallerID/src/main/java/de/tilman/callerId/CallerIdClient.java +++ b/WebCallerID/src/main/java/de/tilman/callerId/CallerIdClient.java @@ -23,6 +23,7 @@ import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; +import com.martiansoftware.jsap.FlaggedOption; import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.JSAPException; import com.martiansoftware.jsap.JSAPResult; @@ -56,10 +57,10 @@ public class CallerIdClient { log.info("logging in to Speedport router"); postUrl("https://speedport.ip/index/login.cgi", "Username=" + URLEncoder.encode("admin", "UTF-8") + "&" + "Password=" + password); - + log.info("retrieving call list"); getUrl("https://speedport.ip/auth/hcti_status_telanrl.php?cookie=SessionID_R3," + cookie); - + log.info("logging out"); postUrl("https://speedport.ip/auth/logout.cgi?RequestFile=/pub/top_beenden.php&cookie=SessionID_R3," + cookie, ""); } catch (Exception e) { @@ -135,7 +136,9 @@ public class CallerIdClient { if (cookie != null) { 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()); if (payload.length() > 0) { @@ -151,7 +154,7 @@ public class CallerIdClient { } else { if (line.equals("4")) log.error(" could not log in, Speedport adminstration account is currently in use"); - else + else log.error(" received unexpected response: " + line); } } @@ -190,12 +193,12 @@ public class CallerIdClient { String pass = config.getString("e-mail password"); Properties props = System.getProperties(); 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.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "465"); - //props.put("mail.smtp.port", "587"); + // props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); String[] to = config.getStringArray("recipient"); @@ -216,9 +219,9 @@ public class CallerIdClient { message.setSubject(TEXT_MAILPREFIX + number); message.setText(TEXT_MAILPREFIX + number + "\n" + time); - + log.info("sending message for call from " + number + " at " + time); - + Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); @@ -261,11 +264,19 @@ public class CallerIdClient { .setGreedy(true); recipients.setHelp("e-mail addresses to send notifications to"); 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"); debugSwitch.setHelp("print debug messages"); jsap.registerParameter(debugSwitch); - + Switch helpSwitch = new Switch("help").setLongFlag("help").setShortFlag('?'); helpSwitch.setHelp("print help and exit"); jsap.registerParameter(helpSwitch); @@ -285,11 +296,10 @@ public class CallerIdClient { log.error("Usage: java -jar speedportcallerid.jar " + jsap.getUsage() + "\n\n" + jsap.getHelp()); System.exit(-1002); } - + if (config.getBoolean("debug")) { log.setLevel(Level.DEBUG); - } - else { + } else { log.setLevel(Level.INFO); } log.info("Log level set to " + log.getLevel()); diff --git a/WebCallerID/src/main/java/de/tilman/callerId/GoogleTest.java b/WebCallerID/src/main/java/de/tilman/callerId/GoogleTest.java new file mode 100644 index 0000000..26fe8e0 --- /dev/null +++ b/WebCallerID/src/main/java/de/tilman/callerId/GoogleTest.java @@ -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("SpeedportCallerIdClient"); + 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(); + } + +} diff --git a/WebCallerID/src/main/java/de/tilman/callerid/example/ContactsExample.java b/WebCallerID/src/main/java/de/tilman/callerid/example/ContactsExample.java new file mode 100644 index 0000000..b9fe05a --- /dev/null +++ b/WebCallerID/src/main/java/de/tilman/callerid/example/ContactsExample.java @@ -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. +*

+* 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 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 [] " + + "<--contactfeed|--groupfeed> " + + "--action= [] " + + "(default contactfeed)\n" + + " Scripting commands usage:\n" + + " contactsExample [] " + + "<--contactfeed|--groupfeed> --script=