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
@@ -0,0 +1,40 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.gdata.client.Service;
/**
* Execute batch operations.
* This command is called from {@link sample.gbase.cmdline.CustomerTool}.
*/
class BatchCommand extends Command {
public void execute() throws Exception {
Service service = createService();
Service.GDataRequest request =
service.createBatchRequest(
fixEditUrl(urlFactory.getItemsBatchFeedURL()));
inputRawRequest(request);
// Send the request (HTTP POST)
request.execute();
// Save the response
outputRawResponse(request);
}
}
@@ -0,0 +1,250 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.api.gbase.client.FeedURLFactory;
import com.google.api.gbase.client.GoogleBaseService;
import com.google.gdata.client.Service;
import com.google.gdata.util.AuthenticationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
/**
* One command that is part of CustomerTool.
* This class contains code that is common to all
* commands. It deals, in particular, with the creation
* of the GData service object.
*/
abstract class Command {
/**
* URL of the google authentication server to use for log in.
*/
private static final String DEFAULT_AUTH_HOSTNAME = "www.google.com";
/**
* Username for google base (e-mail address).
*/
protected String username;
/**
* The user's password.
*/
protected String password;
/**
* Base url of the google base server.
*/
protected FeedURLFactory urlFactory = FeedURLFactory.getDefault();
/**
* Base url of the google authentication server.
*/
private String authenticationServer = DEFAULT_AUTH_HOSTNAME;
/**
* Protocol (http or https) to use to connect to the authentication server.
*/
private String authenticationProtocol = "https";
/**
* Developer key used for identification against the Google Base data API
* servers.
*/
private String key;
/**
* Enables dry-run mode for edit operations.
*/
private boolean dryRun;
/**
* Executes the command.
*
* Call this method only after setting the username and password.
*/
public abstract void execute() throws Exception;
/**
* Sets the username, which is required for {@link #execute()} to work.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Sets the password, which is required for {@link #execute()} to work.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Sets the Url of the google base server to connect to.
*/
public void setGoogleBaseServerUrl(String url) throws MalformedURLException {
this.urlFactory = new FeedURLFactory(url);
}
/**
* Sets the name of the google authentication server to connect to.
*/
public void setAuthenticationServerUrl(String urlString)
throws MalformedURLException {
URL url = new URL(urlString);
this.authenticationProtocol = url.getProtocol();
this.authenticationServer = url.getHost();
if (url.getPort() != -1) {
this.authenticationServer += ":" + url.getPort();
}
}
public void setKey(String key) {
this.key = key;
}
/**
* Makes sure username and password have been set.
*/
public boolean hasAllIdentificationInformation() {
return username != null && password != null;
}
/**
* Creates the service and sets the username and password for
* authentication.
*
* @return the GData service object to use
* @throws com.google.gdata.util.AuthenticationException
* if authentication failed
*/
protected GoogleBaseService createService()
throws AuthenticationException {
GoogleBaseService service =
new GoogleBaseService("Google.-CustomerTool-1.0",
key,
authenticationProtocol,
authenticationServer);
service.setUserCredentials(username, password);
return service;
}
/**
* Gets the URL of the customer feed.
*
* The feed contains only the items uploaded by this
* specific customer. This is also the feed that is
* used to upload customer data.
*
* @return the url to the customer feed
*/
protected URL getCustomerFeedURL() throws MalformedURLException {
return urlFactory.getItemsFeedURL();
}
/**
* Writes the response (XML feed) to standard output.
*/
protected void outputRawResponse(Service.GDataRequest request)
throws IOException {
InputStream responseStream = request.getResponseStream();
try {
copyStreamContent(responseStream, System.out);
} finally {
responseStream.close();
}
System.out.println();
}
/**
* Reads data from in input stream and write it into an
* output stream.
*/
protected void copyStreamContent(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
int l;
while ( (l=in.read(buffer)) > 0 ) {
out.write(buffer, 0, l);
}
}
/**
* Reads data from standard input and use it in the request.
*
* The data must be the XML feed appropriate for the command.
* For update, get or insert it should be one Atom XML entry.
*/
protected void inputRawRequest(Service.GDataRequest request)
throws IOException {
OutputStream outputStream = request.getRequestStream();
try {
copyStreamContent(System.in, outputStream);
} finally {
outputStream.close();
}
}
/**
* Puts the command in dry-run mode, in which nothing will
* really happen on the server.
*
* @param dryRun
*/
public void setDryRun(boolean dryRun) {
this.dryRun = dryRun;
}
/**
* Builds an edit URL from a string, adding the dry-run parameter
* if necessary.
*
* This method is not applicable to query URLs, for which the dry-run
* parameter is not supported.
*
* @param url the original url
* @return the same URL with maybe some parameters
* @throws MalformedURLException
*/
protected URL fixEditUrl(URL url) throws MalformedURLException {
return fixEditUrl(url.toExternalForm());
}
/**
* Builds an edit URL from a string, adding the dry-run parameter
* if necessary.
*
* This method is not applicable to query URLs, for which the dry-run
* parameter is not supported.
*
* @param url the original url, as a string
* @return the same URL with maybe some parameters
* @throws MalformedURLException
*/
protected URL fixEditUrl(String url) throws MalformedURLException {
if (dryRun) {
char separator = url.contains("?") ? '&' : '?';
url = url + separator + "dry-run=true";
}
return new URL(url);
}
}
@@ -0,0 +1,316 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import java.net.MalformedURLException;
import java.util.Arrays;
/**
* Creates and initializes commands given command-line
* arguments.
*
* This class is totally useless if you want to understand
* how the API works. All it does is parse command-line
* arguments and call some setters on the different <code>*Command</code>
* objects. Have a look at the <code>*Command</code> classes instead.
*/
class CommandFactory {
/**
* All commands available in this system, for producing error messages.
*/
private static final String ALL_COMMANDS =
"query, get, update, insert, delete, batch";
/**
* Creates a {@link Command} object and initializes it using
* command-line arguments.
*
* @param args command-line arguments
* @return a new Command object, properly initialized and ready to use
*/
public static Command createCommand(String[] args) {
if (args.length == 0) {
throw error("Please give first the command you want to run (" +
ALL_COMMANDS + ") then the parameters for that " +
"command.");
}
String commandName = args[0];
if ("query".equals(commandName)) {
return createQueryCommand(args);
} else if("insert".equals(commandName)) {
return createInsertCommand(args);
} else if("update".equals(commandName)) {
return createUpdateCommand(args);
} else if("delete".equals(commandName)) {
return createDeleteCommand(args);
} else if("get".equals(commandName)) {
return createGetCommand(args);
} else if("batch".equals(commandName)) {
return createBatchCommand(args);
} else if("query-media".equals(commandName)) {
return createQueryMediaCommand(args);
} else if("insert-media".equals(commandName)) {
return createInsertMediaCommand(args);
} else if("update-media".equals(commandName)) {
return createUpdateMediaCommand(args);
} else if("delete-media".equals(commandName)) {
return createDeleteMediaCommand(args);
} else if("get-media".equals(commandName)) {
return createGetMediaCommand(args);
} else {
throw error("Unknown command: " + commandName +
". Available commands: " + ALL_COMMANDS);
}
}
/**
* Creates and initializes a {@link QueryCommand}.
*/
private static Command createQueryCommand(String[] args) {
QueryCommand command = new QueryCommand();
args = parseAndSetCommonArguments(command, args);
if (args.length == 1) {
command.setQuery(args[0]);
} else if (args.length > 1) {
throw error("Expected at most one query argument, got " + args.length);
}
return command;
}
/**
* Creates and initializes a {@link InsertCommand}.
*/
private static Command createInsertCommand(String[] args) {
InsertCommand command = new InsertCommand();
args = parseAndSetCommonArguments(command, args);
expectNoMoreArguments(args);
return command;
}
/**
* Creates and initializes a {@link BatchCommand}.
*/
private static Command createBatchCommand(String[] args) {
BatchCommand command = new BatchCommand();
args = parseAndSetCommonArguments(command, args);
expectNoMoreArguments(args);
return command;
}
/**
* Creates and initializes a {@link UpdateCommand}.
*/
private static Command createUpdateCommand(String[] args) {
UpdateCommand command = new UpdateCommand();
args = parseAndSetCommonArguments(command, args);
command.setItemId(getItemId(args));
return command;
}
/**
* Creates and initializes a {@link DeleteCommand}.
*/
private static Command createDeleteCommand(String[] args) {
DeleteCommand command = new DeleteCommand();
args = parseAndSetCommonArguments(command, args);
command.setItemId(getItemId(args));
return command;
}
/**
* Creates and initializes a {@link GetCommand).
*/
private static Command createGetCommand(String[] args) {
GetCommand command = new GetCommand();
args = parseAndSetCommonArguments(command, args);
command.setItemId(getItemId(args));
return command;
}
/**
* Creates and initializes a {@link QueryMediaCommand}.
*/
private static Command createQueryMediaCommand(String[] args) {
QueryMediaCommand command = new QueryMediaCommand();
args = parseAndSetCommonArguments(command, args);
if (args.length == 1) {
command.setItemMediaUrl(args[0]);
} else {
throw error("Expected [item_media_feed_url], got " + Arrays.toString(args));
}
return command;
}
/**
* Creates and initializes a {@link InsertMediaCommand}.
*/
private static Command createInsertMediaCommand(String[] args) {
InsertMediaCommand command = new InsertMediaCommand();
args = parseAndSetCommonArguments(command, args);
if (args.length < 3 || args.length > 4) {
throw error("Expected four arguments: [item_media_feed_url attachment_path_to_file " +
"attachment_mime_type caption?], got " + Arrays.toString(args));
}
command.setItemMediaUrl(args[0]);
command.setAttachmentFile(args[1]);
command.setAttachmentMimeType(args[2]);
if (args.length == 4) {
command.setCaption(args[3]);
}
return command;
}
/**
* Creates and initializes a {@link UpdateMediaCommand}.
*/
private static Command createUpdateMediaCommand(String[] args) {
UpdateMediaCommand command = new UpdateMediaCommand();
args = parseAndSetCommonArguments(command, args);
command.setAttachmentId(getItemId(args));
return command;
}
/**
* Creates and initializes a {@link DeleteMediaCommand}.
*/
private static Command createDeleteMediaCommand(String[] args) {
DeleteMediaCommand command = new DeleteMediaCommand();
args = parseAndSetCommonArguments(command, args);
command.setAttachmentId(getItemId(args));
return command;
}
/**
* Creates and initializes a {@link GetMediaCommand).
*/
private static Command createGetMediaCommand(String[] args) {
GetMediaCommand command = new GetMediaCommand();
args = parseAndSetCommonArguments(command, args);
command.setAttachmentId(getItemId(args));
return command;
}
/**
* Get the item id from the command line and make sure it's the
* only argument left.
*
* @param args command line arguments left over from
* {@link #parseAndSetCommonArguments(Command, String[])}
* @return the item ID (an url)
*/
private static String getItemId(String[] args) {
if (args.length != 1) {
throw error("Expected one argument after the command name: " +
"the ID (url) of the item to delete.");
}
return args[0];
}
/**
* Parse the command line and initialize things that are common
* to all {@link Command}s.
*
* @param command the command object
* @param args command-line arguments (0 is the command name)
* @return the arguments that are left that haven't been parsed
* by this method, or an empty array if there's nothing left
*/
private static String[] parseAndSetCommonArguments(Command command,
String[] args) {
// Start at the first argument after the command name
int current = 1;
while (current < args.length && args[current].startsWith("-")) {
String option = args[current];
current++;
if ( current >= args.length) {
throw error("expected an argument after option " + option);
}
if ("--dry_run".equals(option)) {
command.setDryRun(true);
continue;
}
String value = args[current];
current++;
if ("--user".equals(option)) {
command.setUsername(value);
} else if("--password".equals(option)) {
command.setPassword(value);
} else if("--url".equals(option)) {
try {
command.setGoogleBaseServerUrl(value);
} catch(MalformedURLException e) {
throw error("Value for --url should be a valid URL: " +
e.getMessage());
}
} else if("--auth".equals(option)) {
try {
command.setAuthenticationServerUrl(value);
} catch(MalformedURLException e) {
throw error("Value for --auth should be a valid http or https " +
"URL: " + e.getMessage());
}
} else if("--key".equals(option)) {
command.setKey(value);
} else {
throw error("unexpected option: " + option);
}
}
if (!command.hasAllIdentificationInformation()) {
throw error("You must input all two required parameters: " +
"--user email --password password ");
}
// leave the rest for the command
String[] retval = new String[args.length-current];
System.arraycopy(args, current, retval, 0, retval.length);
return retval;
}
private static void expectNoMoreArguments(String[] args) {
if (args.length > 0) {
throw error("Expected no more arguments, got instead " + args[0]);
}
}
private static IllegalArgumentException error(String message) {
return new IllegalArgumentException("Error: wrong arguments. " + message);
}
}
@@ -0,0 +1,74 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.gdata.util.ServiceException;
import com.google.api.gbase.client.ServiceErrors;
import com.google.api.gbase.client.ServiceError;
import java.util.List;
/**
* An example tool that helps manage customer items on
* Google Base using Google data API.
*
* This tool deals directly with XML feeds. If you would
* like to use a higher-level API, have a look at QueryExample.
*
* Have a look at the different <code>*Command</code> classes for some more
* interesting code.
*/
public class CustomerTool {
public static void main(String[] args) throws Exception {
Command command = CommandFactory.createCommand(args);
try {
command.execute();
} catch (ServiceException e) {
/* Display the error message sent by the server, if it
* is available. A real application would need to parse
* the body (as HTML or XML, depending on e.getContentType())
* and display it nicely.
*/
StringBuffer message = new StringBuffer("Response code:");
ServiceErrors errors = new ServiceErrors(e);
if (e.getHttpErrorCodeOverride() > 0) {
message.append(" ");
message.append(e.getHttpErrorCodeOverride());
}
message.append(" ");
message.append(e.getMessage());
System.err.println(message);
List<? extends ServiceError> allErrors = errors.getAllErrors();
for (ServiceError error: allErrors) {
String field = error.getField();
StringBuffer buffer = new StringBuffer();
buffer.append(" ");
if (field != null) {
buffer.append("in field '");
buffer.append(field);
buffer.append("'");
buffer.append(": ");
}
buffer.append(error.getReason());
System.err.println(buffer);
}
System.exit(10);
}
}
}
@@ -0,0 +1,43 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.gdata.client.Service;
/**
* Deletes an item.
*/
public class DeleteCommand extends Command {
private String itemId;
public void execute() throws Exception {
Service service = createService();
Service.GDataRequest request =
service.createDeleteRequest(fixEditUrl(itemId));
// Send the request (HTTP DELETE)
request.execute();
System.out.println("Item deleted successfully.");
}
/** Sets the Id of the item, which is also its URL. */
public void setItemId(String itemId) {
this.itemId = itemId;
}
}
@@ -0,0 +1,44 @@
/* Copyright (c) 2007 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.gbase.cmdline;
import com.google.gdata.client.Service;
/**
* Deletes a media attachment from an item.
* This command is called from {@link CustomerTool}.
*/
public class DeleteMediaCommand extends Command {
private String attachmentId;
@Override
public void execute() throws Exception {
Service service = createService();
Service.GDataRequest request =
service.createDeleteRequest(fixEditUrl(attachmentId));
// Send the request (HTTP DELETE)
request.execute();
System.out.println("Item deleted successfully.");
}
/** Sets the Id of the media attachment, which is also its URL. */
public void setAttachmentId(String attachmentId) {
this.attachmentId = attachmentId;
}
}
@@ -0,0 +1,111 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.api.gbase.client.FeedURLFactory;
import com.google.api.gbase.client.GoogleBaseService;
import com.google.api.gbase.client.ServiceError;
import com.google.api.gbase.client.ServiceErrors;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
/**
* Utility class that allows creating simple Example Tools.
*
* Contains methods for parsing the arguments and for printing errors.
*/
public abstract class Example {
protected static FeedURLFactory urlFactory = FeedURLFactory.getDefault();
protected static GoogleBaseService service;
/**
* Parses the arguments, creates a FeedURLFactory and a GoogleBaseService.
* @return the remaining arguments
*/
public static String[] init(String[] args, String applicationName)
throws IOException {
String baseUrl = null;
int argsIndex = 0;
while (argsIndex < args.length && args[argsIndex].startsWith("-")) {
String arg = args[argsIndex];
argsIndex++;
if ( argsIndex >= args.length) {
throw new IllegalArgumentException("Expected a parameter value " +
"after " + arg);
}
String value = args[argsIndex];
argsIndex++;
if ("--url".equals(arg)) {
baseUrl = value;
} else if("--key".equals(arg)) {
// This parameter used to contain the developer key.
// It is still accepted so as not to break scripts that used it, but
// it is now ignored.
} else {
throw new IllegalArgumentException("unknown parameter: " + arg);
}
}
if(baseUrl != null) {
urlFactory = new FeedURLFactory(baseUrl);
}
// service.query does a GET on the url above and parses the result,
// which is an ATOM feed with some extensions (called the Google Base
// data API items feed).
service = new GoogleBaseService(applicationName);
if (argsIndex > 0) {
String[] newargs = new String[args.length - argsIndex];
System.arraycopy(args, argsIndex, newargs, 0, newargs.length);
args = newargs;
}
return args;
}
/**
* Prints an error message returned by the server, if any.
*
* @param e an exception that may contain an error message from the server
*/
protected static void printServiceException(ServiceException e) {
System.err.print("Error");
if (e.getHttpErrorCodeOverride() > 0) {
System.err.print(e.getHttpErrorCodeOverride());
}
System.err.print(": ");
System.err.println(e.getMessage());
ServiceErrors errors = new ServiceErrors(e);
for (ServiceError error: errors.getAllErrors()) {
String field = error.getField();
System.err.print(" ");
if (field != null) {
System.err.print("in field '");
System.err.print(field);
System.err.print("' ");
}
System.err.println(error.getReason());
}
}
}
@@ -0,0 +1,45 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.gdata.client.Service;
import java.net.URL;
/**
* Displays one item.
*/
public class GetCommand extends Command {
private String itemId;
public void execute() throws Exception {
Service service = createService();
Service.GDataRequest request =
service.createEntryRequest(new URL(itemId));
// Send the request (HTTP GET)
request.execute();
// Save the response
outputRawResponse(request);
}
/** Sets the id/URL of the item to display. */
public void setItemId(String itemId) {
this.itemId = itemId;
}
}
@@ -0,0 +1,47 @@
/* Copyright (c) 2007 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.gbase.cmdline;
import com.google.gdata.client.Service;
import java.net.URL;
/**
* Displays the media entry (meta-data) of one attachment.
* This command is called from {@link CustomerTool}.
*/
public class GetMediaCommand extends Command {
private String attachmentId;
@Override
public void execute() throws Exception {
Service service = createService();
Service.GDataRequest request =
service.createEntryRequest(new URL(attachmentId));
// Send the request (HTTP GET)
request.execute();
// Save the response
outputRawResponse(request);
}
/** Sets the id/URL of the media attachment to display. */
public void setAttachmentId(String attachmentId) {
this.attachmentId = attachmentId;
}
}
@@ -0,0 +1,40 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.gdata.client.Service;
/**
* Inserts a new Item into Google Base items.
* This command is called from {@link CustomerTool}.
*/
class InsertCommand extends Command {
public void execute() throws Exception {
Service service = createService();
Service.GDataRequest request =
service.createInsertRequest(fixEditUrl(getCustomerFeedURL()));
inputRawRequest(request);
// Send the request (HTTP POST)
request.execute();
// Save the response
outputRawResponse(request);
}
}
@@ -0,0 +1,83 @@
/* Copyright (c) 2007 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.gbase.cmdline;
import com.google.gdata.client.Service;
import com.google.gdata.client.Service.GDataRequest;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.ContentType;
import java.io.File;
import java.net.URL;
/**
* Inserts a new media attachment to a Google Base item, by using
* a media binary POST. See
* {@link com.google.api.gbase.client.GoogleBaseService#insert(URL, Class, MediaSource)}
* for an easier way to do a media binary POST, or look at
* {@link com.google.api.gbase.client.GoogleBaseService#insert(URL, com.google.gdata.data.BaseEntry)}
* for an easier way to insert an attachment together with the media entry (meta-data) describing it.
* This command is called from {@link CustomerTool}.
*/
class InsertMediaCommand extends Command {
private String itemMediaUrl;
private String attachmentFile;
private String attachmentMimeType;
private String caption;
@Override
public void execute() throws Exception {
MediaFileSource media = new MediaFileSource(new File(attachmentFile), attachmentMimeType);
Service service = createService();
Service.GDataRequest request = service.createRequest(GDataRequest.RequestType.INSERT,
new URL(itemMediaUrl), new ContentType(attachmentMimeType));
if (caption != null) {
request.setHeader("Slug", caption);
}
MediaSource.Output.writeTo(media, request.getRequestStream());
// Send the request (HTTP POST)
request.execute();
// Save the response
outputRawResponse(request);
}
/** Set the url of the media feed for the item to insert the attachment into. */
public void setItemMediaUrl(String itemMediaUrl) {
this.itemMediaUrl = itemMediaUrl;
}
/** Sets the path to the file on the disk containing the attachment to upload. */
public void setAttachmentFile(String attachmentFile) {
this.attachmentFile = attachmentFile;
}
/** Sets the mime-type of the attachment. */
public void setAttachmentMimeType(String attachmentMimeType) {
this.attachmentMimeType = attachmentMimeType;
}
/** Sets the caption (title) of the attachment. */
public void setCaption(String caption) {
this.caption = caption;
}
}
@@ -0,0 +1,178 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.api.gbase.client.GoogleBaseAttributeId;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.GoogleBaseFeed;
import com.google.api.gbase.client.GoogleBaseQuery;
import com.google.api.gbase.client.ItemTypeDescription;
import com.google.api.gbase.client.MetadataEntryExtension;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.URL;
/**
* This class demonstrates how to retrieve Google Base item types
* using the client library of the Google Base data API.
*
* The tool implemented by this class will connect to Google Base,
* run the request and display some results.
*/
public class ItemTypesExample extends Example {
/**
* Runs the example.
*/
public static void main(String[] args) throws IOException, ServiceException {
String locale = null;
String itemType = null;
args = init(args, "Google-ItemTypesExample-1.0");
if (args.length == 0) {
// nothing to do
} else if (args.length == 1) {
locale = args[0];
} else if (args.length == 2) {
locale = args[0];
itemType = args[1];
} else {
System.err.println("Invalid argument count.");
System.err.println("Expected either two arguments, to get an itemtype:");
System.err.println(" locale itemtype");
System.err.println("or one argument, to get the itemtypes of a locale:");
System.err.println(" locale");
System.err.println("or no argument, to get the locales.");
System.exit(1);
}
if (locale == null) {
queryLocales();
} else {
if (itemType == null) {
queryItemTypes(locale);
} else {
queryItemType(locale, itemType);
}
}
}
/**
* Retrieves and prints the locales.
*
*/
private static void queryLocales()
throws IOException, ServiceException {
// Create a query URL
URL url = urlFactory.getLocalesFeedURL();
GoogleBaseQuery query = new GoogleBaseQuery(url);
// Display the URL generated by the API
System.out.println("Sending request to: " + query.getUrl());
try {
GoogleBaseFeed feed = service.query(query);
// Print the locales
for (GoogleBaseEntry entry : feed.getEntries()) {
System.out.println(entry.getTitle().getPlainText());
}
} catch (ServiceException e) {
printServiceException(e);
}
}
/**
* Retrieves and prints the item types Google suggests for a locale.
*
* @param locale the locale to be analysed
*/
private static void queryItemTypes(String locale)
throws IOException, ServiceException {
// Create a query URL from the given arguments
URL url = urlFactory.getItemTypesFeedURL(locale);
GoogleBaseQuery query = new GoogleBaseQuery(url);
// Display the URL generated by the API
System.out.println("Sending request to: " + query.getUrl());
try {
GoogleBaseFeed feed = service.query(query);
// Print the item types
printItemTypeFeed(feed);
} catch (ServiceException e) {
printServiceException(e);
}
}
/**
* Retrieves and prints the attribute ids Google suggests for an item type of
* a locale.
*
* @param locale the locale of the item type
* @param itemType the item type to be analysed
*/
private static void queryItemType(String locale, String itemType)
throws IOException, ServiceException {
// Create a query URL from the given arguments
URL url = urlFactory.getItemTypesEntryURL(locale, itemType);
// Display the URL generated by the API
System.out.println("Sending request to: " + url);
try {
GoogleBaseEntry entry = service.getEntry(url);
// Print the item type
printItemTypeEntry(entry);
} catch (ServiceException e) {
printServiceException(e);
}
}
/**
* Prints each itemtype item in the feed to the output.
* Uses {@link #printItemTypeEntry(GoogleBaseEntry)}.
*
* @param feed a Google Base data API itemtypes feed
*/
private static void printItemTypeFeed(GoogleBaseFeed feed) {
if (feed.getTotalResults() == 0) {
System.out.println("No matches.");
return;
}
for (GoogleBaseEntry entry : feed.getEntries()) {
printItemTypeEntry(entry);
}
}
/**
* Prints the name and the recommended attribute names of
* an itemtype GoogleBaseEntry item.
*
* @param entry a Google Base data API itemtype entry
*/
private static void printItemTypeEntry(GoogleBaseEntry entry) {
MetadataEntryExtension metadata = entry.getGoogleBaseMetadata();
ItemTypeDescription itemTypeDescription = metadata.getItemTypeDescription();
System.out.println(itemTypeDescription.getName() + " - " + entry.getId());
for (GoogleBaseAttributeId attrId : itemTypeDescription.getAttributeIds()) {
System.out.println(attrId.getName() +
" (" + attrId.getType().getName() + ")");
}
}
}
@@ -0,0 +1,118 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.api.gbase.client.AttributeHistogram;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.GoogleBaseFeed;
import com.google.api.gbase.client.GoogleBaseQuery;
import com.google.api.gbase.client.MetadataEntryExtension;
import com.google.api.gbase.client.AttributeHistogram.UniqueValue;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.URL;
/**
* This class demonstrates how to retrieve Google Base metadata
* using the client library of the Google Base data API.
*
* The tool implemented by this class will connect to Google Base,
* run the request and display some results.
*/
public class MetadataExample extends Example {
/**
* Runs the example.
*/
public static void main(String[] args) throws IOException, ServiceException {
String queryString = null;
args = init(args, "Google-MetadataExample-1.0");
// Process command-line arguments
if (args.length == 1) {
queryString = args[0];
} else {
System.err.println("Invalid argument count.");
System.err.println("Expected one argument:");
System.err.println(" query");
System.exit(1);
}
queryMetadata(queryString);
}
/**
* Retrieves and prints the list of the most used attributes used by
* the items that match a query.
*
* @param queryString a Google Base Query Language query
*/
private static void queryMetadata(String queryString)
throws IOException, ServiceException {
// Create a query URL from the given arguments
URL url = urlFactory.getAttributesFeedURL();
GoogleBaseQuery query = new GoogleBaseQuery(url);
query.setGoogleBaseQuery(queryString);
// Display the URL generated by the API
System.out.println("Sending request to: " + query.getUrl());
try {
GoogleBaseFeed feed = service.query(query);
// Print the items
printMetadataFeed(feed);
} catch (ServiceException e) {
printServiceException(e);
}
}
/**
* Prints each metadata item in the feed to the output.
* Uses {@link #printMetadataEntry(GoogleBaseEntry)}.
*
* @param feed a Google Base data API metadata feed
*/
private static void printMetadataFeed(GoogleBaseFeed feed) {
if (feed.getTotalResults() == 0) {
System.out.println("No matches.");
return;
}
for (GoogleBaseEntry entry : feed.getEntries()) {
printMetadataEntry(entry);
}
}
/**
* Prints a few relevant attributes and the values of the attribute histogram
* of a metadata GoogleBaseEntry item.
*
* @param entry a Google Base data API metadata entry
*/
private static void printMetadataEntry(GoogleBaseEntry entry) {
MetadataEntryExtension metadata = entry.getGoogleBaseMetadata();
AttributeHistogram attributeHistogram = metadata.getAttributeHistogram();
System.out.println(attributeHistogram.getAttributeName() +
" (" + attributeHistogram.getAttributeType().getName() + "): " +
"valueCount=" + attributeHistogram.getTotalValueCount() + " - " +
entry.getId());
for (UniqueValue value : attributeHistogram.getValues()) {
System.out.println(value.getValueAsString() +
" count=" + value.getCount());
}
}
}
@@ -0,0 +1,49 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.api.gbase.client.GoogleBaseQuery;
import com.google.gdata.client.Service;
/**
* Runs a query on Google Base items.
* This command is called from {@link CustomerTool}.
*/
class QueryCommand extends Command {
private String query;
public void execute() throws Exception {
// Build the query URL
GoogleBaseQuery queryObject = new GoogleBaseQuery(getCustomerFeedURL());
queryObject.setGoogleBaseQuery(query);
Service service = createService();
Service.GDataRequest request =
service.createFeedRequest(queryObject.getUrl());
// Send the request (HTTP GET)
request.execute();
outputRawResponse(request);
}
/** Sets the Google Base query to run. */
public void setQuery(String query) {
this.query = query;
}
}
@@ -0,0 +1,93 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.GoogleBaseFeed;
import com.google.api.gbase.client.GoogleBaseQuery;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
/**
* This class demonstrates how to send simple Google Base search queries
* using the client library of the Google Base data API.
*
* The tool implemented by this class will connect to Google Base, run the
* query and display some results.
*/
public class QueryExample extends Example {
/**
* Maximum number of results to return.
*/
private static final int MAX_RESULTS = 10;
/**
* Runs the example.
*/
public static void main(String[] args) throws IOException, ServiceException {
String queryString = null;
args = init(args, "Google-QueryExample-1.0");
// Process command-line arguments
if (args.length == 1) {
queryString = args[0];
} else {
System.err.println("Invalid argument count.");
System.err.println("Expected one argument:");
System.err.println(" query");
System.exit(1);
}
// Create a query URL from the given arguments
GoogleBaseQuery query =
new GoogleBaseQuery(urlFactory.getSnippetsFeedURL());
query.setGoogleBaseQuery(queryString);
query.setResultFormat(GoogleBaseQuery.ResultFormat.ATOM);
query.setMaxResults(MAX_RESULTS);
// Display the URL generated by the API
System.out.println("Sending request to: " + query.getUrl());
try {
GoogleBaseFeed feed = service.query(query, GoogleBaseFeed.class);
// Print the items
printResult(feed);
} catch (ServiceException e) {
printServiceException(e);
}
}
/**
* Prints a few relevant attributes from each item in the feed to the output.
*
* @param feed a Google Base data API items feed
*/
private static void printResult(GoogleBaseFeed feed) {
if (feed.getTotalResults() == 0) {
System.out.println("No matches.");
} else {
for (GoogleBaseEntry entry : feed.getEntries()) {
System.out.println(entry.getGoogleBaseAttributes().getItemType() +
": " + entry.getTitle().getPlainText() +
" - " +entry.getId());
}
}
}
}
@@ -0,0 +1,46 @@
/* Copyright (c) 2007 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.gbase.cmdline;
import com.google.gdata.client.Service;
import java.net.URL;
/**
* Queries the specified media feed for all the media attachments
* of one item.
* This command is called from {@link CustomerTool}.
*/
class QueryMediaCommand extends Command {
private String itemMediaUrl;
@Override
public void execute() throws Exception {
Service service = createService();
Service.GDataRequest request = service.createFeedRequest(new URL(itemMediaUrl));
// Send the request (HTTP GET)
request.execute();
outputRawResponse(request);
}
/** Set the url of the media feed. */
public void setItemMediaUrl(String itemMediaUrl) {
this.itemMediaUrl = itemMediaUrl;
}
}
@@ -0,0 +1,44 @@
/* Copyright (c) 2006 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.gbase.cmdline;
import com.google.gdata.client.Service;
/**
* Modifies an existing item in Google Base.
*
* This command is called from
* {@link com.google.commerce.api.client.cmdline.CustomerTool}.
*/
class UpdateCommand extends Command {
private String itemId;
public void execute() throws Exception {
Service service = createService();
Service.GDataRequest request =
service.createUpdateRequest(fixEditUrl(itemId));
inputRawRequest(request);
// Send the request (HTTP POST)
request.execute();
System.out.println("Item updated successfully.");
}
/** Sets the Id of the item, which is also its URL. */
public void setItemId(String itemId) {
this.itemId = itemId;
}
}
@@ -0,0 +1,45 @@
/* Copyright (c) 2007 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.gbase.cmdline;
import com.google.gdata.client.Service;
/**
* Modifies the media entry (meta-data) describing a media attachment
* of a Google Base item.
* This command is called from {@link CustomerTool}.
*/
class UpdateMediaCommand extends Command {
private String attachmentId;
@Override
public void execute() throws Exception {
Service service = createService();
Service.GDataRequest request = service.createUpdateRequest(fixEditUrl(attachmentId));
inputRawRequest(request);
// Send the request (HTTP POST)
request.execute();
System.out.println("Item attachment updated successfully.");
}
/** Sets the Id of the media attachment to be updated. */
public void setAttachmentId(String attachmentId) {
this.attachmentId = attachmentId;
}
}