code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2010 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 com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.StringUtils; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Imports GPX XML files to the my tracks provider. * * TODO: Show progress indication to the user. * * @author Leif Hendrik Wilden * @author Steffen Horlacher * @author Rodrigo Damazio */ public class GpxImporter extends DefaultHandler { /* * GPX-XML tag names and attributes. */ private static final String TAG_TRACK = "trk"; private static final String TAG_TRACK_POINT = "trkpt"; private static final Object TAG_TRACK_SEGMENT = "trkseg"; private static final String TAG_NAME = "name"; private static final String TAG_DESCRIPTION = "desc"; private static final String TAG_ALTITUDE = "ele"; private static final String TAG_TIME = "time"; private static final String ATT_LAT = "lat"; private static final String ATT_LON = "lon"; /** * The maximum number of locations to buffer for bulk-insertion into the database. */ private static final int MAX_BUFFERED_LOCATIONS = 512; /** * Utilities for accessing the contnet provider. */ private final MyTracksProviderUtils providerUtils; /** * List of track ids written in the database. Only contains successfully * written tracks. */ private final List<Long> tracksWritten; /** * Contains the current elements content. */ private String content; /** * Currently reading location. */ private Location location; /** * Previous location, required for calculations. */ private Location lastLocation; /** * Currently reading track. */ private Track track; /** * Statistics builder for the current track. */ private TripStatisticsBuilder statsBuilder; /** * Buffer of locations to be bulk-inserted into the database. */ private Location[] bufferedPointInserts = new Location[MAX_BUFFERED_LOCATIONS]; /** * Number of locations buffered to be inserted into the database. */ private int numBufferedPointInserts = 0; /** * Number of locations already processed. */ private int numberOfLocations; /** * Number of segments already processed. */ private int numberOfSegments; /** * Used to identify if a track was written to the database but not yet * finished successfully. */ private boolean isCurrentTrackRollbackable; /** * Flag to indicate if we're inside a track's xml element. * Some sub elements like name may be used in other parts of the gpx file, * and we use this to ignore them. */ private boolean isInTrackElement; /** * Counter to find out which child level of track we are processing. */ private int trackChildDepth; /** * SAX-Locator to get current line information. */ private Locator locator; private Location lastSegmentLocation; /** * Reads GPS tracks from a GPX file and writes tracks and their coordinates to * the database. * * @param is a input steam with gpx-xml data * @return long[] array of track ids written in the database * @throws SAXException a parsing error * @throws ParserConfigurationException internal error * @throws IOException a file reading problem */ public static long[] importGPXFile(final InputStream is, final MyTracksProviderUtils providerUtils) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); GpxImporter handler = new GpxImporter(providerUtils); SAXParser parser = factory.newSAXParser(); long[] trackIds = null; try { long start = System.currentTimeMillis(); parser.parse(is, handler); long end = System.currentTimeMillis(); Log.d(Constants.TAG, "Total import time: " + (end - start) + "ms"); trackIds = handler.getImportedTrackIds(); } finally { // delete track if not finished handler.rollbackUnfinishedTracks(); } return trackIds; } /** * Constructor, requires providerUtils for writing tracks the database. */ public GpxImporter(MyTracksProviderUtils providerUtils) { this.providerUtils = providerUtils; tracksWritten = new ArrayList<Long>(); } @Override public void characters(char[] ch, int start, int length) throws SAXException { String newContent = new String(ch, start, length); if (content == null) { content = newContent; } else { // In 99% of the cases, a single call to this method will be made for each // sequence of characters we're interested in, so we'll rarely be // concatenating strings, thus not justifying the use of a StringBuilder. content += newContent; } } @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { if (isInTrackElement) { trackChildDepth++; if (localName.equals(TAG_TRACK_POINT)) { onTrackPointElementStart(attributes); } else if (localName.equals(TAG_TRACK_SEGMENT)) { onTrackSegmentElementStart(); } else if (localName.equals(TAG_TRACK)) { String msg = createErrorMessage("Invalid GPX-XML detected"); throw new SAXException(msg); } } else if (localName.equals(TAG_TRACK)) { isInTrackElement = true; trackChildDepth = 0; onTrackElementStart(); } } @Override public void endElement(String uri, String localName, String name) throws SAXException { if (!isInTrackElement) { content = null; return; } // process these elements only as sub-elements of track if (localName.equals(TAG_TRACK_POINT)) { onTrackPointElementEnd(); } else if (localName.equals(TAG_ALTITUDE)) { onAltitudeElementEnd(); } else if (localName.equals(TAG_TIME)) { onTimeElementEnd(); } else if (localName.equals(TAG_NAME)) { // we are only interested in the first level name element if (trackChildDepth == 1) { onNameElementEnd(); } } else if (localName.equals(TAG_DESCRIPTION)) { // we are only interested in the first level description element if (trackChildDepth == 1) { onDescriptionElementEnd(); } } else if (localName.equals(TAG_TRACK_SEGMENT)) { onTrackSegmentElementEnd(); } else if (localName.equals(TAG_TRACK)) { onTrackElementEnd(); isInTrackElement = false; trackChildDepth = 0; } trackChildDepth--; // reset element content content = null; } @Override public void setDocumentLocator(Locator locator) { this.locator = locator; } /** * Create a new Track object and insert empty track in database. Track will be * updated with missing values later. */ private void onTrackElementStart() { track = new Track(); numberOfLocations = 0; Uri trackUri = providerUtils.insertTrack(track); long trackId = Long.parseLong(trackUri.getLastPathSegment()); track.setId(trackId); isCurrentTrackRollbackable = true; } private void onDescriptionElementEnd() { track.setDescription(content.toString().trim()); } private void onNameElementEnd() { track.setName(content.toString().trim()); } /** * Track segment started. */ private void onTrackSegmentElementStart() { if (numberOfSegments > 0) { // Add a segment separator: location = new Location(LocationManager.GPS_PROVIDER); location.setLatitude(100.0); location.setLongitude(100.0); location.setAltitude(0); if (lastLocation != null) { location.setTime(lastLocation.getTime()); } insertTrackPoint(location); lastLocation = location; lastSegmentLocation = null; location = null; } numberOfSegments++; } /** * Reads trackpoint attributes and assigns them to the current location. * * @param attributes xml attributes */ private void onTrackPointElementStart(Attributes attributes) throws SAXException { if (location != null) { String errorMsg = createErrorMessage("Found a track point inside another one."); throw new SAXException(errorMsg); } location = createLocationFromAttributes(attributes); } /** * Creates and returns a location with the position parsed from the given * attributes. * * @param attributes the attributes to parse * @return the created location * @throws SAXException if the attributes cannot be parsed */ private Location createLocationFromAttributes(Attributes attributes) throws SAXException { String latitude = attributes.getValue(ATT_LAT); String longitude = attributes.getValue(ATT_LON); if (latitude == null || longitude == null) { throw new SAXException(createErrorMessage("Point with no longitude or latitude")); } // create new location and set attributes Location loc = new Location(LocationManager.GPS_PROVIDER); try { loc.setLatitude(Double.parseDouble(latitude)); loc.setLongitude(Double.parseDouble(longitude)); } catch (NumberFormatException e) { String msg = createErrorMessage( "Unable to parse lat/long: " + latitude + "/" + longitude); throw new SAXException(msg, e); } return loc; } /** * Track point finished, write in database. * * @throws SAXException - thrown if track point is invalid */ private void onTrackPointElementEnd() throws SAXException { if (LocationUtils.isValidLocation(location)) { if (statsBuilder == null) { // first point did not have a time, start stats builder without it statsBuilder = new TripStatisticsBuilder(0); } statsBuilder.addLocation(location, location.getTime()); // insert in db insertTrackPoint(location); // first track point? if (lastLocation == null && numberOfSegments == 1) { track.setStartId(getLastPointId()); } lastLocation = location; lastSegmentLocation = location; location = null; } else { // invalid location - abort import String msg = createErrorMessage("Invalid location detected: " + location); throw new SAXException(msg); } } private void insertTrackPoint(Location loc) { bufferedPointInserts[numBufferedPointInserts] = loc; numBufferedPointInserts++; numberOfLocations++; if (numBufferedPointInserts >= MAX_BUFFERED_LOCATIONS) { flushPointInserts(); } } private void flushPointInserts() { if (numBufferedPointInserts <= 0) { return; } providerUtils.bulkInsertTrackPoints(bufferedPointInserts, numBufferedPointInserts, track.getId()); numBufferedPointInserts = 0; } /** * Track segment finished. */ private void onTrackSegmentElementEnd() { // Nothing to be done } /** * Track finished - update in database. */ private void onTrackElementEnd() { if (lastLocation != null) { flushPointInserts(); // Calculate statistics for the imported track and update statsBuilder.pauseAt(lastLocation.getTime()); track.setStopId(getLastPointId()); track.setNumberOfPoints(numberOfLocations); track.setStatistics(statsBuilder.getStatistics()); providerUtils.updateTrack(track); tracksWritten.add(track.getId()); isCurrentTrackRollbackable = false; lastSegmentLocation = null; lastLocation = null; statsBuilder = null; } else { // track contains no track points makes no real // sense to import it as we have no location // information -> roll back rollbackUnfinishedTracks(); } } /** * Setting time and doing additional calculations as this is the last value * required. Also sets the start time for track and statistics as there is no * start time in the track root element. * * @throws SAXException on parsing errors */ private void onTimeElementEnd() throws SAXException { if (location == null) { return; } // Parse the time long time; try { time = StringUtils.parseXmlDateTime(content.trim()); } catch (IllegalArgumentException e) { String msg = createErrorMessage("Unable to parse time: " + content); throw new SAXException(msg, e); } // Calculate derived attributes from previous point if (lastSegmentLocation != null) { long timeDifference = time - lastSegmentLocation.getTime(); // check for negative time change if (timeDifference < 0) { Log.w(Constants.TAG, "Found negative time change."); } else { // We don't have a speed and bearing in GPX, make something up from // the last two points. // TODO GPS points tend to have some inherent imprecision, // speed and bearing will likely be off, so the statistics for things like // max speed will also be off. float speed = location.distanceTo(lastLocation) * 1000.0f / timeDifference; location.setSpeed(speed); location.setBearing(lastSegmentLocation.bearingTo(location)); } } // Fill in the time location.setTime(time); // initialize start time with time of first track point if (statsBuilder == null) { statsBuilder = new TripStatisticsBuilder(time); } } private void onAltitudeElementEnd() throws SAXException { if (location != null) { try { location.setAltitude(Double.parseDouble(content)); } catch (NumberFormatException e) { String msg = createErrorMessage("Unable to parse altitude: " + content); throw new SAXException(msg, e); } } } /** * Deletes the last track if it was not completely imported. */ public void rollbackUnfinishedTracks() { if (isCurrentTrackRollbackable) { providerUtils.deleteTrack(track.getId()); isCurrentTrackRollbackable = false; } } /** * Get all track ids of the tracks created by this importer run. * * @return array of track ids */ private long[] getImportedTrackIds() { // Convert from java.lang.Long for convenience long[] result = new long[tracksWritten.size()]; for (int i = 0; i < result.length; i++) { result[i] = tracksWritten.get(i); } return result; } /** * Returns the ID of the last point inserted into the database. */ private long getLastPointId() { flushPointInserts(); return providerUtils.getLastLocationId(track.getId()); } /** * Builds a parsing error message with current line information. * * @param details details about the error, will be appended * @return error message string with current line information */ private String createErrorMessage(String details) { StringBuffer msg = new StringBuffer(); msg.append("Parsing error at line: "); msg.append(locator.getLineNumber()); msg.append(" column: "); msg.append(locator.getColumnNumber()); msg.append(". "); msg.append(details); return msg.toString(); } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.io.file; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import android.content.Context; import android.util.Log; /** * A factory to produce track writers for any format. * * @author Rodrigo Damazio */ public class TrackWriterFactory { /** * Definition of all possible track formats. */ public enum TrackFileFormat { GPX { @Override TrackFormatWriter newFormatWriter(Context context) { return new GpxTrackWriter(); } }, KML { @Override TrackFormatWriter newFormatWriter(Context context) { return new KmlTrackWriter(context); } }, CSV { @Override public TrackFormatWriter newFormatWriter(Context context) { return new CsvTrackWriter(); } }, TCX { @Override public TrackFormatWriter newFormatWriter(Context context) { return new TcxTrackWriter(context); } }; /** * Creates and returns a new format writer for each format. */ abstract TrackFormatWriter newFormatWriter(Context context); /** * Returns the mime type for each format. */ public String getMimeType() { return "application/" + getExtension() + "+xml"; } /** * Returns the file extension for each format. */ public String getExtension() { return this.name().toLowerCase(); } } /** * Creates a new track writer to write the track with the given ID. * * @param context the context in which the track will be read * @param providerUtils the data provider utils to read the track with * @param trackId the ID of the track to be written * @param format the output format to write in * @return the new track writer */ public static TrackWriter newWriter(Context context, MyTracksProviderUtils providerUtils, long trackId, TrackFileFormat format) { Track track = providerUtils.getTrack(trackId); if (track == null) { Log.w(TAG, "Trying to create a writer for an invalid track, id=" + trackId); return null; } return newWriter(context, providerUtils, track, format); } /** * Creates a new track writer to write the given track. * * @param context the context in which the track will be read * @param providerUtils the data provider utils to read the track with * @param track the track to be written * @param format the output format to write in * @return the new track writer */ private static TrackWriter newWriter(Context context, MyTracksProviderUtils providerUtils, Track track, TrackFileFormat format) { TrackFormatWriter writer = format.newFormatWriter(context); return new TrackWriterImpl(context, providerUtils, track, writer); } private TrackWriterFactory() { } }
Java
/* * Copyright 2011 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 com.google.android.apps.mytracks.io.file; import java.io.File; /** * Implementations of this class export tracks to the SD card. This class is * intended to be format-neutral - it handles creating the output file and * reading the track to be exported, but requires an instance of * {@link TrackFormatWriter} to actually format the data. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public interface TrackWriter { /** This listener is used to signal completion of track write */ public interface OnCompletionListener { public void onComplete(); } /** This listener is used to signal track writes. */ public interface OnWriteListener { /** * This method is invoked whenever a location within a track is written. * @param number the location number * @param max the maximum number of locations, for calculation of * completion percentage */ public void onWrite(int number, int max); } /** * Sets listener to be invoked when the writer has finished. */ void setOnCompletionListener(OnCompletionListener onCompletionListener); /** * Sets a listener to be invoked for each location writer. */ void setOnWriteListener(OnWriteListener onWriteListener); /** * Sets a custom directory where the file will be written. */ void setDirectory(File directory); /** * Returns the absolute path to the file which was created. */ String getAbsolutePath(); /** * Writes the given track id to the SD card. * This is non-blocking. */ void writeTrackAsync(); /** * Writes the given track id to the SD card. * This is blocking. */ void writeTrack(); /** * Stop any in-progress writes */ void stopWriteTrack(); /** * Returns true if the write completed successfully. */ boolean wasSuccess(); /** * Returns the error message (if any) generated by a writer failure. */ int getErrorMessage(); }
Java
/* * Copyright 2011 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 com.google.android.apps.mytracks.io.file; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.PlayTrackUtils; import com.google.android.apps.mytracks.util.UriUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import java.io.File; /** * Activity for saving a track to a file (and optionally sending that file). * * @author Rodrigo Damazio */ public class SaveActivity extends Activity { public static final String EXTRA_FILE_FORMAT = "file_format"; public static final String EXTRA_SHARE_FILE = "share_file"; public static final String EXTRA_PLAY_FILE = "play_file"; private static final int RESULT_DIALOG = 1; /* VisibleForTesting */ static final int PROGRESS_DIALOG = 2; private MyTracksProviderUtils providerUtils; private long trackId; private TrackWriter writer; private boolean shareFile; private boolean playFile; private TrackFileFormat format; private WriteProgressController controller; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); providerUtils = MyTracksProviderUtils.Factory.get(this); } @Override protected void onStart() { super.onStart(); Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); Uri data = intent.getData(); if (!getString(R.string.track_action_save).equals(action) || !TracksColumns.CONTENT_ITEMTYPE.equals(type) || !UriUtils.matchesContentUri(data, TracksColumns.CONTENT_URI)) { Log.e(TAG, "Got bad save intent: " + intent); finish(); return; } trackId = ContentUris.parseId(data); int formatIdx = intent.getIntExtra(EXTRA_FILE_FORMAT, -1); format = TrackFileFormat.values()[formatIdx]; shareFile = intent.getBooleanExtra(EXTRA_SHARE_FILE, false); playFile = intent.getBooleanExtra(EXTRA_PLAY_FILE, false); writer = TrackWriterFactory.newWriter(this, providerUtils, trackId, format); if (writer == null) { Log.e(TAG, "Unable to build writer"); finish(); return; } if (shareFile || playFile) { // If the file is for sending, save it to a temporary location instead. FileUtils fileUtils = new FileUtils(); String extension = format.getExtension(); String dirName = fileUtils.buildExternalDirectoryPath(extension, "tmp"); File dir = new File(dirName); writer.setDirectory(dir); } controller = new WriteProgressController(this, writer, PROGRESS_DIALOG); controller.setOnCompletionListener(new WriteProgressController.OnCompletionListener() { @Override public void onComplete() { onWriteComplete(); } }); controller.startWrite(); } private void onWriteComplete() { if (shareFile) { shareWrittenFile(); } if (playFile) { playWrittenFile(); } else { showResultDialog(); } } private void shareWrittenFile() { if (!writer.wasSuccess()) { showResultDialog(); return; } // Share the file. Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getText(R.string.share_track_subject).toString()); shareIntent.putExtra(Intent.EXTRA_TEXT, getResources().getText(R.string.share_track_file_body_format) .toString()); shareIntent.setType(format.getMimeType()); Uri u = Uri.fromFile(new File(writer.getAbsolutePath())); shareIntent.putExtra(Intent.EXTRA_STREAM, u); shareIntent.putExtra(getString(R.string.track_id_broadcast_extra), trackId); startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_track_picker_title).toString())); } private void playWrittenFile() { if (!writer.wasSuccess()) { showResultDialog(); return; } Uri uri = Uri.fromFile(new File(writer.getAbsolutePath())); Intent intent = new Intent() .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .setDataAndType(uri, PlayTrackUtils.KML_MIME_TYPE); startActivity(intent); } private void showResultDialog() { removeDialog(RESULT_DIALOG); showDialog(RESULT_DIALOG); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case RESULT_DIALOG: return createResultDialog(); case PROGRESS_DIALOG: if (controller != null) { return controller.createProgressDialog(); } //$FALL-THROUGH$ default: return super.onCreateDialog(id); } } private Dialog createResultDialog() { boolean success = writer.wasSuccess(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(writer.getErrorMessage()); builder.setPositiveButton(R.string.generic_ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { dialog.dismiss(); finish(); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { dialog.dismiss(); finish(); } }); builder.setIcon(success ? android.R.drawable.ic_dialog_info : android.R.drawable.ic_dialog_alert); builder.setTitle(success ? R.string.generic_success_title : R.string.generic_error_title); return builder.create(); } public static void handleExportTrackAction(Context ctx, long trackId, int actionCode) { if (trackId < 0) { return; } TrackFileFormat exportFormat = null; switch (actionCode) { case Constants.SAVE_GPX_FILE: case Constants.SHARE_GPX_FILE: exportFormat = TrackFileFormat.GPX; break; case Constants.SAVE_KML_FILE: case Constants.SHARE_KML_FILE: exportFormat = TrackFileFormat.KML; break; case Constants.SAVE_CSV_FILE: case Constants.SHARE_CSV_FILE: exportFormat = TrackFileFormat.CSV; break; case Constants.SAVE_TCX_FILE: case Constants.SHARE_TCX_FILE: exportFormat = TrackFileFormat.TCX; break; default: throw new IllegalArgumentException("Warning unhandled action code: " + actionCode); } boolean shareFile = false; switch (actionCode) { case Constants.SHARE_GPX_FILE: case Constants.SHARE_KML_FILE: case Constants.SHARE_CSV_FILE: case Constants.SHARE_TCX_FILE: shareFile = true; } Uri uri = ContentUris.withAppendedId(TracksColumns.CONTENT_URI, trackId); Intent intent = new Intent(ctx, SaveActivity.class); intent.setAction(ctx.getString(R.string.track_action_save)); intent.setDataAndType(uri, TracksColumns.CONTENT_ITEMTYPE); intent.putExtra(EXTRA_FILE_FORMAT, exportFormat.ordinal()); intent.putExtra(EXTRA_SHARE_FILE, shareFile); ctx.startActivity(intent); } }
Java
/* * Copyright 2011 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 com.google.android.apps.mytracks.io.file; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.ImportAllTracks; import com.google.android.apps.mytracks.util.UriUtils; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.util.Log; /** * An activity that imports a track from a file and displays the track in My Tracks. * * @author Rodrigo Damazio */ public class ImportActivity extends Activity { @Override public void onStart() { super.onStart(); Intent intent = getIntent(); String action = intent.getAction(); Uri data = intent.getData(); if (!(Intent.ACTION_VIEW.equals(action) || Intent.ACTION_ATTACH_DATA.equals(action))) { Log.e(TAG, "Received an intent with unsupported action: " + intent); finish(); return; } if (!UriUtils.isFileUri(data)) { Log.e(TAG, "Received an intent with unsupported data: " + intent); finish(); return; } String path = data.getPath(); Log.i(TAG, "Importing GPX file at " + path); new ImportAllTracks(this, path); } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.FileUtils; import android.location.Location; import java.io.OutputStream; import java.io.PrintWriter; import java.text.NumberFormat; import java.util.Date; /** * Exports a track as a CSV file, according to RFC 4180. * * The first field is a type: * TRACK - track description * P - point * WAYPOINT - waypoint * * For each type, the fields are: * * TRACK,,,,,,,,name,description, * P,time,lat,lon,alt,bearing,accurancy,speed,,,segmentIdx * WAYPOINT,time,lat,lon,alt,bearing,accuracy,speed,name,description, * * @author Rodrigo Damazio */ public class CsvTrackWriter implements TrackFormatWriter { private static final NumberFormat SHORT_FORMAT = NumberFormat.getInstance(); static { SHORT_FORMAT.setMaximumFractionDigits(4); } private int segmentIdx = 0; private int numFields = -1; private PrintWriter pw; private Track track; @Override public String getExtension() { return TrackFileFormat.CSV.getExtension(); } @SuppressWarnings("hiding") @Override public void prepare(Track track, OutputStream out) { this.track = track; this.pw = new PrintWriter(out); } @Override public void writeHeader() { writeCommaSeparatedLine("TYPE", "TIME", "LAT", "LON", "ALT", "BEARING", "ACCURACY", "SPEED", "NAME", "DESCRIPTION", "SEGMENT"); } @Override public void writeBeginTrack(Location firstPoint) { writeCommaSeparatedLine("TRACK", null, null, null, null, null, null, null, track.getName(), track.getDescription(), null); } @Override public void writeOpenSegment() { // Do nothing } @Override public void writeLocation(Location location) { String timeStr = FileUtils.FILE_TIMESTAMP_FORMAT.format(new Date(location.getTime())); writeCommaSeparatedLine("P", timeStr, Double.toString(location.getLatitude()), Double.toString(location.getLongitude()), Double.toString(location.getAltitude()), Double.toString(location.getBearing()), SHORT_FORMAT.format(location.getAccuracy()), SHORT_FORMAT.format(location.getSpeed()), null, null, Integer.toString(segmentIdx)); } @Override public void writeWaypoint(Waypoint waypoint) { Location location = waypoint.getLocation(); String timeStr = FileUtils.FILE_TIMESTAMP_FORMAT.format(new Date(location.getTime())); writeCommaSeparatedLine("WAYPOINT", timeStr, Double.toString(location.getLatitude()), Double.toString(location.getLongitude()), Double.toString(location.getAltitude()), Double.toString(location.getBearing()), SHORT_FORMAT.format(location.getAccuracy()), SHORT_FORMAT.format(location.getSpeed()), waypoint.getName(), waypoint.getDescription(), null); } /** * Writes a single line of a comma-separated-value file. * * @param strs the values to be written as comma-separated */ private void writeCommaSeparatedLine(String... strs) { if (numFields == -1) { numFields = strs.length; } else if (strs.length != numFields) { throw new IllegalArgumentException( "CSV lines with different number of fields"); } boolean isFirst = true; for (String str : strs) { if (!isFirst) { pw.print(','); } isFirst = false; if (str != null) { pw.print('"'); pw.print(str.replaceAll("\"", "\"\"")); pw.print('"'); } } pw.println(); } @Override public void writeCloseSegment() { segmentIdx++; } @Override public void writeEndTrack(Location lastPoint) { // Do nothing } @Override public void writeFooter() { // Do nothing } @Override public void close() { pw.close(); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.location.Location; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; /** * This class exports tracks to the SD card. It is intended to be format- * neutral -- it handles creating the output file and reading the track to be * exported, but requires an instance of {@link TrackFormatWriter} to actually * format the data. * * @author Sandor Dornbush * @author Rodrigo Damazio */ class TrackWriterImpl implements TrackWriter { private final Context context; private final MyTracksProviderUtils providerUtils; private final Track track; private final TrackFormatWriter writer; private final FileUtils fileUtils; private boolean success = false; private int errorMessage = -1; private File directory = null; private File file = null; private OnCompletionListener onCompletionListener; private OnWriteListener onWriteListener; private Thread writeThread; TrackWriterImpl(Context context, MyTracksProviderUtils providerUtils, Track track, TrackFormatWriter writer) { this.context = context; this.providerUtils = providerUtils; this.track = track; this.writer = writer; this.fileUtils = new FileUtils(); } @Override public void setOnCompletionListener(OnCompletionListener onCompletionListener) { this.onCompletionListener = onCompletionListener; } @Override public void setOnWriteListener(OnWriteListener onWriteListener) { this.onWriteListener = onWriteListener; } @Override public void setDirectory(File directory) { this.directory = directory; } @Override public String getAbsolutePath() { return file.getAbsolutePath(); } @Override public void writeTrackAsync() { writeThread = new Thread() { @Override public void run() { doWriteTrack(); } }; writeThread.start(); } @Override public void writeTrack() { writeTrackAsync(); try { writeThread.join(); } catch (InterruptedException e) { Log.e(Constants.TAG, "Interrupted waiting for write to complete", e); } } private void doWriteTrack() { // Open the input and output success = false; errorMessage = R.string.sd_card_error_write_file; if (track != null) { if (openFile()) { try { writeDocument(); } catch (InterruptedException e) { Log.i(Constants.TAG, "The track write was interrupted"); if (file != null) { if (!file.delete()) { Log.w(TAG, "Failed to delete file " + file.getAbsolutePath()); } } success = false; errorMessage = R.string.sd_card_canceled; } } } finished(); } public void stopWriteTrack() { if (writeThread != null && writeThread.isAlive()) { Log.i(Constants.TAG, "Attempting to stop track write"); writeThread.interrupt(); try { writeThread.join(); Log.i(Constants.TAG, "Track write stopped"); } catch (InterruptedException e) { Log.e(Constants.TAG, "Failed to wait for writer to stop", e); } } } @Override public int getErrorMessage() { return errorMessage; } @Override public boolean wasSuccess() { return success; } /* * Helper methods: * =============== */ private void finished() { if (onCompletionListener != null) { runOnUiThread(new Runnable() { @Override public void run() { onCompletionListener.onComplete(); } }); return; } } /** * Runs the given runnable in the UI thread. */ protected void runOnUiThread(Runnable runnable) { if (context instanceof Activity) { ((Activity) context).runOnUiThread(runnable); } } /** * Opens the file and prepares the format writer for it. * * @return true on success, false otherwise (and errorMessage is set) */ protected boolean openFile() { if (!canWriteFile()) { return false; } // Make sure the file doesn't exist yet (possibly by changing the filename) String fileName = fileUtils.buildUniqueFileName( directory, track.getName(), writer.getExtension()); if (fileName == null) { Log.e(Constants.TAG, "Unable to get a unique filename for " + track.getName()); return false; } Log.i(Constants.TAG, "Writing track to: " + fileName); try { writer.prepare(track, newOutputStream(fileName)); } catch (FileNotFoundException e) { Log.e(Constants.TAG, "Failed to open output file.", e); errorMessage = R.string.sd_card_error_write_file; return false; } return true; } /** * Checks and returns whether we're ready to create the output file. */ protected boolean canWriteFile() { if (directory == null) { String dirName = fileUtils.buildExternalDirectoryPath(writer.getExtension()); directory = newFile(dirName); } if (!fileUtils.isSdCardAvailable()) { Log.i(Constants.TAG, "Could not find SD card."); errorMessage = R.string.sd_card_error_no_storage; return false; } if (!fileUtils.ensureDirectoryExists(directory)) { Log.i(Constants.TAG, "Could not create export directory."); errorMessage = R.string.sd_card_error_create_dir; return false; } return true; } /** * Creates a new output stream to write to the given filename. * * @throws FileNotFoundException if the file could't be created */ protected OutputStream newOutputStream(String fileName) throws FileNotFoundException { file = new File(directory, fileName); return new FileOutputStream(file); } /** * Creates a new file object for the given path. */ protected File newFile(String path) { return new File(path); } /** * Writes the waypoints for the given track. * * @param trackId the ID of the track to write waypoints for */ private void writeWaypoints(long trackId) { // TODO: Stream through he waypoints in chunks. // I am leaving the number of waypoints very high which should not be a // problem because we don't try to load them into objects all at the // same time. Cursor cursor = null; cursor = providerUtils.getWaypointsCursor(trackId, 0, Constants.MAX_LOADED_WAYPOINTS_POINTS); if (cursor != null) { try { if (cursor.moveToFirst()) { // Yes, this will skip the 1st way point and that is intentional // as the 1st points holds the stats for the current/last segment. while (cursor.moveToNext()) { Waypoint wpt = providerUtils.createWaypoint(cursor); writer.writeWaypoint(wpt); } } } finally { cursor.close(); } } } /** * Does the actual work of writing the track to the now open file. */ void writeDocument() throws InterruptedException { Log.d(Constants.TAG, "Started writing track."); writer.writeHeader(); writeWaypoints(track.getId()); writeLocations(); writer.writeFooter(); writer.close(); success = true; Log.d(Constants.TAG, "Done writing track."); errorMessage = R.string.sd_card_success_write_file; } private void writeLocations() throws InterruptedException { boolean wroteFirst = false; boolean segmentOpen = false; boolean isLastValid = false; class TrackWriterLocationFactory implements MyTracksProviderUtils.LocationFactory { Location currentLocation; Location lastLocation; @Override public Location createLocation() { if (currentLocation == null) { currentLocation = new MyTracksLocation(""); } return currentLocation; } public void swapLocations() { Location tmpLoc = lastLocation; lastLocation = currentLocation; currentLocation = tmpLoc; if (currentLocation != null) { currentLocation.reset(); } } }; TrackWriterLocationFactory locationFactory = new TrackWriterLocationFactory(); LocationIterator it = providerUtils.getLocationIterator(track.getId(), 0, false, locationFactory); try { if (!it.hasNext()) { Log.w(Constants.TAG, "Unable to get any points to write"); return; } int pointNumber = 0; while (it.hasNext()) { Location loc = it.next(); if (Thread.interrupted()) { throw new InterruptedException(); } pointNumber++; boolean isValid = LocationUtils.isValidLocation(loc); boolean validSegment = isValid && isLastValid; if (!wroteFirst && validSegment) { // Found the first two consecutive points which are valid writer.writeBeginTrack(locationFactory.lastLocation); wroteFirst = true; } if (validSegment) { if (!segmentOpen) { // Start a segment for this point writer.writeOpenSegment(); segmentOpen = true; // Write the previous point, which we had previously skipped writer.writeLocation(locationFactory.lastLocation); } // Write the current point writer.writeLocation(loc); if (onWriteListener != null) { onWriteListener.onWrite(pointNumber, track.getNumberOfPoints()); } } else { if (segmentOpen) { writer.writeCloseSegment(); segmentOpen = false; } } locationFactory.swapLocations(); isLastValid = isValid; } if (segmentOpen) { writer.writeCloseSegment(); segmentOpen = false; } if (wroteFirst) { writer.writeEndTrack(locationFactory.lastLocation); } } finally { it.close(); } } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import android.location.Location; import java.io.OutputStream; /** * Interface for writing data to a specific track file format. * * The expected sequence of calls is: * <ol> * <li>{@link #prepare} * <li>{@link #writeHeader} * <li>{@link #writeBeginTrack} * <li>For each segment: * <ol> * <li>{@link #writeOpenSegment} * <li>For each location in the segment: {@link #writeLocation} * <li>{@link #writeCloseSegment} * </ol> * <li>{@link #writeEndTrack} * <li>For each waypoint: {@link #writeWaypoint} * <li>{@link #writeFooter} * </ol> * * @author Rodrigo Damazio */ public interface TrackFormatWriter { /** * Sets up the writer to write the given track to the given output. * * @param track the track to write * @param out the stream to write the track contents to */ void prepare(Track track, OutputStream out); /** * @return The file extension (i.e. gpx, kml, ...) */ String getExtension(); /** * Writes the header. * This is chance for classes to write out opening information. */ void writeHeader(); /** * Writes the footer. * This is chance for classes to write out closing information. */ void writeFooter(); /** * Write the given location object. * * TODO Add some flexible handling of other sensor data. * * @param location the location to write */ void writeLocation(Location location) throws InterruptedException; /** * Write a way point. * * @param waypoint */ void writeWaypoint(Waypoint waypoint); /** * Write the beginning of a track. */ void writeBeginTrack(Location firstPoint); /** * Write the end of a track. */ void writeEndTrack(Location lastPoint); /** * Write the statements necessary to open a new segment. */ void writeOpenSegment(); /** * Write the statements necessary to close a segment. */ void writeCloseSegment(); /** * Close the underlying file handle. */ void close(); }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.DescriptionGenerator; import com.google.android.apps.mytracks.content.DescriptionGeneratorImpl; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.StringUtils; import com.google.common.annotations.VisibleForTesting; import android.content.Context; import android.location.Location; import android.os.Build; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Vector; /** * Write track as KML to a file. * * @author Leif Hendrik Wilden */ public class KmlTrackWriter implements TrackFormatWriter { private final Vector<Double> distances = new Vector<Double>(); private final Vector<Double> elevations = new Vector<Double>(); private final DescriptionGenerator descriptionGenerator; private PrintWriter pw = null; private Track track; public KmlTrackWriter(Context context) { descriptionGenerator = new DescriptionGeneratorImpl(context); } @VisibleForTesting KmlTrackWriter(DescriptionGenerator descriptionGenerator) { this.descriptionGenerator = descriptionGenerator; } @SuppressWarnings("hiding") @Override public void prepare(Track track, OutputStream out) { this.track = track; this.pw = new PrintWriter(out); } @Override public String getExtension() { return TrackFileFormat.KML.getExtension(); } @Override public void writeHeader() { if (pw != null) { pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); pw.print("<kml"); pw.print(" xmlns=\"http://earth.google.com/kml/2.0\""); pw.println(" xmlns:atom=\"http://www.w3.org/2005/Atom\">"); pw.println("<Document>"); pw.format("<atom:author><atom:name>My Tracks running on %s" + "</atom:name></atom:author>\n", Build.MODEL); pw.println("<name>" + StringUtils.stringAsCData(track.getName()) + "</name>"); pw.println("<description>" + StringUtils.stringAsCData(track.getDescription()) + "</description>"); writeStyles(); } } @Override public void writeFooter() { if (pw != null) { pw.println("</Document>"); pw.println("</kml>"); } } @Override public void writeBeginTrack(Location firstPoint) { if (pw != null) { writePlacemark("(Start)", track.getDescription(), "#sh_green-circle", firstPoint); pw.println("<Placemark>"); pw.println("<name>" + StringUtils.stringAsCData(track.getName()) + "</name>"); pw.println("<description>" + StringUtils.stringAsCData(track.getDescription()) + "</description>"); pw.println("<styleUrl>#track</styleUrl>"); pw.println("<MultiGeometry>"); } } @Override public void writeEndTrack(Location lastPoint) { if (pw != null) { pw.println("</MultiGeometry>"); pw.println("</Placemark>"); String description = descriptionGenerator.generateTrackDescription( track, distances, elevations); writePlacemark("(End)", description, "#sh_red-circle", lastPoint); } } @Override public void writeOpenSegment() { if (pw != null) { pw.print("<LineString><coordinates>"); } } @Override public void writeCloseSegment() { if (pw != null) { pw.println("</coordinates></LineString>"); } } @Override public void writeLocation(Location l) { if (pw != null) { pw.print(l.getLongitude() + "," + l.getLatitude() + "," + l.getAltitude() + " "); } } private String getPinStyle(Waypoint waypoint) { if (waypoint.getType() == Waypoint.TYPE_STATISTICS) { return "#sh_ylw-pushpin"; } // Try to find the icon color. // The string should be of the form: // "http://maps.google.com/mapfiles/ms/micons/XXX.png" int slash = waypoint.getIcon().lastIndexOf('/'); int png = waypoint.getIcon().lastIndexOf('.'); if ((slash != -1) && (slash < png)) { String color = waypoint.getIcon().substring(slash + 1, png); return "#sh_" + color + "-pushpin"; } return "#sh_blue-pushpin"; } @Override public void writeWaypoint(Waypoint waypoint) { if (pw != null) { writePlacemark( waypoint.getName(), waypoint.getDescription(), getPinStyle(waypoint), waypoint.getLocation()); } } @Override public void close() { if (pw != null) { pw.close(); pw = null; } } private void writeStyles() { pw.println("<Style id=\"track\"><LineStyle><color>7f0000ff</color>" + "<width>4</width></LineStyle></Style>"); pw.print("<Style id=\"sh_green-circle\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/paddle/" + "grn-circle.png</href></Icon>"); pw.println("<hotSpot x=\"32\" y=\"1\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); pw.print("<Style id=\"sh_red-circle\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/paddle/" + "red-circle.png</href></Icon>"); pw.println("<hotSpot x=\"32\" y=\"1\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); pw.print("<Style id=\"sh_ylw-pushpin\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/pushpin/" + "ylw-pushpin.png</href></Icon>"); pw.println("<hotSpot x=\"20\" y=\"2\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); pw.print("<Style id=\"sh_blue-pushpin\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/pushpin/" + "blue-pushpin.png</href></Icon>"); pw.println("<hotSpot x=\"20\" y=\"2\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); pw.print("<Style id=\"sh_green-pushpin\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/pushpin/" + "grn-pushpin.png</href></Icon>"); pw.println("<hotSpot x=\"20\" y=\"2\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); pw.print("<Style id=\"sh_red-pushpin\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/pushpin/" + "red-pushpin.png</href></Icon>"); pw.println("<hotSpot x=\"20\" y=\"2\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); } private void writePlacemark(String name, String description, String style, Location location) { if (location != null) { pw.println("<Placemark>"); pw.println(" <name>" + StringUtils.stringAsCData(name) + "</name>"); pw.println(" <description>" + StringUtils.stringAsCData(description) + "</description>"); pw.println(" <styleUrl>" + style + "</styleUrl>"); pw.println(" <Point>"); pw.println(" <coordinates>" + location.getLongitude() + "," + location.getLatitude() + "</coordinates>"); pw.println(" </Point>"); pw.println("</Placemark>"); } } }
Java
/* * Copyright 2011 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 com.google.android.apps.mytracks.io.file; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; /** * Given a {@link TrackWriter}, this class manages the process of writing the * data in the track represented by the writer. This includes the display of * a progress dialog, updating the progress bar in said dialog, and notifying * interested parties when the write completes. * * @author Matthew Simmons */ class WriteProgressController { /** * This listener is used to notify interested parties when the write has * completed. */ public interface OnCompletionListener { /** * When this method is invoked, the write has completed, and the progress * dialog has been dismissed. Whether the write succeeded can be * determined by examining the {@link TrackWriter}. */ public void onComplete(); } private final Activity activity; private final TrackWriter writer; private ProgressDialog dialog; private OnCompletionListener onCompletionListener; private final int progressDialogId; /** * @param activity the activity associated with this write * @param writer the writer which writes the track to disk. Note that this * class will use the writer's completion listener. If callers are * interested in notification upon completion of the write, they should * use {@link #setOnCompletionListener}. */ public WriteProgressController(Activity activity, TrackWriter writer, int progressDialogId) { this.activity = activity; this.writer = writer; this.progressDialogId = progressDialogId; writer.setOnCompletionListener(writerCompleteListener); writer.setOnWriteListener(writerWriteListener); } /** Set a listener to be invoked when the write completes. */ public void setOnCompletionListener(OnCompletionListener onCompletionListener) { this.onCompletionListener = onCompletionListener; } // For testing purpose OnCompletionListener getOnCompletionListener() { return onCompletionListener; } public ProgressDialog createProgressDialog() { dialog = new ProgressDialog(activity); dialog.setIcon(android.R.drawable.ic_dialog_info); dialog.setTitle(activity.getString(R.string.generic_progress_title)); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setMessage(activity.getString(R.string.sd_card_progress_write_file)); dialog.setIndeterminate(true); dialog.setOnCancelListener(dialogCancelListener); return dialog; } /** Initiate an asynchronous write. */ public void startWrite() { activity.showDialog(progressDialogId); writer.writeTrackAsync(); } /** VisibleForTesting */ ProgressDialog getDialog() { return dialog; } private final DialogInterface.OnCancelListener dialogCancelListener = new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { writer.stopWriteTrack(); } }; private final TrackWriter.OnCompletionListener writerCompleteListener = new TrackWriter.OnCompletionListener() { @Override public void onComplete() { activity.dismissDialog(progressDialogId); if (onCompletionListener != null) { onCompletionListener.onComplete(); } } }; private final TrackWriter.OnWriteListener writerWriteListener = new TrackWriter.OnWriteListener() { @Override public void onWrite(int number, int max) { if (number % 500 == 0) { dialog.setIndeterminate(false); dialog.setMax(max); dialog.setProgress(Math.min(number, max)); } } }; }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.StringUtils; import android.location.Location; import android.os.Build; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.charset.Charset; import java.text.NumberFormat; import java.util.Date; import java.util.Locale; /** * Log of one track. * * @author Sandor Dornbush */ public class GpxTrackWriter implements TrackFormatWriter { private final NumberFormat elevationFormatter; private final NumberFormat coordinateFormatter; private PrintWriter pw = null; private Track track; public GpxTrackWriter() { // GPX readers expect to see fractional numbers with US-style punctuation. // That is, they want periods for decimal points, rather than commas. elevationFormatter = NumberFormat.getInstance(Locale.US); elevationFormatter.setMaximumFractionDigits(1); elevationFormatter.setGroupingUsed(false); coordinateFormatter = NumberFormat.getInstance(Locale.US); coordinateFormatter.setMaximumFractionDigits(5); coordinateFormatter.setMaximumIntegerDigits(3); coordinateFormatter.setGroupingUsed(false); } private String formatLocation(Location l) { return "lat=\"" + coordinateFormatter.format(l.getLatitude()) + "\" lon=\"" + coordinateFormatter.format(l.getLongitude()) + "\""; } @SuppressWarnings("hiding") @Override public void prepare(Track track, OutputStream out) { this.track = track; this.pw = new PrintWriter(out); } @Override public String getExtension() { return TrackFileFormat.GPX.getExtension(); } @Override public void writeHeader() { if (pw != null) { pw.format("<?xml version=\"1.0\" encoding=\"%s\" standalone=\"yes\"?>\n", Charset.defaultCharset().name()); pw.println("<?xml-stylesheet type=\"text/xsl\" href=\"details.xsl\"?>"); pw.println("<gpx"); pw.println(" version=\"1.1\""); pw.format(" creator=\"My Tracks running on %s\"\n", Build.MODEL); pw.println(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""); pw.println(" xmlns=\"http://www.topografix.com/GPX/1/1\""); pw.print(" xmlns:topografix=\"http://www.topografix.com/GPX/Private/" + "TopoGrafix/0/1\""); pw.print(" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 "); pw.print("http://www.topografix.com/GPX/1/1/gpx.xsd "); pw.print("http://www.topografix.com/GPX/Private/TopoGrafix/0/1 "); pw.println("http://www.topografix.com/GPX/Private/TopoGrafix/0/1/" + "topografix.xsd\">"); // TODO: Author etc. } } @Override public void writeFooter() { if (pw != null) { pw.println("</gpx>"); } } @Override public void writeBeginTrack(Location firstPoint) { if (pw != null) { pw.println("<trk>"); pw.println("<name>" + StringUtils.stringAsCData(track.getName()) + "</name>"); pw.println("<desc>" + StringUtils.stringAsCData(track.getDescription()) + "</desc>"); pw.println("<number>" + track.getId() + "</number>"); pw.println("<extensions><topografix:color>c0c0c0</topografix:color></extensions>"); } } @Override public void writeEndTrack(Location lastPoint) { if (pw != null) { pw.println("</trk>"); } } @Override public void writeOpenSegment() { pw.println("<trkseg>"); } @Override public void writeCloseSegment() { pw.println("</trkseg>"); } @Override public void writeLocation(Location l) { if (pw != null) { pw.println("<trkpt " + formatLocation(l) + ">"); Date d = new Date(l.getTime()); pw.println("<ele>" + elevationFormatter.format(l.getAltitude()) + "</ele>"); pw.println("<time>" + FileUtils.FILE_TIMESTAMP_FORMAT.format(d) + "</time>"); pw.println("</trkpt>"); } } @Override public void close() { if (pw != null) { pw.close(); pw = null; } } @Override public void writeWaypoint(Waypoint waypoint) { if (pw != null) { Location l = waypoint.getLocation(); if (l != null) { pw.println("<wpt " + formatLocation(l) + ">"); pw.println("<ele>" + elevationFormatter.format(l.getAltitude()) + "</ele>"); pw.println("<time>" + FileUtils.FILE_TIMESTAMP_FORMAT.format(l.getTime()) + "</time>"); pw.println("<name>" + StringUtils.stringAsCData(waypoint.getName()) + "</name>"); pw.println("<desc>" + StringUtils.stringAsCData(waypoint.getDescription()) + "</desc>"); pw.println("</wpt>"); } } } }
Java
/* * Copyright 2012 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 com.google.android.apps.mytracks.io.fusiontables; import com.google.android.apps.mytracks.io.docs.SendDocsActivity; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendActivity; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendAsyncTask; import com.google.android.apps.mytracks.io.sendtogoogle.SendRequest; import com.google.android.apps.mytracks.io.sendtogoogle.UploadResultActivity; import com.google.android.maps.mytracks.R; import android.content.Intent; /** * An activity to send a track to Google Fusion Tables. * * @author Jimmy Shih */ public class SendFusionTablesActivity extends AbstractSendActivity { @Override protected AbstractSendAsyncTask createAsyncTask() { return new SendFusionTablesAsyncTask(this, sendRequest.getTrackId(), sendRequest.getAccount()); } @Override protected String getServiceName() { return getString(R.string.send_google_fusion_tables); } @Override protected void startNextActivity(boolean success, boolean isCancel) { sendRequest.setFusionTablesSuccess(success); Class<?> next; if (isCancel) { next = UploadResultActivity.class; } else { if (sendRequest.isSendDocs()) { next = SendDocsActivity.class; } else { next = UploadResultActivity.class; } } Intent intent = new Intent(this, next).putExtra(SendRequest.SEND_REQUEST_KEY, sendRequest); startActivity(intent); finish(); } }
Java
/* * Copyright 2012 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 com.google.android.apps.mytracks.io.fusiontables; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.api.client.util.Strings; import com.google.common.annotations.VisibleForTesting; import android.location.Location; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Locale; /** * Utilities for sending a track to Google Fusion Tables. * * @author Jimmy Shih */ public class SendFusionTablesUtils { public static final String SERVICE = "fusiontables"; private static final String UTF8 = "UTF8"; private static final String TABLE_ID = "tableid"; private static final String MAP_URL = "https://www.google.com/fusiontables/embedviz?" + "viz=MAP&q=select+col0,+col1,+col2,+col3+from+%s+&h=false&lat=%f&lng=%f&z=%d&t=1&l=col2"; private static final String TAG = SendFusionTablesUtils.class.getSimpleName(); private SendFusionTablesUtils() {} /** * Gets the url to visualize a fusion table on a map. * * @param track the track * @return the url. */ public static String getMapUrl(Track track) { if (track == null || track.getStatistics() == null || track.getTableId() == null) { Log.e(TAG, "Invalid track"); return null; } // TODO(jshih): Determine the correct bounding box and zoom level that // will show the entire track. TripStatistics stats = track.getStatistics(); double latE6 = stats.getBottom() + (stats.getTop() - stats.getBottom()) / 2; double lonE6 = stats.getLeft() + (stats.getRight() - stats.getLeft()) / 2; int z = 15; // We explicitly format with Locale.US because we need the latitude and // longitude to be formatted in a locale-independent manner. Specifically, // we need the decimal separator to be a period rather than a comma. return String.format( Locale.US, MAP_URL, track.getTableId(), latE6 / 1.E6, lonE6 / 1.E6, z); } /** * Formats an array of values as a SQL VALUES like * ('value1','value2',...,'value_n'). Escapes single quotes with two single * quotes. * * @param values an array of values to format * @return the formated SQL VALUES. */ public static String formatSqlValues(String... values) { StringBuilder builder = new StringBuilder("("); for (int i = 0; i < values.length; i++) { if (i > 0) { builder.append(','); } builder.append('\''); builder.append(escapeSqlString(values[i])); builder.append('\''); } builder.append(")"); return builder.toString(); } /** * Escapes a SQL string. Escapes single quotes with two single quotes. * * @param string the string * @return the escaped string. */ public static String escapeSqlString(String string) { return string.replaceAll("'", "''"); } /** * Gets a KML Point value representing a location. * * @param location the location * @return the KML Point value. */ public static String getKmlPoint(Location location) { StringBuilder builder = new StringBuilder("<Point><coordinates>"); if (location != null) { appendLocation(location, builder); } builder.append("</coordinates></Point>"); return builder.toString(); } /** * Gets a KML LineString value representing an array of locations. * * @param locations the locations. * @return the KML LineString value. */ public static String getKmlLineString(ArrayList<Location> locations) { StringBuilder builder = new StringBuilder("<LineString><coordinates>"); if (locations != null) { for (int i = 0; i < locations.size(); i++) { if (i != 0) { builder.append(' '); } appendLocation(locations.get(i), builder); } } builder.append("</coordinates></LineString>"); return builder.toString(); } /** * Appends a location to a string builder using "longitude,latitude[,altitude]" format. * * @param location the location * @param builder the string builder */ @VisibleForTesting static void appendLocation(Location location, StringBuilder builder) { builder.append(location.getLongitude()).append(",").append(location.getLatitude()); if (location.hasAltitude()) { builder.append(","); builder.append(location.getAltitude()); } } /** * Gets the table id from an input streawm. * * @param inputStream input stream * @return table id or null if not available. */ public static String getTableId(InputStream inputStream) { if (inputStream == null) { Log.d(TAG, "inputStream is null"); return null; } byte[] result = new byte[1024]; int read; try { read = inputStream.read(result); } catch (IOException e) { Log.d(TAG, "Unable to read result", e); return null; } if (read == -1) { Log.d(TAG, "no data read"); return null; } String s; try { s = new String(result, 0, read, UTF8); } catch (UnsupportedEncodingException e) { Log.d(TAG, "Unable to parse result", e); return null; } String[] lines = s.split(Strings.LINE_SEPARATOR); if (lines.length > 1 && lines[0].equals(TABLE_ID)) { // returns the next line return lines[1]; } else { Log.d(TAG, "Response is not valid: " + s); return null; } } }
Java
// Copyright 2012 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.fusiontables; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.DescriptionGenerator; import com.google.android.apps.mytracks.content.DescriptionGeneratorImpl; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendAsyncTask; import com.google.android.apps.mytracks.io.sendtogoogle.SendToGoogleUtils; import com.google.android.apps.mytracks.stats.DoubleBuffer; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.ApiAdapterFactory; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.MethodOverride; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.InputStreamContent; import com.google.api.client.util.Strings; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Vector; /** * AsyncTask to send a track to Google Fusion Tables. * * @author Jimmy Shih */ public class SendFusionTablesAsyncTask extends AbstractSendAsyncTask { private static final String APP_NAME_PREFIX = "Google-MyTracks-"; private static final String SQL_KEY = "sql="; private static final String CONTENT_TYPE = "application/x-www-form-urlencoded"; private static final String FUSION_TABLES_BASE_URL = "https://www.google.com/fusiontables/api/query"; private static final int MAX_POINTS_PER_UPLOAD = 2048; private static final String GDATA_VERSION = "2"; private static final int PROGRESS_CREATE_TABLE = 0; private static final int PROGRESS_UNLIST_TABLE = 5; private static final int PROGRESS_UPLOAD_DATA_MIN = 10; private static final int PROGRESS_UPLOAD_DATA_MAX = 90; private static final int PROGRESS_UPLOAD_WAYPOINTS = 95; private static final int PROGRESS_COMPLETE = 100; // See http://support.google.com/fusiontables/bin/answer.py?hl=en&answer=185991 private static final String MARKER_TYPE_START = "large_green"; private static final String MARKER_TYPE_END = "large_red"; private static final String MARKER_TYPE_WAYPOINT = "large_yellow"; private static final String TAG = SendFusionTablesAsyncTask.class.getSimpleName(); private final Context context; private final long trackId; private final Account account; private final MyTracksProviderUtils myTracksProviderUtils; private final HttpRequestFactory httpRequestFactory; // The following variables are for per upload states private String authToken; private String tableId; int currentSegment; public SendFusionTablesAsyncTask( SendFusionTablesActivity activity, long trackId, Account account) { super(activity); this.trackId = trackId; this.account = account; context = activity.getApplicationContext(); myTracksProviderUtils = MyTracksProviderUtils.Factory.get(context); HttpTransport transport = ApiAdapterFactory.getApiAdapter().getHttpTransport(); httpRequestFactory = transport.createRequestFactory(new MethodOverride()); } @Override protected void closeConnection() { // No action needed for Google Fusion Tables } @Override protected void saveResult() { Track track = myTracksProviderUtils.getTrack(trackId); if (track != null) { track.setTableId(tableId); myTracksProviderUtils.updateTrack(track); } else { Log.d(TAG, "No track"); } } @Override protected boolean performTask() { // Reset the per upload states authToken = null; tableId = null; currentSegment = 1; try { authToken = AccountManager.get(context).blockingGetAuthToken( account, SendFusionTablesUtils.SERVICE, false); } catch (OperationCanceledException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } catch (AuthenticatorException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } catch (IOException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } Track track = myTracksProviderUtils.getTrack(trackId); if (track == null) { Log.d(TAG, "Track is null"); return false; } // Create a new table publishProgress(PROGRESS_CREATE_TABLE); if (!createNewTable(track)) { // Retry upload in case the auth token is invalid return retryTask(); } // Unlist table publishProgress(PROGRESS_UNLIST_TABLE); if (!unlistTable()) { return false; } // Upload all the track points plus the start and end markers publishProgress(PROGRESS_UPLOAD_DATA_MIN); if (!uploadAllTrackPoints(track)) { return false; } // Upload all the waypoints publishProgress(PROGRESS_UPLOAD_WAYPOINTS); if (!uploadWaypoints()) { return false; } publishProgress(PROGRESS_COMPLETE); return true; } @Override protected void invalidateToken() { AccountManager.get(context).invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken); } /** * Creates a new table. * * @param track the track * @return true if success. */ private boolean createNewTable(Track track) { String query = "CREATE TABLE '" + SendFusionTablesUtils.escapeSqlString(track.getName()) + "' (name:STRING,description:STRING,geometry:LOCATION,marker:STRING)"; return sendQuery(query, true); } /** * Unlists a table. * * @return true if success. */ private boolean unlistTable() { String query = "UPDATE TABLE " + tableId + " SET VISIBILITY = UNLISTED"; return sendQuery(query, false); } /** * Uploads all the points in a track. * * @param track the track * @return true if success. */ private boolean uploadAllTrackPoints(Track track) { Cursor locationsCursor = null; try { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); boolean metricUnits = prefs.getBoolean(context.getString(R.string.metric_units_key), true); locationsCursor = myTracksProviderUtils.getLocationsCursor(trackId, 0, -1, false); if (locationsCursor == null) { Log.d(TAG, "Location cursor is null"); return false; } int locationsCount = locationsCursor.getCount(); List<Location> locations = new ArrayList<Location>(MAX_POINTS_PER_UPLOAD); Location lastLocation = null; // For chart server, limit the number of elevation readings to 250. int elevationSamplingFrequency = Math.max(1, (int) (locationsCount / 250.0)); TripStatisticsBuilder tripStatisticsBuilder = new TripStatisticsBuilder( track.getStatistics().getStartTime()); DoubleBuffer elevationBuffer = new DoubleBuffer(Constants.ELEVATION_SMOOTHING_FACTOR); Vector<Double> distances = new Vector<Double>(); Vector<Double> elevations = new Vector<Double>(); for (int i = 0; i < locationsCount; i++) { locationsCursor.moveToPosition(i); Location location = myTracksProviderUtils.createLocation(locationsCursor); locations.add(location); if (i == 0) { // Create a start marker String name = context.getString(R.string.marker_label_start, track.getName()); if (!createNewPoint(name, "", location, MARKER_TYPE_START)) { Log.d(TAG, "Unable to create the start marker"); return false; } } // Add to the distances and elevations vectors if (LocationUtils.isValidLocation(location)) { tripStatisticsBuilder.addLocation(location, location.getTime()); // All points go into the smoothing buffer elevationBuffer.setNext(metricUnits ? location.getAltitude() : location.getAltitude() * UnitConversions.M_TO_FT); if (i % elevationSamplingFrequency == 0) { distances.add(tripStatisticsBuilder.getStatistics().getTotalDistance()); elevations.add(elevationBuffer.getAverage()); } lastLocation = location; } // Upload periodically int readCount = i + 1; if (readCount % MAX_POINTS_PER_UPLOAD == 0) { if (!prepareAndUploadPoints(track, locations, false)) { Log.d(TAG, "Unable to upload points"); return false; } updateProgress(readCount, locationsCount); locations.clear(); } } // Do a final upload with the remaining locations if (!prepareAndUploadPoints(track, locations, true)) { Log.d(TAG, "Unable to upload points"); return false; } // Create an end marker if (lastLocation != null) { distances.add(tripStatisticsBuilder.getStatistics().getTotalDistance()); elevations.add(elevationBuffer.getAverage()); DescriptionGenerator descriptionGenerator = new DescriptionGeneratorImpl(context); track.setDescription("<p>" + track.getDescription() + "</p><p>" + descriptionGenerator.generateTrackDescription(track, distances, elevations) + "</p>"); String name = context.getString(R.string.marker_label_end, track.getName()); if (!createNewPoint(name, track.getDescription(), lastLocation, MARKER_TYPE_END)) { Log.d(TAG, "Unable to create the end marker"); return false; } } return true; } finally { if (locationsCursor != null) { locationsCursor.close(); } } } /** * Prepares and uploads a list of locations from a track. * * @param track the track * @param locations the locations from the track * @param lastBatch true if it is the last batch of locations */ private boolean prepareAndUploadPoints(Track track, List<Location> locations, boolean lastBatch) { // Prepare locations ArrayList<Track> splitTracks = SendToGoogleUtils.prepareLocations(track, locations); // Upload segments boolean onlyOneSegment = lastBatch && currentSegment == 1 && splitTracks.size() == 1; for (Track splitTrack : splitTracks) { if (!onlyOneSegment) { splitTrack.setName(context.getString( R.string.send_google_track_part_label, splitTrack.getName(), currentSegment)); } if (!createNewLineString(splitTrack)) { Log.d(TAG, "Upload points failed"); return false; } currentSegment++; } return true; } /** * Uploads all the waypoints. * * @return true if success. */ private boolean uploadWaypoints() { Cursor cursor = null; try { cursor = myTracksProviderUtils.getWaypointsCursor( trackId, 0, Constants.MAX_LOADED_WAYPOINTS_POINTS); if (cursor != null && cursor.moveToFirst()) { // This will skip the first waypoint (it carries the stats for the // track). while (cursor.moveToNext()) { Waypoint wpt = myTracksProviderUtils.createWaypoint(cursor); if (!createNewPoint( wpt.getName(), wpt.getDescription(), wpt.getLocation(), MARKER_TYPE_WAYPOINT)) { Log.d(TAG, "Upload waypoints failed"); return false; } } } return true; } finally { if (cursor != null) { cursor.close(); } } } /** * Creates a new row in Google Fusion Tables representing a marker as a * point. * * @param name the marker name * @param description the marker description * @param location the marker location * @param type the marker type * @return true if success. */ private boolean createNewPoint( String name, String description, Location location, String type) { String query = "INSERT INTO " + tableId + " (name,description,geometry,marker) VALUES " + SendFusionTablesUtils.formatSqlValues( name, description, SendFusionTablesUtils.getKmlPoint(location), type); return sendQuery(query, false); } /** * Creates a new row in Google Fusion Tables representing the track as a * line segment. * * @param track the track * @return true if success. */ private boolean createNewLineString(Track track) { String query = "INSERT INTO " + tableId + " (name,description,geometry) VALUES " + SendFusionTablesUtils.formatSqlValues(track.getName(), track.getDescription(), SendFusionTablesUtils.getKmlLineString(track.getLocations())); return sendQuery(query, false); } /** * Sends a query to Google Fusion Tables. * * @param query the Fusion Tables SQL query * @param setTableId true to set the table id * @return true if success. */ private boolean sendQuery(String query, boolean setTableId) { Log.d(TAG, "SendQuery: " + query); if (isCancelled()) { return false; } GenericUrl url = new GenericUrl(FUSION_TABLES_BASE_URL); String sql = SQL_KEY + URLEncoder.encode(query); ByteArrayInputStream inputStream = new ByteArrayInputStream(Strings.toBytesUtf8(sql)); InputStreamContent inputStreamContent = new InputStreamContent(null, inputStream); HttpRequest request; try { request = httpRequestFactory.buildPostRequest(url, inputStreamContent); } catch (IOException e) { Log.d(TAG, "Unable to build request", e); return false; } GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName(APP_NAME_PREFIX + SystemUtils.getMyTracksVersion(context)); headers.gdataVersion = GDATA_VERSION; headers.setGoogleLogin(authToken); headers.setContentType(CONTENT_TYPE); request.setHeaders(headers); HttpResponse response; try { response = request.execute(); } catch (IOException e) { Log.d(TAG, "Unable to execute request", e); return false; } boolean isSuccess = response.isSuccessStatusCode(); if (isSuccess) { InputStream content; try { content = response.getContent(); } catch (IOException e) { Log.d(TAG, "Unable to get response", e); return false; } if (setTableId) { tableId = SendFusionTablesUtils.getTableId(content); if (tableId == null) { Log.d(TAG, "tableId is null"); return false; } } } else { Log.d(TAG, "sendQuery failed: " + response.getStatusMessage() + ": " + response.getStatusCode()); return false; } return true; } /** * Updates the progress based on the number of locations uploaded. * * @param uploaded the number of uploaded locations * @param total the number of total locations */ private void updateProgress(int uploaded, int total) { double totalPercentage = uploaded / total; double scaledPercentage = totalPercentage * (PROGRESS_UPLOAD_DATA_MAX - PROGRESS_UPLOAD_DATA_MIN) + PROGRESS_UPLOAD_DATA_MIN; publishProgress((int) scaledPercentage); } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.content; import android.os.Parcel; import android.os.Parcelable; /** * A request for the service to create a waypoint at the current location. * * @author Sandor Dornbush */ public class WaypointCreationRequest implements Parcelable { public static enum WaypointType { MARKER, STATISTICS; } private WaypointType type; private String name; private String description; private String iconUrl; public final static WaypointCreationRequest DEFAULT_MARKER = new WaypointCreationRequest(WaypointType.MARKER); public final static WaypointCreationRequest DEFAULT_STATISTICS = new WaypointCreationRequest(WaypointType.STATISTICS); private WaypointCreationRequest(WaypointType type) { this.type = type; } public WaypointCreationRequest(WaypointType type, String name, String description, String iconUrl) { this.type = type; this.name = name; this.description = description; this.iconUrl = iconUrl; } public static class Creator implements Parcelable.Creator<WaypointCreationRequest> { @Override public WaypointCreationRequest createFromParcel(Parcel source) { int i = source.readInt(); if (i > WaypointType.values().length) { throw new IllegalArgumentException("Could not find waypoint type: " + i); } WaypointCreationRequest request = new WaypointCreationRequest(WaypointType.values()[i]); request.description = source.readString(); request.iconUrl = source.readString(); request.name = source.readString(); return request; } public WaypointCreationRequest[] newArray(int size) { return new WaypointCreationRequest[size]; } } public static final Creator CREATOR = new Creator(); @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int arg1) { parcel.writeInt(type.ordinal()); parcel.writeString(description); parcel.writeString(iconUrl); parcel.writeString(name); } public WaypointType getType() { return type; } public String getName() { return name; } public String getDescription() { return description; } public String getIconUrl() { return iconUrl; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.stats.TripStatistics; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; /** * A class representing a (GPS) Track. * * TODO: hashCode and equals * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class Track implements Parcelable { /** * Creator for a Track object. */ public static class Creator implements Parcelable.Creator<Track> { public Track createFromParcel(Parcel source) { ClassLoader classLoader = getClass().getClassLoader(); Track track = new Track(); track.id = source.readLong(); track.name = source.readString(); track.description = source.readString(); track.mapId = source.readString(); track.category = source.readString(); track.startId = source.readLong(); track.stopId = source.readLong(); track.stats = source.readParcelable(classLoader); track.numberOfPoints = source.readInt(); for (int i = 0; i < track.numberOfPoints; ++i) { Location loc = source.readParcelable(classLoader); track.locations.add(loc); } track.tableId = source.readString(); return track; } public Track[] newArray(int size) { return new Track[size]; } } public static final Creator CREATOR = new Creator(); /** * The track points (which may not have been loaded). */ private ArrayList<Location> locations = new ArrayList<Location>(); /** * The number of location points (present even if the points themselves were * not loaded). */ private int numberOfPoints = 0; private long id = -1; private String name = ""; private String description = ""; private String mapId = ""; private String tableId = ""; private long startId = -1; private long stopId = -1; private String category = ""; private TripStatistics stats = new TripStatistics(); public Track() { } public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeString(name); dest.writeString(description); dest.writeString(mapId); dest.writeString(category); dest.writeLong(startId); dest.writeLong(stopId); dest.writeParcelable(stats, 0); dest.writeInt(numberOfPoints); for (int i = 0; i < numberOfPoints; ++i) { dest.writeParcelable(locations.get(i), 0); } dest.writeString(tableId); } // Getters and setters: //--------------------- public int describeContents() { return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getStartId() { return startId; } public void setStartId(long startId) { this.startId = startId; } public long getStopId() { return stopId; } public void setStopId(long stopId) { this.stopId = stopId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getMapId() { return mapId; } public void setMapId(String mapId) { this.mapId = mapId; } public String getTableId() { return tableId; } public void setTableId(String tableId) { this.tableId = tableId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public int getNumberOfPoints() { return numberOfPoints; } public void setNumberOfPoints(int numberOfPoints) { this.numberOfPoints = numberOfPoints; } public void addLocation(Location l) { locations.add(l); } public ArrayList<Location> getLocations() { return locations; } public void setLocations(ArrayList<Location> locations) { this.locations = locations; } public TripStatistics getStatistics() { return stats; } public void setStatistics(TripStatistics stats) { this.stats = stats; } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.content; import android.location.Location; /** * This class extends the standard Android location with extra information. * * @author Sandor Dornbush */ public class MyTracksLocation extends Location { private Sensor.SensorDataSet sensorDataSet = null; /** * The id of this location from the provider. */ private int id = -1; public MyTracksLocation(Location location, Sensor.SensorDataSet sd) { super(location); this.sensorDataSet = sd; } public MyTracksLocation(String provider) { super(provider); } public Sensor.SensorDataSet getSensorDataSet() { return sensorDataSet; } public void setSensorData(Sensor.SensorDataSet sensorData) { this.sensorDataSet = sensorData; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void reset() { super.reset(); sensorDataSet = null; id = -1; } }
Java
/* * Copyright 2009 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 com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the tracks provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface WaypointsColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/waypoints"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.waypoint"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.waypoint"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String CATEGORY = "category"; public static final String ICON = "icon"; public static final String TRACKID = "trackid"; public static final String TYPE = "type"; public static final String LENGTH = "length"; public static final String DURATION = "duration"; public static final String STARTTIME = "starttime"; public static final String STARTID = "startid"; public static final String STOPID = "stopid"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String ALTITUDE = "elevation"; public static final String BEARING = "bearing"; public static final String TIME = "time"; public static final String ACCURACY = "accuracy"; public static final String SPEED = "speed"; public static final String TOTALDISTANCE = "totaldistance"; public static final String TOTALTIME = "totaltime"; public static final String MOVINGTIME = "movingtime"; public static final String AVGSPEED = "avgspeed"; public static final String AVGMOVINGSPEED = "avgmovingspeed"; public static final String MAXSPEED = "maxspeed"; public static final String MINELEVATION = "minelevation"; public static final String MAXELEVATION = "maxelevation"; public static final String ELEVATIONGAIN = "elevationgain"; public static final String MINGRADE = "mingrade"; public static final String MAXGRADE = "maxgrade"; }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the track points provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface TrackPointsColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/trackpoints"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.trackpoint"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.trackpoint"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String TRACKID = "trackid"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String ALTITUDE = "elevation"; public static final String BEARING = "bearing"; public static final String TIME = "time"; public static final String ACCURACY = "accuracy"; public static final String SPEED = "speed"; public static final String SENSOR = "sensor"; }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import static com.google.android.apps.mytracks.lib.MyTracksLibConstants.TAG; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.protobuf.InvalidProtocolBufferException; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; /** * Helper class providing easy access to locations and tracks in the * MyTracksProvider. All static members. * * @author Leif Hendrik Wilden */ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { private final ContentResolver contentResolver; private int defaultCursorBatchSize = 2000; public MyTracksProviderUtilsImpl(ContentResolver contentResolver) { this.contentResolver = contentResolver; } /** * Creates the ContentValues for a given location object. * * @param location a given location * @param trackId the id of the track it belongs to * @return a filled in ContentValues object */ private static ContentValues createContentValues( Location location, long trackId) { ContentValues values = new ContentValues(); values.put(TrackPointsColumns.TRACKID, trackId); values.put(TrackPointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); values.put(TrackPointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); // This is an ugly hack for Samsung phones that don't properly populate the // time field. values.put(TrackPointsColumns.TIME, (location.getTime() == 0) ? System.currentTimeMillis() : location.getTime()); if (location.hasAltitude()) { values.put(TrackPointsColumns.ALTITUDE, location.getAltitude()); } if (location.hasBearing()) { values.put(TrackPointsColumns.BEARING, location.getBearing()); } if (location.hasAccuracy()) { values.put(TrackPointsColumns.ACCURACY, location.getAccuracy()); } if (location.hasSpeed()) { values.put(TrackPointsColumns.SPEED, location.getSpeed()); } if (location instanceof MyTracksLocation) { MyTracksLocation mtLocation = (MyTracksLocation) location; if (mtLocation.getSensorDataSet() != null) { values.put(TrackPointsColumns.SENSOR, mtLocation.getSensorDataSet().toByteArray()); } } return values; } @Override public ContentValues createContentValues(Track track) { ContentValues values = new ContentValues(); TripStatistics stats = track.getStatistics(); // Values id < 0 indicate no id is available: if (track.getId() >= 0) { values.put(TracksColumns._ID, track.getId()); } values.put(TracksColumns.NAME, track.getName()); values.put(TracksColumns.DESCRIPTION, track.getDescription()); values.put(TracksColumns.MAPID, track.getMapId()); values.put(TracksColumns.TABLEID, track.getTableId()); values.put(TracksColumns.CATEGORY, track.getCategory()); values.put(TracksColumns.NUMPOINTS, track.getNumberOfPoints()); values.put(TracksColumns.STARTID, track.getStartId()); values.put(TracksColumns.STARTTIME, stats.getStartTime()); values.put(TracksColumns.STOPTIME, stats.getStopTime()); values.put(TracksColumns.STOPID, track.getStopId()); values.put(TracksColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(TracksColumns.TOTALTIME, stats.getTotalTime()); values.put(TracksColumns.MOVINGTIME, stats.getMovingTime()); values.put(TracksColumns.MAXLAT, stats.getTop()); values.put(TracksColumns.MINLAT, stats.getBottom()); values.put(TracksColumns.MAXLON, stats.getRight()); values.put(TracksColumns.MINLON, stats.getLeft()); values.put(TracksColumns.AVGSPEED, stats.getAverageSpeed()); values.put(TracksColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(TracksColumns.MAXSPEED, stats.getMaxSpeed()); values.put(TracksColumns.MINELEVATION, stats.getMinElevation()); values.put(TracksColumns.MAXELEVATION, stats.getMaxElevation()); values.put(TracksColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(TracksColumns.MINGRADE, stats.getMinGrade()); values.put(TracksColumns.MAXGRADE, stats.getMaxGrade()); return values; } private static ContentValues createContentValues(Waypoint waypoint) { ContentValues values = new ContentValues(); // Values id < 0 indicate no id is available: if (waypoint.getId() >= 0) { values.put(WaypointsColumns._ID, waypoint.getId()); } values.put(WaypointsColumns.NAME, waypoint.getName()); values.put(WaypointsColumns.DESCRIPTION, waypoint.getDescription()); values.put(WaypointsColumns.CATEGORY, waypoint.getCategory()); values.put(WaypointsColumns.ICON, waypoint.getIcon()); values.put(WaypointsColumns.TRACKID, waypoint.getTrackId()); values.put(WaypointsColumns.TYPE, waypoint.getType()); values.put(WaypointsColumns.LENGTH, waypoint.getLength()); values.put(WaypointsColumns.DURATION, waypoint.getDuration()); values.put(WaypointsColumns.STARTID, waypoint.getStartId()); values.put(WaypointsColumns.STOPID, waypoint.getStopId()); TripStatistics stats = waypoint.getStatistics(); if (stats != null) { values.put(WaypointsColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(WaypointsColumns.TOTALTIME, stats.getTotalTime()); values.put(WaypointsColumns.MOVINGTIME, stats.getMovingTime()); values.put(WaypointsColumns.AVGSPEED, stats.getAverageSpeed()); values.put(WaypointsColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(WaypointsColumns.MAXSPEED, stats.getMaxSpeed()); values.put(WaypointsColumns.MINELEVATION, stats.getMinElevation()); values.put(WaypointsColumns.MAXELEVATION, stats.getMaxElevation()); values.put(WaypointsColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(WaypointsColumns.MINGRADE, stats.getMinGrade()); values.put(WaypointsColumns.MAXGRADE, stats.getMaxGrade()); values.put(WaypointsColumns.STARTTIME, stats.getStartTime()); } Location location = waypoint.getLocation(); if (location != null) { values.put(WaypointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); values.put(WaypointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); values.put(WaypointsColumns.TIME, location.getTime()); if (location.hasAltitude()) { values.put(WaypointsColumns.ALTITUDE, location.getAltitude()); } if (location.hasBearing()) { values.put(WaypointsColumns.BEARING, location.getBearing()); } if (location.hasAccuracy()) { values.put(WaypointsColumns.ACCURACY, location.getAccuracy()); } if (location.hasSpeed()) { values.put(WaypointsColumns.SPEED, location.getSpeed()); } } return values; } @Override public Location createLocation(Cursor cursor) { Location location = new MyTracksLocation(""); fillLocation(cursor, location); return location; } /** * A cache of track column indices. */ private static class CachedTrackColumnIndices { public final int idxId; public final int idxLatitude; public final int idxLongitude; public final int idxAltitude; public final int idxTime; public final int idxBearing; public final int idxAccuracy; public final int idxSpeed; public final int idxSensor; public CachedTrackColumnIndices(Cursor cursor) { idxId = cursor.getColumnIndex(TrackPointsColumns._ID); idxLatitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LATITUDE); idxLongitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LONGITUDE); idxAltitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.ALTITUDE); idxTime = cursor.getColumnIndexOrThrow(TrackPointsColumns.TIME); idxBearing = cursor.getColumnIndexOrThrow(TrackPointsColumns.BEARING); idxAccuracy = cursor.getColumnIndexOrThrow(TrackPointsColumns.ACCURACY); idxSpeed = cursor.getColumnIndexOrThrow(TrackPointsColumns.SPEED); idxSensor = cursor.getColumnIndexOrThrow(TrackPointsColumns.SENSOR); } } private void fillLocation(Cursor cursor, CachedTrackColumnIndices columnIndices, Location location) { location.reset(); if (!cursor.isNull(columnIndices.idxLatitude)) { location.setLatitude(1. * cursor.getInt(columnIndices.idxLatitude) / 1E6); } if (!cursor.isNull(columnIndices.idxLongitude)) { location.setLongitude(1. * cursor.getInt(columnIndices.idxLongitude) / 1E6); } if (!cursor.isNull(columnIndices.idxAltitude)) { location.setAltitude(cursor.getFloat(columnIndices.idxAltitude)); } if (!cursor.isNull(columnIndices.idxTime)) { location.setTime(cursor.getLong(columnIndices.idxTime)); } if (!cursor.isNull(columnIndices.idxBearing)) { location.setBearing(cursor.getFloat(columnIndices.idxBearing)); } if (!cursor.isNull(columnIndices.idxSpeed)) { location.setSpeed(cursor.getFloat(columnIndices.idxSpeed)); } if (!cursor.isNull(columnIndices.idxAccuracy)) { location.setAccuracy(cursor.getFloat(columnIndices.idxAccuracy)); } if (location instanceof MyTracksLocation && !cursor.isNull(columnIndices.idxSensor)) { MyTracksLocation mtLocation = (MyTracksLocation) location; // TODO get the right buffer. Sensor.SensorDataSet sensorData; try { sensorData = Sensor.SensorDataSet.parseFrom(cursor.getBlob(columnIndices.idxSensor)); mtLocation.setSensorData(sensorData); } catch (InvalidProtocolBufferException e) { Log.w(TAG, "Failed to parse sensor data.", e); } } } @Override public void fillLocation(Cursor cursor, Location location) { CachedTrackColumnIndices columnIndicies = new CachedTrackColumnIndices(cursor); fillLocation(cursor, columnIndicies, location); } @Override public Track createTrack(Cursor cursor) { int idxId = cursor.getColumnIndexOrThrow(TracksColumns._ID); int idxName = cursor.getColumnIndexOrThrow(TracksColumns.NAME); int idxDescription = cursor.getColumnIndexOrThrow(TracksColumns.DESCRIPTION); int idxMapId = cursor.getColumnIndexOrThrow(TracksColumns.MAPID); int idxTableId = cursor.getColumnIndexOrThrow(TracksColumns.TABLEID); int idxCategory = cursor.getColumnIndexOrThrow(TracksColumns.CATEGORY); int idxStartId = cursor.getColumnIndexOrThrow(TracksColumns.STARTID); int idxStartTime = cursor.getColumnIndexOrThrow(TracksColumns.STARTTIME); int idxStopTime = cursor.getColumnIndexOrThrow(TracksColumns.STOPTIME); int idxStopId = cursor.getColumnIndexOrThrow(TracksColumns.STOPID); int idxNumPoints = cursor.getColumnIndexOrThrow(TracksColumns.NUMPOINTS); int idxMaxlat = cursor.getColumnIndexOrThrow(TracksColumns.MAXLAT); int idxMinlat = cursor.getColumnIndexOrThrow(TracksColumns.MINLAT); int idxMaxlon = cursor.getColumnIndexOrThrow(TracksColumns.MAXLON); int idxMinlon = cursor.getColumnIndexOrThrow(TracksColumns.MINLON); int idxTotalDistance = cursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE); int idxTotalTime = cursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME); int idxMovingTime = cursor.getColumnIndexOrThrow(TracksColumns.MOVINGTIME); int idxMaxSpeed = cursor.getColumnIndexOrThrow(TracksColumns.MAXSPEED); int idxMinElevation = cursor.getColumnIndexOrThrow(TracksColumns.MINELEVATION); int idxMaxElevation = cursor.getColumnIndexOrThrow(TracksColumns.MAXELEVATION); int idxElevationGain = cursor.getColumnIndexOrThrow(TracksColumns.ELEVATIONGAIN); int idxMinGrade = cursor.getColumnIndexOrThrow(TracksColumns.MINGRADE); int idxMaxGrade = cursor.getColumnIndexOrThrow(TracksColumns.MAXGRADE); Track track = new Track(); TripStatistics stats = track.getStatistics(); if (!cursor.isNull(idxId)) { track.setId(cursor.getLong(idxId)); } if (!cursor.isNull(idxName)) { track.setName(cursor.getString(idxName)); } if (!cursor.isNull(idxDescription)) { track.setDescription(cursor.getString(idxDescription)); } if (!cursor.isNull(idxMapId)) { track.setMapId(cursor.getString(idxMapId)); } if (!cursor.isNull(idxTableId)) { track.setTableId(cursor.getString(idxTableId)); } if (!cursor.isNull(idxCategory)) { track.setCategory(cursor.getString(idxCategory)); } if (!cursor.isNull(idxStartId)) { track.setStartId(cursor.getInt(idxStartId)); } if (!cursor.isNull(idxStartTime)) { stats.setStartTime(cursor.getLong(idxStartTime)); } if (!cursor.isNull(idxStopTime)) { stats.setStopTime(cursor.getLong(idxStopTime)); } if (!cursor.isNull(idxStopId)) { track.setStopId(cursor.getInt(idxStopId)); } if (!cursor.isNull(idxNumPoints)) { track.setNumberOfPoints(cursor.getInt(idxNumPoints)); } if (!cursor.isNull(idxTotalDistance)) { stats.setTotalDistance(cursor.getFloat(idxTotalDistance)); } if (!cursor.isNull(idxTotalTime)) { stats.setTotalTime(cursor.getLong(idxTotalTime)); } if (!cursor.isNull(idxMovingTime)) { stats.setMovingTime(cursor.getLong(idxMovingTime)); } if (!cursor.isNull(idxMaxlat) && !cursor.isNull(idxMinlat) && !cursor.isNull(idxMaxlon) && !cursor.isNull(idxMinlon)) { int top = cursor.getInt(idxMaxlat); int bottom = cursor.getInt(idxMinlat); int right = cursor.getInt(idxMaxlon); int left = cursor.getInt(idxMinlon); stats.setBounds(left, top, right, bottom); } if (!cursor.isNull(idxMaxSpeed)) { stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed)); } if (!cursor.isNull(idxMinElevation)) { stats.setMinElevation(cursor.getFloat(idxMinElevation)); } if (!cursor.isNull(idxMaxElevation)) { stats.setMaxElevation(cursor.getFloat(idxMaxElevation)); } if (!cursor.isNull(idxElevationGain)) { stats.setTotalElevationGain(cursor.getFloat(idxElevationGain)); } if (!cursor.isNull(idxMinGrade)) { stats.setMinGrade(cursor.getFloat(idxMinGrade)); } if (!cursor.isNull(idxMaxGrade)) { stats.setMaxGrade(cursor.getFloat(idxMaxGrade)); } return track; } @Override public Waypoint createWaypoint(Cursor cursor) { int idxId = cursor.getColumnIndexOrThrow(WaypointsColumns._ID); int idxName = cursor.getColumnIndexOrThrow(WaypointsColumns.NAME); int idxDescription = cursor.getColumnIndexOrThrow(WaypointsColumns.DESCRIPTION); int idxCategory = cursor.getColumnIndexOrThrow(WaypointsColumns.CATEGORY); int idxIcon = cursor.getColumnIndexOrThrow(WaypointsColumns.ICON); int idxTrackId = cursor.getColumnIndexOrThrow(WaypointsColumns.TRACKID); int idxType = cursor.getColumnIndexOrThrow(WaypointsColumns.TYPE); int idxLength = cursor.getColumnIndexOrThrow(WaypointsColumns.LENGTH); int idxDuration = cursor.getColumnIndexOrThrow(WaypointsColumns.DURATION); int idxStartTime = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTTIME); int idxStartId = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTID); int idxStopId = cursor.getColumnIndexOrThrow(WaypointsColumns.STOPID); int idxTotalDistance = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALDISTANCE); int idxTotalTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALTIME); int idxMovingTime = cursor.getColumnIndexOrThrow(WaypointsColumns.MOVINGTIME); int idxMaxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXSPEED); int idxMinElevation = cursor.getColumnIndexOrThrow(WaypointsColumns.MINELEVATION); int idxMaxElevation = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXELEVATION); int idxElevationGain = cursor.getColumnIndexOrThrow(WaypointsColumns.ELEVATIONGAIN); int idxMinGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MINGRADE); int idxMaxGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXGRADE); int idxLatitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LATITUDE); int idxLongitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LONGITUDE); int idxAltitude = cursor.getColumnIndexOrThrow(WaypointsColumns.ALTITUDE); int idxTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TIME); int idxBearing = cursor.getColumnIndexOrThrow(WaypointsColumns.BEARING); int idxAccuracy = cursor.getColumnIndexOrThrow(WaypointsColumns.ACCURACY); int idxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.SPEED); Waypoint waypoint = new Waypoint(); if (!cursor.isNull(idxId)) { waypoint.setId(cursor.getLong(idxId)); } if (!cursor.isNull(idxName)) { waypoint.setName(cursor.getString(idxName)); } if (!cursor.isNull(idxDescription)) { waypoint.setDescription(cursor.getString(idxDescription)); } if (!cursor.isNull(idxCategory)) { waypoint.setCategory(cursor.getString(idxCategory)); } if (!cursor.isNull(idxIcon)) { waypoint.setIcon(cursor.getString(idxIcon)); } if (!cursor.isNull(idxTrackId)) { waypoint.setTrackId(cursor.getLong(idxTrackId)); } if (!cursor.isNull(idxType)) { waypoint.setType(cursor.getInt(idxType)); } if (!cursor.isNull(idxLength)) { waypoint.setLength(cursor.getDouble(idxLength)); } if (!cursor.isNull(idxDuration)) { waypoint.setDuration(cursor.getLong(idxDuration)); } if (!cursor.isNull(idxStartId)) { waypoint.setStartId(cursor.getLong(idxStartId)); } if (!cursor.isNull(idxStopId)) { waypoint.setStopId(cursor.getLong(idxStopId)); } TripStatistics stats = new TripStatistics(); boolean hasStats = false; if (!cursor.isNull(idxStartTime)) { stats.setStartTime(cursor.getLong(idxStartTime)); hasStats = true; } if (!cursor.isNull(idxTotalDistance)) { stats.setTotalDistance(cursor.getFloat(idxTotalDistance)); hasStats = true; } if (!cursor.isNull(idxTotalTime)) { stats.setTotalTime(cursor.getLong(idxTotalTime)); hasStats = true; } if (!cursor.isNull(idxMovingTime)) { stats.setMovingTime(cursor.getLong(idxMovingTime)); hasStats = true; } if (!cursor.isNull(idxMaxSpeed)) { stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed)); hasStats = true; } if (!cursor.isNull(idxMinElevation)) { stats.setMinElevation(cursor.getFloat(idxMinElevation)); hasStats = true; } if (!cursor.isNull(idxMaxElevation)) { stats.setMaxElevation(cursor.getFloat(idxMaxElevation)); hasStats = true; } if (!cursor.isNull(idxElevationGain)) { stats.setTotalElevationGain(cursor.getFloat(idxElevationGain)); hasStats = true; } if (!cursor.isNull(idxMinGrade)) { stats.setMinGrade(cursor.getFloat(idxMinGrade)); hasStats = true; } if (!cursor.isNull(idxMaxGrade)) { stats.setMaxGrade(cursor.getFloat(idxMaxGrade)); hasStats = true; } if (hasStats) { waypoint.setStatistics(stats); } Location location = new Location(""); if (!cursor.isNull(idxLatitude) && !cursor.isNull(idxLongitude)) { location.setLatitude(1. * cursor.getInt(idxLatitude) / 1E6); location.setLongitude(1. * cursor.getInt(idxLongitude) / 1E6); } if (!cursor.isNull(idxAltitude)) { location.setAltitude(cursor.getFloat(idxAltitude)); } if (!cursor.isNull(idxTime)) { location.setTime(cursor.getLong(idxTime)); } if (!cursor.isNull(idxBearing)) { location.setBearing(cursor.getFloat(idxBearing)); } if (!cursor.isNull(idxSpeed)) { location.setSpeed(cursor.getFloat(idxSpeed)); } if (!cursor.isNull(idxAccuracy)) { location.setAccuracy(cursor.getFloat(idxAccuracy)); } waypoint.setLocation(location); return waypoint; } @Override public void deleteAllTracks() { contentResolver.delete(TracksColumns.CONTENT_URI, null, null); contentResolver.delete(TrackPointsColumns.CONTENT_URI, null, null); contentResolver.delete(WaypointsColumns.CONTENT_URI, null, null); } @Override public void deleteTrack(long trackId) { Track track = getTrack(trackId); if (track != null) { contentResolver.delete(TrackPointsColumns.CONTENT_URI, "_id>=" + track.getStartId() + " AND _id<=" + track.getStopId(), null); } contentResolver.delete(WaypointsColumns.CONTENT_URI, WaypointsColumns.TRACKID + "=" + trackId, null); contentResolver.delete( TracksColumns.CONTENT_URI, "_id=" + trackId, null); } @Override public void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator) { final Waypoint deletedWaypoint = getWaypoint(waypointId); if (deletedWaypoint != null && deletedWaypoint.getType() == Waypoint.TYPE_STATISTICS) { final Waypoint nextWaypoint = getNextStatisticsWaypointAfter(deletedWaypoint); if (nextWaypoint != null) { Log.d(TAG, "Correcting marker " + nextWaypoint.getId() + " after deleted marker " + deletedWaypoint.getId()); nextWaypoint.getStatistics().merge(deletedWaypoint.getStatistics()); nextWaypoint.setDescription( descriptionGenerator.generateWaypointDescription(nextWaypoint)); if (!updateWaypoint(nextWaypoint)) { Log.w(TAG, "Update of marker was unsuccessful."); } } else { Log.d(TAG, "No statistics marker after the deleted one was found."); } } contentResolver.delete( WaypointsColumns.CONTENT_URI, "_id=" + waypointId, null); } @Override public Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint) { final String selection = WaypointsColumns._ID + ">" + waypoint.getId() + " AND " + WaypointsColumns.TRACKID + "=" + waypoint.getTrackId() + " AND " + WaypointsColumns.TYPE + "=" + Waypoint.TYPE_STATISTICS; final String sortOrder = WaypointsColumns._ID + " LIMIT 1"; Cursor cursor = null; try { cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, selection, null /*selectionArgs*/, sortOrder); if (cursor != null && cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public boolean updateWaypoint(Waypoint waypoint) { try { final int rows = contentResolver.update( WaypointsColumns.CONTENT_URI, createContentValues(waypoint), "_id=" + waypoint.getId(), null /*selectionArgs*/); return rows == 1; } catch (RuntimeException e) { Log.e(TAG, "Caught unexpected exception.", e); } return false; } /** * Finds a locations from the provider by the given selection. * * @param select a selection argument that identifies a unique location * @return the fist location matching, or null if not found */ private Location findLocationBy(String select) { Cursor cursor = null; try { cursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, null, select, null, null); if (cursor != null && cursor.moveToNext()) { return createLocation(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpeceted exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } /** * Finds a track from the provider by the given selection. * * @param select a selection argument that identifies a unique track * @return the first track matching, or null if not found */ private Track findTrackBy(String select) { Cursor cursor = null; try { cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, select, null, null); if (cursor != null && cursor.moveToNext()) { return createTrack(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public Location getLastLocation() { return findLocationBy("_id=(select max(_id) from trackpoints)"); } @Override public Waypoint getFirstWaypoint(long trackId) { if (trackId < 0) { return null; } Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, "trackid=" + trackId, null /*selectionArgs*/, "_id LIMIT 1"); if (cursor != null) { try { if (cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return null; } @Override public Waypoint getWaypoint(long waypointId) { if (waypointId < 0) { return null; } Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, "_id=" + waypointId, null /*selectionArgs*/, null /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return null; } @Override public long getLastLocationId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, projection, "_id=(select max(_id) from trackpoints WHERE trackid=" + trackId + ")", null /*selectionArgs*/, null /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(TrackPointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public long getFirstWaypointId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, projection, "trackid=" + trackId, null /*selectionArgs*/, "_id LIMIT 1" /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public long getLastWaypointId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, projection, WaypointsColumns.TRACKID + "=" + trackId, null /*selectionArgs*/, "_id DESC LIMIT 1" /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public Track getLastTrack() { Cursor cursor = null; try { cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, "_id=(select max(_id) from tracks)", null, null); if (cursor != null && cursor.moveToNext()) { return createTrack(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public long getLastTrackId() { String[] proj = { TracksColumns._ID }; Cursor cursor = contentResolver.query( TracksColumns.CONTENT_URI, proj, "_id=(select max(_id) from tracks)", null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(TracksColumns._ID)); } } finally { cursor.close(); } } return -1; } @Override public Location getLocation(long id) { if (id < 0) { return null; } String selection = TrackPointsColumns._ID + "=" + id; return findLocationBy(selection); } @Override public Cursor getLocationsCursor(long trackId, long minTrackPointId, int maxLocations, boolean descending) { if (trackId < 0) { return null; } String selection; if (minTrackPointId >= 0) { selection = String.format("%s=%d AND %s%s%d", TrackPointsColumns.TRACKID, trackId, TrackPointsColumns._ID, descending ? "<=" : ">=", minTrackPointId); } else { selection = String.format("%s=%d", TrackPointsColumns.TRACKID, trackId); } String sortOrder = "_id " + (descending ? "DESC" : "ASC"); if (maxLocations > 0) { sortOrder += " LIMIT " + maxLocations; } return contentResolver.query(TrackPointsColumns.CONTENT_URI, null, selection, null, sortOrder); } @Override public Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints) { if (trackId < 0) { return null; } String selection; String[] selectionArgs; if (minWaypointId > 0) { selection = String.format("%s = ? AND %s >= ?", WaypointsColumns.TRACKID, WaypointsColumns._ID); selectionArgs = new String[] { Long.toString(trackId), Long.toString(minWaypointId) }; } else { selection = String.format("%s=?", WaypointsColumns.TRACKID); selectionArgs = new String[] { Long.toString(trackId) }; } return getWaypointsCursor(selection, selectionArgs, null, maxWaypoints); } @Override public Cursor getWaypointsCursor(String selection, String[] selectionArgs, String order, int maxWaypoints) { if (order == null) { order = "_id ASC"; } if (maxWaypoints > 0) { order += " LIMIT " + maxWaypoints; } return contentResolver.query( WaypointsColumns.CONTENT_URI, null, selection, selectionArgs, order); } @Override public Track getTrack(long id) { if (id < 0) { return null; } String select = TracksColumns._ID + "=" + id; return findTrackBy(select); } @Override public List<Track> getAllTracks() { Cursor cursor = getTracksCursor(null, null, TracksColumns._ID); ArrayList<Track> tracks = new ArrayList<Track>(); if (cursor != null) { tracks.ensureCapacity(cursor.getCount()); if (cursor.moveToFirst()) { do { tracks.add(createTrack(cursor)); } while(cursor.moveToNext()); } cursor.close(); } return tracks; } @Override public Cursor getTracksCursor(String selection, String[] selectionArgs, String order) { return contentResolver.query( TracksColumns.CONTENT_URI, null, selection, selectionArgs, order); } @Override public Uri insertTrack(Track track) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrack"); return contentResolver.insert(TracksColumns.CONTENT_URI, createContentValues(track)); } @Override public Uri insertTrackPoint(Location location, long trackId) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrackPoint"); return contentResolver.insert(TrackPointsColumns.CONTENT_URI, createContentValues(location, trackId)); } @Override public int bulkInsertTrackPoints(Location[] locations, int length, long trackId) { if (length == -1) { length = locations.length; } ContentValues[] values = new ContentValues[length]; for (int i = 0; i < length; i++) { values[i] = createContentValues(locations[i], trackId); } return contentResolver.bulkInsert(TrackPointsColumns.CONTENT_URI, values); } @Override public Uri insertWaypoint(Waypoint waypoint) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertWaypoint"); waypoint.setId(-1); return contentResolver.insert(WaypointsColumns.CONTENT_URI, createContentValues(waypoint)); } @Override public boolean trackExists(long id) { if (id < 0) { return false; } Cursor cursor = null; try { final String[] projection = { TracksColumns._ID }; cursor = contentResolver.query( TracksColumns.CONTENT_URI, projection, TracksColumns._ID + "=" + id/*selection*/, null/*selectionArgs*/, null/*sortOrder*/); if (cursor != null && cursor.moveToNext()) { return true; } } finally { if (cursor != null) { cursor.close(); } } return false; } @Override public void updateTrack(Track track) { Log.d(TAG, "MyTracksProviderUtilsImpl.updateTrack"); contentResolver.update(TracksColumns.CONTENT_URI, createContentValues(track), "_id=" + track.getId(), null); } @Override public LocationIterator getLocationIterator(final long trackId, final long startTrackPointId, final boolean descending, final LocationFactory locationFactory) { if (locationFactory == null) { throw new IllegalArgumentException("Expecting non-null locationFactory"); } return new LocationIterator() { private long lastTrackPointId = startTrackPointId; private Cursor cursor = getCursor(startTrackPointId); private final CachedTrackColumnIndices columnIndices = cursor != null ? new CachedTrackColumnIndices(cursor) : null; private Cursor getCursor(long trackPointId) { return getLocationsCursor(trackId, trackPointId, defaultCursorBatchSize, descending); } private boolean advanceCursorToNextBatch() { long pointId = lastTrackPointId + (descending ? -1 : 1); Log.d(TAG, "Advancing cursor point ID: " + pointId); cursor.close(); cursor = getCursor(pointId); return cursor != null; } @Override public long getLocationId() { return lastTrackPointId; } @Override public boolean hasNext() { if (cursor == null) { return false; } if (cursor.isAfterLast()) { return false; } if (cursor.isLast()) { // If the current batch size was less that max, we can safely return, otherwise // we need to advance to the next batch. return cursor.getCount() == defaultCursorBatchSize && advanceCursorToNextBatch() && !cursor.isAfterLast(); } return true; } @Override public Location next() { if (cursor == null || !(cursor.moveToNext() || advanceCursorToNextBatch() || cursor.moveToNext())) { throw new NoSuchElementException(); } lastTrackPointId = cursor.getLong(columnIndices.idxId); Location location = locationFactory.createLocation(); fillLocation(cursor, columnIndices, location); return location; } @Override public void close() { if (cursor != null) { cursor.close(); cursor = null; } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } // @VisibleForTesting void setDefaultCursorBatchSize(int defaultCursorBatchSize) { this.defaultCursorBatchSize = defaultCursorBatchSize; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the tracks provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface TracksColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/tracks"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.track"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.track"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String CATEGORY = "category"; public static final String STARTID = "startid"; public static final String STOPID = "stopid"; public static final String STARTTIME = "starttime"; public static final String STOPTIME = "stoptime"; public static final String NUMPOINTS = "numpoints"; public static final String TOTALDISTANCE = "totaldistance"; public static final String TOTALTIME = "totaltime"; public static final String MOVINGTIME = "movingtime"; public static final String AVGSPEED = "avgspeed"; public static final String AVGMOVINGSPEED = "avgmovingspeed"; public static final String MAXSPEED = "maxspeed"; public static final String MINELEVATION = "minelevation"; public static final String MAXELEVATION = "maxelevation"; public static final String ELEVATIONGAIN = "elevationgain"; public static final String MINGRADE = "mingrade"; public static final String MAXGRADE = "maxgrade"; public static final String MINLAT = "minlat"; public static final String MAXLAT = "maxlat"; public static final String MINLON = "minlon"; public static final String MAXLON = "maxlon"; public static final String MAPID = "mapid"; public static final String TABLEID = "tableid"; }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.content; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.location.Location; import android.net.Uri; import java.util.Iterator; import java.util.List; /** * Utility to access data from the mytracks content provider. * * @author Rodrigo Damazio */ public interface MyTracksProviderUtils { /** * Authority (first part of URI) for the MyTracks content provider: */ public static final String AUTHORITY = "com.google.android.maps.mytracks"; /** * Deletes all tracks (including track points) from the provider. */ void deleteAllTracks(); /** * Deletes a track with the given track id. * * @param trackId the unique track id */ void deleteTrack(long trackId); /** * Deletes a way point with the given way point id. * This will also correct the next statistics way point after the deleted one * to reflect the deletion. * The generator is needed to stitch together statistics waypoints. * * @param waypointId the unique way point id * @param descriptionGenerator the class to generate descriptions */ void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator); /** * Finds the next statistics waypoint after the given waypoint. * * @param waypoint a given waypoint * @return the next statistics waypoint, or null if none found. */ Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint); /** * Updates the waypoint in the provider. * * @param waypoint * @return true if successful */ boolean updateWaypoint(Waypoint waypoint); /** * Finds the last recorded location from the location provider. * * @return the last location, or null if no locations available */ Location getLastLocation(); /** * Finds the first recorded waypoint for a given track from the location * provider. * This is a special waypoint that holds the stats for current segment. * * @param trackId the id of the track the waypoint belongs to * @return the first waypoint, or null if no waypoints available */ Waypoint getFirstWaypoint(long trackId); /** * Finds the given waypoint from the location provider. * * @param waypointId * @return the waypoint, or null if it does not exist */ Waypoint getWaypoint(long waypointId); /** * Finds the last recorded location id from the track points provider. * * @param trackId find last location on this track * @return the location id, or -1 if no locations available */ long getLastLocationId(long trackId); /** * Finds the id of the 1st waypoint for a given track. * The 1st waypoint is special as it contains the stats for the current * segment. * * @param trackId find last location on this track * @return the waypoint id, or -1 if no waypoints are available */ long getFirstWaypointId(long trackId); /** * Finds the id of the 1st waypoint for a given track. * The 1st waypoint is special as it contains the stats for the current * segment. * * @param trackId find last location on this track * @return the waypoint id, or -1 if no waypoints are available */ long getLastWaypointId(long trackId); /** * Finds the last recorded track from the track provider. * * @return the last track, or null if no tracks available */ Track getLastTrack(); /** * Finds the last recorded track id from the tracks provider. * * @return the track id, or -1 if no tracks available */ long getLastTrackId(); /** * Finds a location by given unique id. * * @param id the desired id * @return a Location object, or null if not found */ Location getLocation(long id); /** * Creates a cursor over the locations in the track points provider which * iterates over a given range of unique ids. * Caller owns the returned cursor and is responsible for closing it. * * @param trackId the id of the track for which to get the points * @param minTrackPointId the minimum id for the track points * @param maxLocations maximum number of locations retrieved * @param descending if true the results will be returned in descending id * order (latest location first) * @return A cursor over the selected range of locations */ Cursor getLocationsCursor(long trackId, long minTrackPointId, int maxLocations, boolean descending); /** * Creates a cursor over the waypoints of a track. * Caller owns the returned cursor and is responsible for closing it. * * @param trackId the id of the track for which to get the points * @param minWaypointId the minimum id for the track points * @param maxWaypoints the maximum number of waypoints to return * @return A cursor over the selected range of locations */ Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints); /** * Creates a cursor over waypoints with the given selection. * Caller owns the returned cursor and is responsible for closing it. * * @param selection a given selection * @param selectionArgs arguments for the given selection * @param order the order in which to return results * @param maxWaypoints the maximum number of waypoints to return * @return a cursor of the selected waypoints */ Cursor getWaypointsCursor(String selection, String[] selectionArgs, String order, int maxWaypoints); /** * Finds a track by given unique track id. * Note that the returned track object does not have any track points attached. * Use {@link #getLocationIterator(long, long, boolean, LocationFactory)} to load * the track points. * * @param id desired unique track id * @return a Track object, or null if not found */ Track getTrack(long id); /** * Retrieves all tracks without track points. If no tracks exist, an empty * list will be returned. Use {@link #getLocationIterator(long, long, boolean, LocationFactory)} * to load the track points. * * @return a list of all the recorded tracks */ List<Track> getAllTracks(); /** * Creates a cursor over the tracks provider with a given selection. * Caller owns the returned cursor and is responsible for closing it. * * @param selection a given selection * @param selectionArgs parameters for the given selection * @param order the order to return results in * @return a cursor of the selected tracks */ Cursor getTracksCursor(String selection, String[] selectionArgs, String order); /** * Inserts a track in the tracks provider. * Note: This does not insert any track points. * Use {@link #insertTrackPoint(Location, long)} to insert them. * * @param track the track to insert * @return the content provider URI for the inserted track */ Uri insertTrack(Track track); /** * Inserts a track point in the tracks provider. * * @param location the location to insert * @return the content provider URI for the inserted track point */ Uri insertTrackPoint(Location location, long trackId); /** * Inserts multiple track points in a single operation. * * @param locations an array of locations to insert * @param length the number of locations (from the beginning of the array) * to actually insert, or -1 for all of them * @param trackId the ID of the track to insert the points into * @return the number of points inserted */ int bulkInsertTrackPoints(Location[] locations, int length, long trackId); /** * Inserts a waypoint in the provider. * * @param waypoint the waypoint to insert * @return the content provider URI for the inserted track */ Uri insertWaypoint(Waypoint waypoint); /** * Tests if a track with given id exists. * * @param id the unique id * @return true if track exists */ boolean trackExists(long id); /** * Updates a track in the content provider. * Note: This will not update any track points. * * @param track a given track */ void updateTrack(Track track); /** * Creates a Track object from a given cursor. * * @param cursor a cursor pointing at a db or provider with tracks * @return a new Track object */ Track createTrack(Cursor cursor); /** * Creates the ContentValues for a given Track object. * * Note: If the track has an id<0 the id column will not be filled. * * @param track a given track object * @return a filled in ContentValues object */ ContentValues createContentValues(Track track); /** * Creates a location object from a given cursor. * * @param cursor a cursor pointing at a db or provider with locations * @return a new location object */ Location createLocation(Cursor cursor); /** * Fill a location object with values from a given cursor. * * @param cursor a cursor pointing at a db or provider with locations * @param location a location object to be overwritten */ void fillLocation(Cursor cursor, Location location); /** * Creates a waypoint object from a given cursor. * * @param cursor a cursor pointing at a db or provider with waypoints. * @return a new waypoint object */ Waypoint createWaypoint(Cursor cursor); /** * A lightweight wrapper around the original {@link Cursor} with a method to clean up. */ interface LocationIterator extends Iterator<Location> { /** * Returns ID of the most recently retrieved track point through a call to {@link #next()}. * * @return the ID of the most recent track point ID. */ long getLocationId(); /** * Should be called in case the underlying iterator hasn't reached the last record. * Calling it if it has reached the last record is a no-op. */ void close(); } /** * A factory for creating new {@class Location}s. */ interface LocationFactory { /** * Creates a new {@link Location} object to be populated from the underlying database record. * It's up to the implementing class to decide whether to create a new instance or reuse * existing to optimize for speed. * * @return a {@link Location} to be populated from the database. */ Location createLocation(); } /** * The default {@class Location}s factory, which creates a new location of 'gps' type. */ LocationFactory DEFAULT_LOCATION_FACTORY = new LocationFactory() { @Override public Location createLocation() { return new Location("gps"); } }; /** * A location factory which uses two location instances (one for the current location, * and one for the previous), useful when we need to keep the last location. */ public class DoubleBufferedLocationFactory implements LocationFactory { private final Location locs[] = new MyTracksLocation[] { new MyTracksLocation("gps"), new MyTracksLocation("gps") }; private int lastLoc = 0; @Override public Location createLocation() { lastLoc = (lastLoc + 1) % locs.length; return locs[lastLoc]; } } /** * Creates a new read-only iterator over all track points for the given track. It provides * a lightweight way of iterating over long tracks without failing due to the underlying cursor * limitations. Since it's a read-only iterator, {@link Iterator#remove()} always throws * {@class UnsupportedOperationException}. * * Each call to {@link LocationIterator#next()} may advance to the next DB record, and if so, * the iterator calls {@link LocationFactory#createLocation()} and populates it with information * retrieved from the record. * * When done with iteration, you must call {@link LocationIterator#close()} to make sure that all * resources are properly deallocated. * * Example use: * <code> * ... * LocationIterator it = providerUtils.getLocationIterator( * 1, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); * try { * for (Location loc : it) { * ... // Do something useful with the location. * } * } finally { * it.close(); * } * ... * </code> * * @param trackId the ID of a track to retrieve locations for. * @param startTrackPointId the ID of the first track point to load, or -1 to start from * the first point. * @param descending if true the results will be returned in descending ID * order (latest location first). * @param locationFactory the factory for creating new locations. * * @return the read-only iterator over the given track's points. */ LocationIterator getLocationIterator(long trackId, long startTrackPointId, boolean descending, LocationFactory locationFactory); /** * A factory which can produce instances of {@link MyTracksProviderUtils}, * and can be overridden in tests (a.k.a. poor man's guice). */ public static class Factory { private static Factory instance = new Factory(); /** * Creates and returns an instance of {@link MyTracksProviderUtils} which * uses the given context to access its data. */ public static MyTracksProviderUtils get(Context context) { return instance.newForContext(context); } /** * Returns the global instance of this factory. */ public static Factory getInstance() { return instance; } /** * Overrides the global instance for this factory, to be used for testing. * If used, don't forget to set it back to the original value after the * test is run. */ public static void overrideInstance(Factory factory) { instance = factory; } /** * Creates an instance of {@link MyTracksProviderUtils}. */ protected MyTracksProviderUtils newForContext(Context context) { return new MyTracksProviderUtilsImpl(context.getContentResolver()); } } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.content; import java.util.Vector; /** * An interface for an object that can generate descriptions of track and * waypoint. * * @author Sandor Dornbush */ public interface DescriptionGenerator { /** * Generates a track description. * * @param track the track * @param distances a vector of distances to generate the elevation chart * @param elevations a vector of elevations to generate the elevation chart */ public String generateTrackDescription( Track track, Vector<Double> distances, Vector<Double> elevations); /** * Generate a waypoint description. * * @param waypoint the waypoint */ public String generateWaypointDescription(Waypoint waypoint); }
Java
/* * Copyright 2009 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 com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.stats.TripStatistics; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; /** * A way point. It has a location, meta data such as name, description, * category, and icon, plus it can store track statistics for a "sub-track". * * TODO: hashCode and equals * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public final class Waypoint implements Parcelable { /** * Creator for a Waypoint object */ public static class Creator implements Parcelable.Creator<Waypoint> { public Waypoint createFromParcel(Parcel source) { ClassLoader classLoader = getClass().getClassLoader(); Waypoint waypoint = new Waypoint(); waypoint.id = source.readLong(); waypoint.name = source.readString(); waypoint.description = source.readString(); waypoint.category = source.readString(); waypoint.icon = source.readString(); waypoint.trackId = source.readLong(); waypoint.type = source.readInt(); waypoint.startId = source.readLong(); waypoint.stopId = source.readLong(); byte hasStats = source.readByte(); if (hasStats > 0) { waypoint.stats = source.readParcelable(classLoader); } byte hasLocation = source.readByte(); if (hasLocation > 0) { waypoint.location = source.readParcelable(classLoader); } return waypoint; } public Waypoint[] newArray(int size) { return new Waypoint[size]; } } public static final Creator CREATOR = new Creator(); public static final int TYPE_WAYPOINT = 0; public static final int TYPE_STATISTICS = 1; private long id = -1; private String name = ""; private String description = ""; private String category = ""; private String icon = ""; private long trackId = -1; private int type = 0; private Location location; /** Start track point id */ private long startId = -1; /** Stop track point id */ private long stopId = -1; private TripStatistics stats; /** The length of the track, without smoothing. */ private double length; /** The total duration of the track (not from the last waypoint) */ private long duration; public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeString(name); dest.writeString(description); dest.writeString(category); dest.writeString(icon); dest.writeLong(trackId); dest.writeInt(type); dest.writeLong(startId); dest.writeLong(stopId); dest.writeByte(stats == null ? (byte) 0 : (byte) 1); if (stats != null) { dest.writeParcelable(stats, 0); } dest.writeByte(location == null ? (byte) 0 : (byte) 1); if (location != null) { dest.writeParcelable(location, 0); } } // Getters and setters: //--------------------- public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Location getLocation() { return location; } public void setTrackId(long trackId) { this.trackId = trackId; } public int describeContents() { return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getTrackId() { return trackId; } public int getType() { return type; } public void setType(int type) { this.type = type; } public long getStartId() { return startId; } public void setStartId(long startId) { this.startId = startId; } public long getStopId() { return stopId; } public void setStopId(long stopId) { this.stopId = stopId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public void setLocation(Location location) { this.location = location; } public TripStatistics getStatistics() { return stats; } public void setStatistics(TripStatistics stats) { this.stats = stats; } // WARNING: These fields are used for internal state keeping. You probably // want to look at getStatistics instead. public double getLength() { return length; } public void setLength(double length) { this.length = length; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } }
Java
/* * Copyright 2009 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 com.google.android.apps.mytracks.stats; /** * A helper class that tracks a minimum and a maximum of a variable. * * @author Sandor Dornbush */ public class ExtremityMonitor { /** * The smallest value seen so far. */ private double min; /** * The largest value seen so far. */ private double max; public ExtremityMonitor() { reset(); } /** * Updates the min and the max with the new value. * * @param value the new value for the monitor * @return true if an extremity was found */ public boolean update(double value) { boolean changed = false; if (value < min) { min = value; changed = true; } if (value > max) { max = value; changed = true; } return changed; } /** * Gets the minimum value seen. * * @return The minimum value passed into the update() function */ public double getMin() { return min; } /** * Gets the maximum value seen. * * @return The maximum value passed into the update() function */ public double getMax() { return max; } /** * Resets this object to it's initial state where the min and max are unknown. */ public void reset() { min = Double.POSITIVE_INFINITY; max = Double.NEGATIVE_INFINITY; } /** * Sets the minimum and maximum values. */ public void set(double min, double max) { this.min = min; this.max = max; } /** * Sets the minimum value. */ public void setMin(double min) { this.min = min; } /** * Sets the maximum value. */ public void setMax(double max) { this.max = max; } public boolean hasData() { return min != Double.POSITIVE_INFINITY && max != Double.NEGATIVE_INFINITY; } @Override public String toString() { return "Min: " + min + " Max: " + max; } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.stats; import android.os.Parcel; import android.os.Parcelable; /** * Statistical data about a trip. * The data in this class should be filled out by TripStatisticsBuilder. * * TODO: hashCode and equals * * @author Rodrigo Damazio */ public class TripStatistics implements Parcelable { /** * The start time for the trip. This is system time which might not match gps * time. */ private long startTime = -1L; /** * The stop time for the trip. This is the system time which might not match * gps time. */ private long stopTime = -1L; /** * The total time that we believe the user was traveling in milliseconds. */ private long movingTime; /** * The total time of the trip in milliseconds. * This is only updated when new points are received, so it may be stale. */ private long totalTime; /** * The total distance in meters that the user traveled on this trip. */ private double totalDistance; /** * The total elevation gained on this trip in meters. */ private double totalElevationGain; /** * The maximum speed in meters/second reported that we believe to be a valid * speed. */ private double maxSpeed; /** * The min and max latitude values seen in this trip. */ private final ExtremityMonitor latitudeExtremities = new ExtremityMonitor(); /** * The min and max longitude values seen in this trip. */ private final ExtremityMonitor longitudeExtremities = new ExtremityMonitor(); /** * The min and max elevation seen on this trip in meters. */ private final ExtremityMonitor elevationExtremities = new ExtremityMonitor(); /** * The minimum and maximum grade calculations on this trip. */ private final ExtremityMonitor gradeExtremities = new ExtremityMonitor(); /** * Default constructor. */ public TripStatistics() { } /** * Copy constructor. * * @param other another statistics data object to copy from */ public TripStatistics(TripStatistics other) { this.maxSpeed = other.maxSpeed; this.movingTime = other.movingTime; this.startTime = other.startTime; this.stopTime = other.stopTime; this.totalDistance = other.totalDistance; this.totalElevationGain = other.totalElevationGain; this.totalTime = other.totalTime; this.latitudeExtremities.set(other.latitudeExtremities.getMin(), other.latitudeExtremities.getMax()); this.longitudeExtremities.set(other.longitudeExtremities.getMin(), other.longitudeExtremities.getMax()); this.elevationExtremities.set(other.elevationExtremities.getMin(), other.elevationExtremities.getMax()); this.gradeExtremities.set(other.gradeExtremities.getMin(), other.gradeExtremities.getMax()); } /** * Combines these statistics with those from another object. * This assumes that the time periods covered by each do not intersect. * * @param other the other waypoint */ public void merge(TripStatistics other) { startTime = Math.min(startTime, other.startTime); stopTime = Math.max(stopTime, other.stopTime); totalTime += other.totalTime; movingTime += other.movingTime; totalDistance += other.totalDistance; totalElevationGain += other.totalElevationGain; maxSpeed = Math.max(maxSpeed, other.maxSpeed); latitudeExtremities.update(other.latitudeExtremities.getMax()); latitudeExtremities.update(other.latitudeExtremities.getMin()); longitudeExtremities.update(other.longitudeExtremities.getMax()); longitudeExtremities.update(other.longitudeExtremities.getMin()); elevationExtremities.update(other.elevationExtremities.getMax()); elevationExtremities.update(other.elevationExtremities.getMin()); gradeExtremities.update(other.gradeExtremities.getMax()); gradeExtremities.update(other.gradeExtremities.getMin()); } /** * Gets the time that this track started. * * @return The number of milliseconds since epoch to the time when this track * started */ public long getStartTime() { return startTime; } /** * Gets the time that this track stopped. * * @return The number of milliseconds since epoch to the time when this track * stopped */ public long getStopTime() { return stopTime; } /** * Gets the total time that this track has been active. * This statistic is only updated when a new point is added to the statistics, * so it may be off. If you need to calculate the proper total time, use * {@link #getStartTime} with the current time. * * @return The total number of milliseconds the track was active */ public long getTotalTime() { return totalTime; } /** * Gets the total distance the user traveled. * * @return The total distance traveled in meters */ public double getTotalDistance() { return totalDistance; } /** * Gets the the average speed the user traveled. * This calculation only takes into account the displacement until the last * point that was accounted for in statistics. * * @return The average speed in m/s */ public double getAverageSpeed() { if (totalTime == 0L) { return 0.0; } return totalDistance / ((double) totalTime / 1000.0); } /** * Gets the the average speed the user traveled when they were actively * moving. * * @return The average moving speed in m/s */ public double getAverageMovingSpeed() { if (movingTime == 0L) { return 0.0; } return totalDistance / ((double) movingTime / 1000.0); } /** * Gets the the maximum speed for this track. * * @return The maximum speed in m/s */ public double getMaxSpeed() { return maxSpeed; } /** * Gets the moving time. * * @return The total number of milliseconds the user was moving */ public long getMovingTime() { return movingTime; } /** * Gets the total elevation gain for this trip. This is calculated as the sum * of all positive differences in the smoothed elevation. * * @return The elevation gain in meters for this trip */ public double getTotalElevationGain() { return totalElevationGain; } /** * Returns the leftmost position (lowest longitude) of the track, in signed degrees. */ public double getLeftDegrees() { return longitudeExtremities.getMin(); } /** * Returns the leftmost position (lowest longitude) of the track, in signed millions of degrees. */ public int getLeft() { return (int) (longitudeExtremities.getMin() * 1E6); } /** * Returns the rightmost position (highest longitude) of the track, in signed degrees. */ public double getRightDegrees() { return longitudeExtremities.getMax(); } /** * Returns the rightmost position (highest longitude) of the track, in signed millions of degrees. */ public int getRight() { return (int) (longitudeExtremities.getMax() * 1E6); } /** * Returns the bottommost position (lowest latitude) of the track, in signed degrees. */ public double getBottomDegrees() { return latitudeExtremities.getMin(); } /** * Returns the bottommost position (lowest latitude) of the track, in signed millions of degrees. */ public int getBottom() { return (int) (latitudeExtremities.getMin() * 1E6); } /** * Returns the topmost position (highest latitude) of the track, in signed degrees. */ public double getTopDegrees() { return latitudeExtremities.getMax(); } /** * Returns the topmost position (highest latitude) of the track, in signed millions of degrees. */ public int getTop() { return (int) (latitudeExtremities.getMax() * 1E6); } /** * Returns the mean position (center latitude) of the track, in signed degrees. */ public double getMeanLatitude() { return (getBottomDegrees() + getTopDegrees()) / 2.0; } /** * Returns the mean position (center longitude) of the track, in signed degrees. */ public double getMeanLongitude() { return (getLeftDegrees() + getRightDegrees()) / 2.0; } /** * Gets the minimum elevation seen on this trip. This is calculated from the * smoothed elevation so this can actually be more than the current elevation. * * @return The smallest elevation reading for this trip in meters */ public double getMinElevation() { return elevationExtremities.getMin(); } /** * Gets the maximum elevation seen on this trip. This is calculated from the * smoothed elevation so this can actually be less than the current elevation. * * @return The largest elevation reading for this trip in meters */ public double getMaxElevation() { return elevationExtremities.getMax(); } /** * Gets the maximum grade for this trip. * * @return The maximum grade for this trip as a fraction */ public double getMaxGrade() { return gradeExtremities.getMax(); } /** * Gets the minimum grade for this trip. * * @return The minimum grade for this trip as a fraction */ public double getMinGrade() { return gradeExtremities.getMin(); } // Setters - to be used when restoring state or loading from the DB /** * Sets the start time for this trip. * * @param startTime the start time, in milliseconds since the epoch */ public void setStartTime(long startTime) { this.startTime = startTime; } /** * Sets the stop time for this trip. * * @param stopTime the stop time, in milliseconds since the epoch */ public void setStopTime(long stopTime) { this.stopTime = stopTime; } /** * Sets the total moving time. * * @param movingTime the moving time in milliseconds */ public void setMovingTime(long movingTime) { this.movingTime = movingTime; } /** * Sets the total trip time. * * @param totalTime the total trip time in milliseconds */ public void setTotalTime(long totalTime) { this.totalTime = totalTime; } /** * Sets the total trip distance. * * @param totalDistance the trip distance in meters */ public void setTotalDistance(double totalDistance) { this.totalDistance = totalDistance; } /** * Sets the total elevation variation during the trip. * * @param totalElevationGain the elevation variation in meters */ public void setTotalElevationGain(double totalElevationGain) { this.totalElevationGain = totalElevationGain; } /** * Sets the maximum speed reached during the trip. * * @param maxSpeed the maximum speed in meters per second */ public void setMaxSpeed(double maxSpeed) { this.maxSpeed = maxSpeed; } /** * Sets the minimum elevation reached during the trip. * * @param elevation the minimum elevation in meters */ public void setMinElevation(double elevation) { elevationExtremities.setMin(elevation); } /** * Sets the maximum elevation reached during the trip. * * @param elevation the maximum elevation in meters */ public void setMaxElevation(double elevation) { elevationExtremities.setMax(elevation); } /** * Sets the minimum grade obtained during the trip. * * @param grade the grade as a fraction (-1.0 would mean vertical downwards) */ public void setMinGrade(double grade) { gradeExtremities.setMin(grade); } /** * Sets the maximum grade obtained during the trip). * * @param grade the grade as a fraction (1.0 would mean vertical upwards) */ public void setMaxGrade(double grade) { gradeExtremities.setMax(grade); } /** * Sets the bounding box for this trip. * The unit for all parameters is signed decimal degrees (degrees * 1E6). * * @param leftE6 the westmost longitude reached * @param topE6 the northmost latitude reached * @param rightE6 the eastmost longitude reached * @param bottomE6 the southmost latitude reached */ public void setBounds(int leftE6, int topE6, int rightE6, int bottomE6) { latitudeExtremities.set(bottomE6 / 1E6, topE6 / 1E6); longitudeExtremities.set(leftE6 / 1E6, rightE6 / 1E6); } // Data manipulation methods /** * Adds to the current total distance. * * @param distance the distance to add in meters */ void addTotalDistance(double distance) { totalDistance += distance; } /** * Adds to the total elevation variation. * * @param gain the elevation variation in meters */ void addTotalElevationGain(double gain) { totalElevationGain += gain; } /** * Adds to the total moving time of the trip. * * @param time the time in milliseconds */ void addMovingTime(long time) { movingTime += time; } /** * Accounts for a new latitude value for the bounding box. * * @param latitude the latitude value in signed decimal degrees */ void updateLatitudeExtremities(double latitude) { latitudeExtremities.update(latitude); } /** * Accounts for a new longitude value for the bounding box. * * @param longitude the longitude value in signed decimal degrees */ void updateLongitudeExtremities(double longitude) { longitudeExtremities.update(longitude); } /** * Accounts for a new elevation value for the bounding box. * * @param elevation the elevation value in meters */ void updateElevationExtremities(double elevation) { elevationExtremities.update(elevation); } /** * Accounts for a new grade value. * * @param grade the grade value as a fraction */ void updateGradeExtremities(double grade) { gradeExtremities.update(grade); } // String conversion @Override public String toString() { return "TripStatistics { Start Time: " + getStartTime() + "; Total Time: " + getTotalTime() + "; Moving Time: " + getMovingTime() + "; Total Distance: " + getTotalDistance() + "; Elevation Gain: " + getTotalElevationGain() + "; Min Elevation: " + getMinElevation() + "; Max Elevation: " + getMaxElevation() + "; Average Speed: " + getAverageMovingSpeed() + "; Min Grade: " + getMinGrade() + "; Max Grade: " + getMaxGrade() + "}"; } // Parcelable interface and creator /** * Creator of statistics data from parcels. */ public static class Creator implements Parcelable.Creator<TripStatistics> { @Override public TripStatistics createFromParcel(Parcel source) { TripStatistics data = new TripStatistics(); data.startTime = source.readLong(); data.movingTime = source.readLong(); data.totalTime = source.readLong(); data.totalDistance = source.readDouble(); data.totalElevationGain = source.readDouble(); data.maxSpeed = source.readDouble(); double minLat = source.readDouble(); double maxLat = source.readDouble(); data.latitudeExtremities.set(minLat, maxLat); double minLong = source.readDouble(); double maxLong = source.readDouble(); data.longitudeExtremities.set(minLong, maxLong); double minElev = source.readDouble(); double maxElev = source.readDouble(); data.elevationExtremities.set(minElev, maxElev); double minGrade = source.readDouble(); double maxGrade = source.readDouble(); data.gradeExtremities.set(minGrade, maxGrade); return data; } @Override public TripStatistics[] newArray(int size) { return new TripStatistics[size]; } } /** * Creator of {@link TripStatistics} from parcels. */ public static final Creator CREATOR = new Creator(); @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(startTime); dest.writeLong(movingTime); dest.writeLong(totalTime); dest.writeDouble(totalDistance); dest.writeDouble(totalElevationGain); dest.writeDouble(maxSpeed); dest.writeDouble(latitudeExtremities.getMin()); dest.writeDouble(latitudeExtremities.getMax()); dest.writeDouble(longitudeExtremities.getMin()); dest.writeDouble(longitudeExtremities.getMax()); dest.writeDouble(elevationExtremities.getMin()); dest.writeDouble(elevationExtremities.getMax()); dest.writeDouble(gradeExtremities.getMin()); dest.writeDouble(gradeExtremities.getMax()); } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.lib; /** * Constants for the My Tracks common library. * These constants should ideally not be used by third-party applications. * * @author Rodrigo Damazio */ public class MyTracksLibConstants { public static final String TAG = "MyTracksLib"; private MyTracksLibConstants() {} }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.Context; import android.telephony.PhoneStateListener; import android.telephony.SignalStrength; import android.telephony.TelephonyManager; import android.util.Log; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerEclair extends SignalStrengthListenerCupcake { private SignalStrength signalStrength = null; public SignalStrengthListenerEclair(Context ctx, SignalStrengthCallback callback) { super(ctx, callback); } @Override protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTHS; } @SuppressWarnings("hiding") @Override public void onSignalStrengthsChanged(SignalStrength signalStrength) { Log.d(TAG, "Signal Strength Modern: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ @Override protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: return "1xRTT"; case TelephonyManager.NETWORK_TYPE_CDMA: return "CDMA"; case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_EVDO_0: return "EVDO 0"; case TelephonyManager.NETWORK_TYPE_EVDO_A: return "EVDO A"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_HSDPA: return "HSDPA"; case TelephonyManager.NETWORK_TYPE_HSPA: return "HSPA"; case TelephonyManager.NETWORK_TYPE_HSUPA: return "HSUPA"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ @Override protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public String getStrengthAsString() { if (signalStrength == null) { return "Strength: " + getContext().getString(R.string.unknown) + "\n"; } StringBuffer sb = new StringBuffer(); if (signalStrength.isGsm()) { appendSignal(signalStrength.getGsmSignalStrength(), R.string.gsm_strength, sb); maybeAppendSignal(signalStrength.getGsmBitErrorRate(), R.string.error_rate, sb); } else { appendSignal(signalStrength.getCdmaDbm(), R.string.cdma_strength, sb); appendSignal(signalStrength.getCdmaEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoDbm(), R.string.evdo_strength, sb); appendSignal(signalStrength.getEvdoEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoSnr(), R.string.signal_to_noise_ratio, sb); } return sb.toString(); } private void maybeAppendSignal( int signal, int signalFormat, StringBuffer sb) { if (signal > 0) { sb.append(getContext().getString(signalFormat, signal)); } } private void appendSignal(int signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } private void appendSignal(double signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.signalstrength; import android.os.Build; /** * Constants for the signal sampler. * * @author Rodrigo Damazio */ public class SignalStrengthConstants { public static final String START_SAMPLING = "com.google.android.apps.mytracks.signalstrength.START"; public static final String STOP_SAMPLING = "com.google.android.apps.mytracks.signalstrength.STOP"; public static final int ANDROID_API_LEVEL = Integer.parseInt( Build.VERSION.SDK); public static final String TAG = "SignalStrengthSampler"; private SignalStrengthConstants() {} }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.START_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.STOP_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.IBinder; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import java.util.List; /** * Serivce which actually reads signal strength and sends it to My Tracks. * * @author Rodrigo Damazio */ public class SignalStrengthService extends Service implements ServiceConnection, SignalStrengthCallback, OnSharedPreferenceChangeListener { private ComponentName mytracksServiceComponent; private SharedPreferences preferences; private SignalStrengthListenerFactory signalListenerFactory; private SignalStrengthListener signalListener; private ITrackRecordingService mytracksService; private long lastSamplingTime; private long samplingPeriod; @Override public void onCreate() { super.onCreate(); mytracksServiceComponent = new ComponentName( getString(R.string.mytracks_service_package), getString(R.string.mytracks_service_class)); preferences = PreferenceManager.getDefaultSharedPreferences(this); signalListenerFactory = new SignalStrengthListenerFactory(); } @Override public void onStart(Intent intent, int startId) { handleCommand(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleCommand(intent); return START_STICKY; } private void handleCommand(Intent intent) { String action = intent.getAction(); if (START_SAMPLING.equals(action)) { startSampling(); } else { stopSampling(); } } private void startSampling() { // TODO: Start foreground if (!isMytracksRunning()) { Log.w(TAG, "My Tracks not running!"); return; } Log.d(TAG, "Starting sampling"); Intent intent = new Intent(); intent.setComponent(mytracksServiceComponent); if (!bindService(intent, SignalStrengthService.this, 0)) { Log.e(TAG, "Couldn't bind to service."); return; } } private boolean isMytracksRunning() { ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo serviceInfo : services) { if (serviceInfo.pid != 0 && serviceInfo.service.equals(mytracksServiceComponent)) { return true; } } return false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { synchronized (this) { mytracksService = ITrackRecordingService.Stub.asInterface(service); Log.d(TAG, "Bound to My Tracks"); boolean recording = false; try { recording = mytracksService.isRecording(); } catch (RemoteException e) { Log.e(TAG, "Failed to talk to my tracks", e); } if (!recording) { Log.w(TAG, "My Tracks is not recording, bailing"); stopSampling(); return; } // We're ready to send waypoints, so register for signal sampling signalListener = signalListenerFactory.create(this, this); signalListener.register(); // Register for preference changes samplingPeriod = Long.parseLong(preferences.getString( getString(R.string.settings_min_signal_sampling_period_key), "-1")); preferences.registerOnSharedPreferenceChangeListener(this); // Tell the user we've started. Toast.makeText(this, R.string.started_sampling, Toast.LENGTH_SHORT).show(); } } @Override public void onSignalStrengthSampled(String description, String icon) { long now = System.currentTimeMillis(); if (now - lastSamplingTime < samplingPeriod * 60 * 1000) { return; } try { long waypointId; synchronized (this) { if (mytracksService == null) { Log.d(TAG, "No my tracks service to send to"); return; } // Create a waypoint. WaypointCreationRequest request = new WaypointCreationRequest(WaypointCreationRequest.WaypointType.MARKER, "Signal Strength", description, icon); waypointId = mytracksService.insertWaypoint(request); } if (waypointId >= 0) { Log.d(TAG, "Added signal marker"); lastSamplingTime = now; } else { Log.e(TAG, "Cannot insert waypoint marker?"); } } catch (RemoteException e) { Log.e(TAG, "Cannot talk to my tracks service", e); } } private void stopSampling() { Log.d(TAG, "Stopping sampling"); synchronized (this) { // Unregister from preference change updates preferences.unregisterOnSharedPreferenceChangeListener(this); // Unregister from receiving signal updates if (signalListener != null) { signalListener.unregister(); signalListener = null; } // Unbind from My Tracks if (mytracksService != null) { unbindService(this); mytracksService = null; } // Reset the last sampling time lastSamplingTime = 0; // Tell the user we've stopped Toast.makeText(this, R.string.stopped_sampling, Toast.LENGTH_SHORT).show(); // Stop stopSelf(); } } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "Disconnected from My Tracks"); synchronized (this) { mytracksService = null; } } @Override public void onDestroy() { stopSampling(); super.onDestroy(); } @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { if (getString(R.string.settings_min_signal_sampling_period_key).equals(key)) { samplingPeriod = Long.parseLong(sharedPreferences.getString(key, "-1")); } } @Override public IBinder onBind(Intent intent) { return null; } public static void startService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(START_SAMPLING); context.startService(intent); } public static void stopService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(STOP_SAMPLING); context.startService(intent); } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; /** * Broadcast listener which gets notified when we start or stop recording a track. * * @author Rodrigo Damazio */ public class RecordingStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context ctx, Intent intent) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx); String action = intent.getAction(); if (ctx.getString(R.string.track_started_broadcast_action).equals(action)) { boolean autoStart = preferences.getBoolean( ctx.getString(R.string.settings_auto_start_key), false); if (!autoStart) { Log.d(TAG, "Not auto-starting signal sampling"); return; } startService(ctx); } else if (ctx.getString(R.string.track_stopped_broadcast_action).equals(action)) { boolean autoStop = preferences.getBoolean( ctx.getString(R.string.settings_auto_stop_key), true); if (!autoStop) { Log.d(TAG, "Not auto-stopping signal sampling"); return; } stopService(ctx); } else { Log.e(TAG, "Unknown action received: " + action); } } // @VisibleForTesting protected void stopService(Context ctx) { SignalStrengthService.stopService(ctx); } // @VisibleForTesting protected void startService(Context ctx) { SignalStrengthService.startService(ctx); } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import java.util.List; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerCupcake extends PhoneStateListener implements SignalStrengthListener { private static final Uri APN_URI = Uri.parse("content://telephony/carriers"); private final Context context; private final SignalStrengthCallback callback; private TelephonyManager manager; private int signalStrength = -1; public SignalStrengthListenerCupcake(Context context, SignalStrengthCallback callback) { this.context = context; this.callback = callback; } @Override public void register() { manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (manager == null) { Log.e(TAG, "Cannot get telephony manager."); } else { manager.listen(this, getListenEvents()); } } protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTH; } @SuppressWarnings("hiding") @Override public void onSignalStrengthChanged(int signalStrength) { Log.d(TAG, "Signal Strength: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } protected void notifySignalSampled() { int networkType = manager.getNetworkType(); callback.onSignalStrengthSampled(getDescription(), getIcon(networkType)); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Builds a description for the current signal strength. * * @return A human readable description of the network state */ private String getDescription() { StringBuilder sb = new StringBuilder(); sb.append(getStrengthAsString()); sb.append("Network Type: "); sb.append(getTypeAsString(manager.getNetworkType())); sb.append('\n'); sb.append("Operator: "); sb.append(manager.getNetworkOperatorName()); sb.append(" / "); sb.append(manager.getNetworkOperator()); sb.append('\n'); sb.append("Roaming: "); sb.append(manager.isNetworkRoaming()); sb.append('\n'); appendCurrentApns(sb); List<NeighboringCellInfo> infos = manager.getNeighboringCellInfo(); Log.i(TAG, "Found " + infos.size() + " cells."); if (infos.size() > 0) { sb.append("Neighbors: "); for (NeighboringCellInfo info : infos) { sb.append(info.toString()); sb.append(' '); } sb.append('\n'); } CellLocation cell = manager.getCellLocation(); if (cell != null) { sb.append("Cell: "); sb.append(cell.toString()); sb.append('\n'); } return sb.toString(); } private void appendCurrentApns(StringBuilder output) { ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query( APN_URI, new String[] { "name", "apn" }, "current=1", null, null); if (cursor == null) { return; } try { String name = null; String apn = null; while (cursor.moveToNext()) { int nameIdx = cursor.getColumnIndex("name"); int apnIdx = cursor.getColumnIndex("apn"); if (apnIdx < 0 || nameIdx < 0) { continue; } name = cursor.getString(nameIdx); apn = cursor.getString(apnIdx); output.append("APN: "); if (name != null) { output.append(name); } if (apn != null) { output.append(" ("); output.append(apn); output.append(")\n"); } } } finally { cursor.close(); } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public void unregister() { if (manager != null) { manager.listen(this, PhoneStateListener.LISTEN_NONE); manager = null; } } public String getStrengthAsString() { return "Strength: " + signalStrength + "\n"; } protected Context getContext() { return context; } public SignalStrengthCallback getSignalStrengthCallback() { return callback; } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.content.Context; import android.util.Log; /** * Factory for producing a proper {@link SignalStrengthListenerCupcake} according to the * current API level. * * @author Rodrigo Damazio */ public class SignalStrengthListenerFactory { public SignalStrengthListener create(Context context, SignalStrengthCallback callback) { if (hasModernSignalStrength()) { Log.d(TAG, "TrackRecordingService using modern signal strength api."); return new SignalStrengthListenerEclair(context, callback); } else { Log.w(TAG, "TrackRecordingService using legacy signal strength api."); return new SignalStrengthListenerCupcake(context, callback); } } // @VisibleForTesting protected boolean hasModernSignalStrength() { return ANDROID_API_LEVEL >= 7; } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.signalstrength; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; /** * Main signal strength sampler activity, which displays preferences. * * @author Rodrigo Damazio */ public class SignalStrengthPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); // Attach service control funciontality findPreference(getString(R.string.settings_control_start_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.startService(SignalStrengthPreferences.this); return true; } }); findPreference(getString(R.string.settings_control_stop_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.stopService(SignalStrengthPreferences.this); return true; } }); // TODO: Check that my tracks is installed - if not, give a warning and // offer to go to the android market. } }
Java
/* * Copyright 2010 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 com.google.android.apps.mytracks.signalstrength; /** * Interface for the service that reads signal strength. * * @author Rodrigo Damazio */ public interface SignalStrengthListener { /** * Interface for getting notified about a new sampled signal strength. */ public interface SignalStrengthCallback { void onSignalStrengthSampled( String description, String icon); } /** * Starts listening to signal strength. */ void register(); /** * Stops listening to signal strength. */ void unregister(); }
Java
/* * Copyright 2011 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 com.google.android.apps.mytracks.samples.api; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * A receiver to receive MyTracks notifications. * * @author Jimmy Shih */ public class MyTracksReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); long trackId = intent.getLongExtra(context.getString(R.string.track_id_broadcast_extra), -1L); Toast.makeText(context, action + " " + trackId, Toast.LENGTH_LONG).show(); } }
Java
/* * Copyright 2011 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 com.google.android.apps.mytracks.samples.api; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.services.ITrackRecordingService; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.Calendar; import java.util.List; /** * An activity to access MyTracks content provider and service. * * Note you must first install MyTracks before installing this app. * * You also need to enable third party application access inside MyTracks * MyTracks -> menu -> Settings -> Sharing -> Allow access * * @author Jimmy Shih */ public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); // utils to access the MyTracks content provider private MyTracksProviderUtils myTracksProviderUtils; // display output from the MyTracks content provider private TextView outputTextView; // MyTracks service private ITrackRecordingService myTracksService; // intent to access the MyTracks service private Intent intent; // connection to the MyTracks service private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { myTracksService = ITrackRecordingService.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName className) { myTracksService = null; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // for the MyTracks content provider myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this); outputTextView = (TextView) findViewById(R.id.output); Button addWaypointsButton = (Button) findViewById(R.id.add_waypoints_button); addWaypointsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<Track> tracks = myTracksProviderUtils.getAllTracks(); Calendar now = Calendar.getInstance(); for (Track track : tracks) { Waypoint waypoint = new Waypoint(); waypoint.setTrackId(track.getId()); waypoint.setName(now.getTime().toLocaleString()); waypoint.setDescription(now.getTime().toLocaleString()); myTracksProviderUtils.insertWaypoint(waypoint); } } }); // for the MyTracks service intent = new Intent(); ComponentName componentName = new ComponentName( getString(R.string.mytracks_service_package), getString(R.string.mytracks_service_class)); intent.setComponent(componentName); Button startRecordingButton = (Button) findViewById(R.id.start_recording_button); startRecordingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myTracksService != null) { try { myTracksService.startNewTrack(); } catch (RemoteException e) { Log.e(TAG, "RemoteException", e); } } } }); Button stopRecordingButton = (Button) findViewById(R.id.stop_recording_button); stopRecordingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myTracksService != null) { try { myTracksService.endCurrentTrack(); } catch (RemoteException e) { Log.e(TAG, "RemoteException", e); } } } }); } @Override protected void onStart() { super.onStart(); // use the MyTracks content provider to get all the tracks List<Track> tracks = myTracksProviderUtils.getAllTracks(); for (Track track : tracks) { outputTextView.append(track.getId() + " "); } // start and bind the MyTracks service startService(intent); bindService(intent, serviceConnection, 0); } @Override protected void onStop() { super.onStop(); // unbind and stop the MyTracks service if (myTracksService != null) { unbindService(serviceConnection); } stopService(intent); } }
Java
/* * Copyright (c) 2010 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Utilities for Google's Atom XML implementation (see detailed package specification). * * <h2>Package Specification</h2> * * <p> * User-defined Partial XML data models allow you to defined Plain Old Java Objects (POJO's) to * define how the library should parse/serialize XML. Each field that should be included must have * an @{@link com.google.api.client.util.Key} annotation. The field can be of any visibility * (private, package private, protected, or public) and must not be static. * </p> * * <p> * The optional value parameter of this @{@link com.google.api.client.util.Key} annotation specifies * the XPath name to use to represent the field. For example, an XML attribute <code>a</code> has an * XPath name of <code>@a</code>, an XML element <code>&lt;a&gt;</code> has an XPath name of <code> *a * </code>, and an XML text content has an XPath name of <code>text()</code>. These are named based * on their usage with the <a * href="http://code.google.com/apis/gdata/docs/2.0/reference.html#PartialResponse">partial * response/update syntax</a> for Google API's. If the @{@link com.google.api.client.util.Key} * annotation is missing, the default is to use the Atom XML namespace and the Java field's name as * the local XML name. By default, the field name is used as the JSON key. Any unrecognized XML is * normally simply ignored and not stored. If the ability to store unknown keys is important, use * {@link com.google.api.client.xml.GenericXml}. * </p> * * <p> * Let's take a look at a typical partial Atom XML album feed from the Picasa Web Albums Data API: * </p> * * <pre><code> &lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gphoto='http://schemas.google.com/photos/2007'&gt; &lt;link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml' href='http://picasaweb.google.com/data/feed/api/user/liz' /&gt; &lt;author&gt; &lt;name&gt;Liz&lt;/name&gt; &lt;/author&gt; &lt;openSearch:totalResults&gt;1&lt;/openSearch:totalResults&gt; &lt;entry gd:etag='"RXY8fjVSLyp7ImA9WxVVGE8KQAE."'&gt; &lt;category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/photos/2007#album' /&gt; &lt;title&gt;lolcats&lt;/title&gt; &lt;summary&gt;Hilarious Felines&lt;/summary&gt; &lt;gphoto:access&gt;public&lt;/gphoto:access&gt; &lt;/entry&gt; &lt;/feed&gt; </code></pre> * * <p> * Here's one possible way to design the Java data classes for this (each class in its own Java * file): * </p> * * <pre><code> import com.google.api.client.util.*; import java.util.List; public class Link { &#64;Key("&#64;href") public String href; &#64;Key("&#64;rel") public String rel; public static String find(List&lt;Link&gt; links, String rel) { if (links != null) { for (Link link : links) { if (rel.equals(link.rel)) { return link.href; } } } return null; } } public class Category { &#64;Key("&#64;scheme") public String scheme; &#64;Key("&#64;term") public String term; public static Category newKind(String kind) { Category category = new Category(); category.scheme = "http://schemas.google.com/g/2005#kind"; category.term = "http://schemas.google.com/photos/2007#" + kind; return category; } } public class AlbumEntry { &#64;Key public String summary; &#64;Key public String title; &#64;Key("gphoto:access") public String access; public Category category = newKind("album"); private String getEditLink() { return Link.find(links, "edit"); } } public class Author { &#64;Key public String name; } public class AlbumFeed { &#64;Key public Author author; &#64;Key("openSearch:totalResults") public int totalResults; &#64;Key("entry") public List&lt;AlbumEntry&gt; photos; &#64;Key("link") public List&lt;Link&gt; links; private String getPostLink() { return Link.find(links, "http://schemas.google.com/g/2005#post"); } } </code></pre> * * <p> * You can also use the @{@link com.google.api.client.util.Key} annotation to defined query * parameters for a URL. For example: * </p> * * <pre><code> public class PicasaUrl extends GoogleUrl { &#64;Key("max-results") public Integer maxResults; &#64;Key public String kinds; public PicasaUrl(String url) { super(url); } public static PicasaUrl fromRelativePath(String relativePath) { PicasaUrl result = new PicasaUrl(PicasaWebAlbums.ROOT_URL); result.path += relativePath; return result; } } </code></pre> * * <p> * To work with a Google API, you first need to set up the * {@link com.google.api.client.http.HttpTransport}. For example: * </p> * * <pre><code> private static HttpTransport setUpTransport() throws IOException { HttpTransport result = new NetHttpTransport(); GoogleUtils.useMethodOverride(result); HttpHeaders headers = new HttpHeaders(); headers.setApplicationName("Google-PicasaSample/1.0"); headers.gdataVersion = "2"; AtomParser parser = new AtomParser(); parser.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY; transport.addParser(parser); // insert authentication code... return transport; } </code></pre> * * <p> * Now that we have a transport, we can execute a partial GET request to the Picasa Web Albums API * and parse the result: * </p> * * <pre><code> public static AlbumFeed executeGet(HttpTransport transport, PicasaUrl url) throws IOException { url.fields = GoogleAtom.getFieldsFor(AlbumFeed.class); url.kinds = "photo"; url.maxResults = 5; HttpRequest request = transport.buildGetRequest(); request.url = url; return request.execute().parseAs(AlbumFeed.class); } </code></pre> * * <p> * If the server responds with an error the {@link com.google.api.client.http.HttpRequest#execute} * method will throw an {@link com.google.api.client.http.HttpResponseException}, which has an * {@link com.google.api.client.http.HttpResponse} field which can be parsed the same way as a * success response inside of a catch block. For example: * </p> * * <pre><code> try { ... } catch (HttpResponseException e) { if (e.response.getParser() != null) { Error error = e.response.parseAs(Error.class); // process error response } else { String errorContentString = e.response.parseAsString(); // process error response as string } throw e; } </code></pre> * * <p> * To update an album, we use the transport to execute an efficient partial update request using the * PATCH method to the Picasa Web Albums API: * </p> * * <pre><code> public AlbumEntry executePatchRelativeToOriginal(HttpTransport transport, AlbumEntry original) throws IOException { HttpRequest request = transport.buildPatchRequest(); request.setUrl(getEditLink()); request.headers.ifMatch = etag; AtomPatchRelativeToOriginalContent content = new AtomPatchRelativeToOriginalContent(); content.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY; content.originalEntry = original; content.patchedEntry = this; request.content = content; return request.execute().parseAs(AlbumEntry.class); } private static AlbumEntry updateTitle(HttpTransport transport, AlbumEntry album) throws IOException { AlbumEntry patched = album.clone(); patched.title = "An alternate title"; return patched.executePatchRelativeToOriginal(transport, album); } </code></pre> * * <p> * To insert an album, we use the transport to execute a POST request to the Picasa Web Albums API: * </p> * * <pre><code> public AlbumEntry insertAlbum(HttpTransport transport, AlbumEntry entry) throws IOException { HttpRequest request = transport.buildPostRequest(); request.setUrl(getPostLink()); AtomContent content = new AtomContent(); content.namespaceDictionary = PicasaWebAlbumsAtom.NAMESPACE_DICTIONARY; content.entry = entry; request.content = content; return request.execute().parseAs(AlbumEntry.class); } </code></pre> * * <p> * To delete an album, we use the transport to execute a DELETE request to the Picasa Web Albums * API: * </p> * * <pre><code> public void executeDelete(HttpTransport transport) throws IOException { HttpRequest request = transport.buildDeleteRequest(); request.setUrl(getEditLink()); request.headers.ifMatch = etag; request.execute().ignore(); } </code></pre> * * <p> * NOTE: As you might guess, the library uses reflection to populate the user-defined data model. * It's not quite as fast as writing the wire format parsing code yourself can potentially be, but * it's a lot easier. * </p> * * <p> * NOTE: If you prefer to use your favorite XML parsing library instead (there are many of them), * that's supported as well. Just call {@link com.google.api.client.http.HttpRequest#execute()} and * parse the returned byte stream. * </p> * * @since 1.0 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.xml.atom;
Java
/* * Copyright (c) 2010 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 com.google.api.client.googleapis.xml.atom; import com.google.api.client.util.ArrayMap; import com.google.api.client.util.Beta; import com.google.api.client.util.ClassInfo; import com.google.api.client.util.Data; import com.google.api.client.util.FieldInfo; import com.google.api.client.util.GenericData; import com.google.api.client.util.Types; import java.util.Collection; import java.util.Map; import java.util.TreeSet; /** * {@link Beta} <br/> * Utilities for working with the Atom XML of Google Data APIs. * * @since 1.0 * @author Yaniv Inbar */ @Beta public class GoogleAtom { /** * GData namespace. * * @since 1.0 */ public static final String GD_NAMESPACE = "http://schemas.google.com/g/2005"; /** * Content type used on an error formatted in XML. * * @since 1.5 */ public static final String ERROR_CONTENT_TYPE = "application/vnd.google.gdata.error+xml"; // TODO(yanivi): require XmlNamespaceDictory and include xmlns declarations since there is no // guarantee that there is a match between Google's mapping and the one used by client /** * Returns the fields mask to use for the given data class of key/value pairs. It cannot be a * {@link Map}, {@link GenericData} or a {@link Collection}. * * @param dataClass data class of key/value pairs */ public static String getFieldsFor(Class<?> dataClass) { StringBuilder fieldsBuf = new StringBuilder(); appendFieldsFor(fieldsBuf, dataClass, new int[1]); return fieldsBuf.toString(); } /** * Returns the fields mask to use for the given data class of key/value pairs for the feed class * and for the entry class. This should only be used if the feed class does not contain the entry * class as a field. The data classes cannot be a {@link Map}, {@link GenericData} or a * {@link Collection}. * * @param feedClass feed data class * @param entryClass entry data class */ public static String getFeedFields(Class<?> feedClass, Class<?> entryClass) { StringBuilder fieldsBuf = new StringBuilder(); appendFeedFields(fieldsBuf, feedClass, entryClass); return fieldsBuf.toString(); } private static void appendFieldsFor( StringBuilder fieldsBuf, Class<?> dataClass, int[] numFields) { if (Map.class.isAssignableFrom(dataClass) || Collection.class.isAssignableFrom(dataClass)) { throw new IllegalArgumentException( "cannot specify field mask for a Map or Collection class: " + dataClass); } ClassInfo classInfo = ClassInfo.of(dataClass); for (String name : new TreeSet<String>(classInfo.getNames())) { FieldInfo fieldInfo = classInfo.getFieldInfo(name); if (fieldInfo.isFinal()) { continue; } if (++numFields[0] != 1) { fieldsBuf.append(','); } fieldsBuf.append(name); // TODO(yanivi): handle Java arrays? Class<?> fieldClass = fieldInfo.getType(); if (Collection.class.isAssignableFrom(fieldClass)) { // TODO(yanivi): handle Java collection of Java collection or Java map? fieldClass = (Class<?>) Types.getIterableParameter(fieldInfo.getField().getGenericType()); } // TODO(yanivi): implement support for map when server implements support for *:* if (fieldClass != null) { if (fieldInfo.isPrimitive()) { if (name.charAt(0) != '@' && !name.equals("text()")) { // TODO(yanivi): wait for bug fix from server to support text() -- already fixed??? // buf.append("/text()"); } } else if (!Collection.class.isAssignableFrom(fieldClass) && !Map.class.isAssignableFrom(fieldClass)) { int[] subNumFields = new int[1]; int openParenIndex = fieldsBuf.length(); fieldsBuf.append('('); // TODO(yanivi): abort if found cycle to avoid infinite loop appendFieldsFor(fieldsBuf, fieldClass, subNumFields); updateFieldsBasedOnNumFields(fieldsBuf, openParenIndex, subNumFields[0]); } } } } private static void appendFeedFields( StringBuilder fieldsBuf, Class<?> feedClass, Class<?> entryClass) { int[] numFields = new int[1]; appendFieldsFor(fieldsBuf, feedClass, numFields); if (numFields[0] != 0) { fieldsBuf.append(","); } fieldsBuf.append("entry("); int openParenIndex = fieldsBuf.length() - 1; numFields[0] = 0; appendFieldsFor(fieldsBuf, entryClass, numFields); updateFieldsBasedOnNumFields(fieldsBuf, openParenIndex, numFields[0]); } private static void updateFieldsBasedOnNumFields( StringBuilder fieldsBuf, int openParenIndex, int numFields) { switch (numFields) { case 0: fieldsBuf.deleteCharAt(openParenIndex); break; case 1: fieldsBuf.setCharAt(openParenIndex, '/'); break; default: fieldsBuf.append(')'); } } /** * Compute the patch object of key/value pairs from the given original and patched objects, adding * a {@code @gd:fields} key for the fields mask. * * @param patched patched object * @param original original object * @return patch object of key/value pairs */ public static Map<String, Object> computePatch(Object patched, Object original) { FieldsMask fieldsMask = new FieldsMask(); ArrayMap<String, Object> result = computePatchInternal(fieldsMask, patched, original); if (fieldsMask.numDifferences != 0) { result.put("@gd:fields", fieldsMask.buf.toString()); } return result; } private static ArrayMap<String, Object> computePatchInternal( FieldsMask fieldsMask, Object patchedObject, Object originalObject) { ArrayMap<String, Object> result = ArrayMap.create(); Map<String, Object> patchedMap = Data.mapOf(patchedObject); Map<String, Object> originalMap = Data.mapOf(originalObject); TreeSet<String> fieldNames = new TreeSet<String>(); fieldNames.addAll(patchedMap.keySet()); fieldNames.addAll(originalMap.keySet()); for (String name : fieldNames) { Object originalValue = originalMap.get(name); Object patchedValue = patchedMap.get(name); if (originalValue == patchedValue) { continue; } Class<?> type = originalValue == null ? patchedValue.getClass() : originalValue.getClass(); if (Data.isPrimitive(type)) { if (originalValue != null && originalValue.equals(patchedValue)) { continue; } fieldsMask.append(name); // TODO(yanivi): wait for bug fix from server // if (!name.equals("text()") && name.charAt(0) != '@') { // fieldsMask.buf.append("/text()"); // } if (patchedValue != null) { result.add(name, patchedValue); } } else if (Collection.class.isAssignableFrom(type)) { if (originalValue != null && patchedValue != null) { @SuppressWarnings("unchecked") Collection<Object> originalCollection = (Collection<Object>) originalValue; @SuppressWarnings("unchecked") Collection<Object> patchedCollection = (Collection<Object>) patchedValue; int size = originalCollection.size(); if (size == patchedCollection.size()) { int i; for (i = 0; i < size; i++) { FieldsMask subFieldsMask = new FieldsMask(); computePatchInternal(subFieldsMask, patchedValue, originalValue); if (subFieldsMask.numDifferences != 0) { break; } } if (i == size) { continue; } } } // TODO(yanivi): implement throw new UnsupportedOperationException( "not yet implemented: support for patching collections"); } else { if (originalValue == null) { // TODO(yanivi): test fieldsMask.append(name); result.add(name, Data.mapOf(patchedValue)); } else if (patchedValue == null) { // TODO(yanivi): test fieldsMask.append(name); } else { FieldsMask subFieldsMask = new FieldsMask(); ArrayMap<String, Object> patch = computePatchInternal(subFieldsMask, patchedValue, originalValue); int numDifferences = subFieldsMask.numDifferences; if (numDifferences != 0) { fieldsMask.append(name, subFieldsMask); result.add(name, patch); } } } } return result; } static class FieldsMask { int numDifferences; StringBuilder buf = new StringBuilder(); void append(String name) { StringBuilder buf = this.buf; if (++numDifferences != 1) { buf.append(','); } buf.append(name); } void append(String name, FieldsMask subFields) { append(name); StringBuilder buf = this.buf; boolean isSingle = subFields.numDifferences == 1; if (isSingle) { buf.append('/'); } else { buf.append('('); } buf.append(subFields.buf); if (!isSingle) { buf.append(')'); } } } private GoogleAtom() { } }
Java
/* * Copyright (c) 2010 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 com.google.api.client.googleapis.xml.atom; import com.google.api.client.http.HttpMediaType; import com.google.api.client.http.xml.AbstractXmlHttpContent; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import com.google.api.client.xml.XmlNamespaceDictionary; import com.google.api.client.xml.atom.Atom; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.util.Map; /** * {@link Beta} <br/> * Serializes an optimal Atom XML PATCH HTTP content based on the data key/value mapping object for * an Atom entry, by comparing the original value to the patched value. * * <p> * Sample usage: * </p> * * <pre> * <code> static void setContent(HttpRequest request, XmlNamespaceDictionary namespaceDictionary, Object originalEntry, Object patchedEntry) { request.setContent( new AtomPatchRelativeToOriginalContent(namespaceDictionary, originalEntry, patchedEntry)); } * </code> * </pre> * * @since 1.0 * @author Yaniv Inbar */ @Beta public final class AtomPatchRelativeToOriginalContent extends AbstractXmlHttpContent { /** Key/value pair data for the updated/patched Atom entry. */ private final Object patchedEntry; /** Key/value pair data for the original unmodified Atom entry. */ private final Object originalEntry; /** * @param namespaceDictionary XML namespace dictionary * @since 1.5 */ public AtomPatchRelativeToOriginalContent( XmlNamespaceDictionary namespaceDictionary, Object originalEntry, Object patchedEntry) { super(namespaceDictionary); this.originalEntry = Preconditions.checkNotNull(originalEntry); this.patchedEntry = Preconditions.checkNotNull(patchedEntry); } @Override protected void writeTo(XmlSerializer serializer) throws IOException { Map<String, Object> patch = GoogleAtom.computePatch(patchedEntry, originalEntry); getNamespaceDictionary().serialize(serializer, Atom.ATOM_NAMESPACE, "entry", patch); } @Override public AtomPatchRelativeToOriginalContent setMediaType(HttpMediaType mediaType) { super.setMediaType(mediaType); return this; } /** * Returns the data key name/value pairs for the updated/patched Atom entry. * * @since 1.5 */ public final Object getPatchedEntry() { return patchedEntry; } /** * Returns the data key name/value pairs for the original unmodified Atom entry. * * @since 1.5 */ public final Object getOriginalEntry() { return originalEntry; } }
Java
/* * Copyright (c) 2010 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 com.google.api.client.googleapis.xml.atom; import com.google.api.client.http.HttpMediaType; import com.google.api.client.http.xml.atom.AtomContent; import com.google.api.client.util.Beta; import com.google.api.client.xml.Xml; import com.google.api.client.xml.XmlNamespaceDictionary; /** * {@link Beta} <br/> * Serializes Atom XML PATCH HTTP content based on the data key/value mapping object for an Atom * entry. * * <p> * Default value for {@link #getType()} is {@link Xml#MEDIA_TYPE}. * </p> * * <p> * Sample usage: * </p> * * <pre> *<code> static void setContent( HttpRequest request, XmlNamespaceDictionary namespaceDictionary, Object patchEntry) { request.setContent(new AtomPatchContent(namespaceDictionary, patchEntry)); } * </code> * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.0 * @author Yaniv Inbar */ @Beta public final class AtomPatchContent extends AtomContent { /** * @param namespaceDictionary XML namespace dictionary * @param patchEntry key/value pair data for the Atom PATCH entry * @since 1.5 */ public AtomPatchContent(XmlNamespaceDictionary namespaceDictionary, Object patchEntry) { super(namespaceDictionary, patchEntry, true); setMediaType(new HttpMediaType(Xml.MEDIA_TYPE)); } @Override public AtomPatchContent setMediaType(HttpMediaType mediaType) { super.setMediaType(mediaType); return this; } }
Java
/* * Copyright (c) 2010 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 com.google.api.client.googleapis.xml.atom; import com.google.api.client.http.HttpResponse; import com.google.api.client.util.Beta; import com.google.api.client.util.ClassInfo; import com.google.api.client.util.FieldInfo; import com.google.api.client.util.Types; import com.google.api.client.xml.Xml; import com.google.api.client.xml.XmlNamespaceDictionary; import com.google.api.client.xml.atom.AbstractAtomFeedParser; import com.google.api.client.xml.atom.Atom; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.util.HashMap; /** * {@link Beta} <br/> * GData Atom feed pull parser when the entry class can be computed from the kind. * * @param <T> feed type * * @since 1.0 * @author Yaniv Inbar */ @Beta public final class MultiKindFeedParser<T> extends AbstractAtomFeedParser<T> { private final HashMap<String, Class<?>> kindToEntryClassMap = new HashMap<String, Class<?>>(); /** * @param namespaceDictionary XML namespace dictionary * @param parser XML pull parser to use * @param inputStream input stream to read * @param feedClass feed class to parse */ MultiKindFeedParser(XmlNamespaceDictionary namespaceDictionary, XmlPullParser parser, InputStream inputStream, Class<T> feedClass) { super(namespaceDictionary, parser, inputStream, feedClass); } /** Sets the entry classes to use when parsing. */ public void setEntryClasses(Class<?>... entryClasses) { int numEntries = entryClasses.length; HashMap<String, Class<?>> kindToEntryClassMap = this.kindToEntryClassMap; for (int i = 0; i < numEntries; i++) { Class<?> entryClass = entryClasses[i]; ClassInfo typeInfo = ClassInfo.of(entryClass); Field field = typeInfo.getField("@gd:kind"); if (field == null) { throw new IllegalArgumentException("missing @gd:kind field for " + entryClass.getName()); } Object entry = Types.newInstance(entryClass); String kind = (String) FieldInfo.getFieldValue(field, entry); if (kind == null) { throw new IllegalArgumentException( "missing value for @gd:kind field in " + entryClass.getName()); } kindToEntryClassMap.put(kind, entryClass); } } @Override protected Object parseEntryInternal() throws IOException, XmlPullParserException { XmlPullParser parser = getParser(); String kind = parser.getAttributeValue(GoogleAtom.GD_NAMESPACE, "kind"); Class<?> entryClass = this.kindToEntryClassMap.get(kind); if (entryClass == null) { throw new IllegalArgumentException("unrecognized kind: " + kind); } Object result = Types.newInstance(entryClass); Xml.parseElement(parser, result, getNamespaceDictionary(), null); return result; } /** * Parses the given HTTP response using the given feed class and entry classes. * * @param <T> feed type * @param <E> entry type * @param response HTTP response * @param namespaceDictionary XML namespace dictionary * @param feedClass feed class * @param entryClasses entry class * @return Atom multi-kind feed pull parser * @throws IOException I/O exception * @throws XmlPullParserException XML pull parser exception */ public static <T, E> MultiKindFeedParser<T> create(HttpResponse response, XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<E>... entryClasses) throws IOException, XmlPullParserException { InputStream content = response.getContent(); try { Atom.checkContentType(response.getContentType()); XmlPullParser parser = Xml.createParser(); parser.setInput(content, null); MultiKindFeedParser<T> result = new MultiKindFeedParser<T>(namespaceDictionary, parser, content, feedClass); result.setEntryClasses(entryClasses); return result; } finally { content.close(); } } }
Java
/* * Copyright (c) 2012 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. */ /** * Google OAuth 2.0 utilities that help simplify the authorization flow on Java 6. * * @since 1.11 * @author Yaniv Inbar */ package com.google.api.client.googleapis.extensions.java6.auth.oauth2;
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.extensions.java6.auth.oauth2; import com.google.api.client.extensions.java6.auth.oauth2.AbstractPromptReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants; import java.io.IOException; /** * Google OAuth 2.0 abstract verification code receiver that prompts user to paste the code copied * from the browser. * * <p> * Implementation is thread-safe. * </p> * * @since 1.11 * @author Yaniv Inbar */ public class GooglePromptReceiver extends AbstractPromptReceiver { @Override public String getRedirectUri() throws IOException { return GoogleOAuthConstants.OOB_REDIRECT_URI; } }
Java
/* * Copyright (c) 2013 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Test utilities for the {@code com.google.api.client.googleapis.protobuf} package. * * @since 1.16 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.testing.services.protobuf;
Java
/* * Copyright (c) 2013 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 com.google.api.client.googleapis.testing.services.protobuf; import com.google.api.client.googleapis.services.protobuf.AbstractGoogleProtoClient; import com.google.api.client.googleapis.services.protobuf.AbstractGoogleProtoClientRequest; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.UriTemplate; import com.google.api.client.util.Beta; import com.google.protobuf.MessageLite; /** * {@link Beta} <br/> * Thread-safe mock Google protocol buffer request. * * @param <T> type of the response * @since 1.16 * @author Yaniv Inbar */ @Beta public class MockGoogleProtoClientRequest<T> extends AbstractGoogleProtoClientRequest<T> { /** * @param client Google client * @param method HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param message message to serialize or {@code null} for none * @param responseClass response class to parse into */ public MockGoogleProtoClientRequest(AbstractGoogleProtoClient client, String method, String uriTemplate, MessageLite message, Class<T> responseClass) { super(client, method, uriTemplate, message, responseClass); } @Override public MockGoogleProtoClient getAbstractGoogleClient() { return (MockGoogleProtoClient) super.getAbstractGoogleClient(); } @Override public MockGoogleProtoClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (MockGoogleProtoClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public MockGoogleProtoClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (MockGoogleProtoClientRequest<T>) super.setRequestHeaders(headers); } }
Java
/* * Copyright (c) 2013 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 com.google.api.client.googleapis.testing.services.protobuf; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.googleapis.services.protobuf.AbstractGoogleProtoClient; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe mock Google protocol buffer client. * * @since 1.16 * @author Yaniv Inbar */ @Beta public class MockGoogleProtoClient extends AbstractGoogleProtoClient { /** * @param builder builder */ protected MockGoogleProtoClient(Builder builder) { super(builder); } /** * @param transport HTTP transport * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ public MockGoogleProtoClient(HttpTransport transport, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, rootUrl, servicePath, httpRequestInitializer)); } /** * {@link Beta} <br/> * Builder for {@link MockGoogleProtoClient}. * * <p> * Implementation is not thread-safe. * </p> */ @Beta public static class Builder extends AbstractGoogleProtoClient.Builder { /** * @param transport HTTP transport * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ public Builder(HttpTransport transport, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer) { super(transport, rootUrl, servicePath, httpRequestInitializer); } @Override public MockGoogleProtoClient build() { return new MockGoogleProtoClient(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
Java
/* * Copyright (c) 2013 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 com.google.api.client.googleapis.services.protobuf; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import com.google.api.client.util.Beta; import java.io.IOException; /** * {@link Beta} <br/> * Google protocol buffer client request initializer implementation for setting properties like key * and userIp. * * <p> * The simplest usage is to use it to set the key parameter: * </p> * * <pre> public static final GoogleClientRequestInitializer KEY_INITIALIZER = new CommonGoogleProtoClientRequestInitializer(KEY); * </pre> * * <p> * There is also a constructor to set both the key and userIp parameters: * </p> * * <pre> public static final GoogleClientRequestInitializer INITIALIZER = new CommonGoogleProtoClientRequestInitializer(KEY, USER_IP); * </pre> * * <p> * If you want to implement custom logic, extend it like this: * </p> * * <pre> public static class MyRequestInitializer extends CommonGoogleProtoClientRequestInitializer { {@literal @}Override public void initialize(AbstractGoogleProtoClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Finally, to set the key and userIp parameters and insert custom logic, extend it like this: * </p> * * <pre> public static class MyKeyRequestInitializer extends CommonGoogleProtoClientRequestInitializer { public MyKeyRequestInitializer() { super(KEY, USER_IP); } {@literal @}Override public void initializeProtoRequest( AbstractGoogleProtoClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Subclasses should be thread-safe. * </p> * * @since 1.16 * @author Yaniv Inbar */ @Beta public class CommonGoogleProtoClientRequestInitializer extends CommonGoogleClientRequestInitializer { public CommonGoogleProtoClientRequestInitializer() { super(); } /** * @param key API key or {@code null} to leave it unchanged */ public CommonGoogleProtoClientRequestInitializer(String key) { super(key); } /** * @param key API key or {@code null} to leave it unchanged * @param userIp user IP or {@code null} to leave it unchanged */ public CommonGoogleProtoClientRequestInitializer(String key, String userIp) { super(key, userIp); } @Override public final void initialize(AbstractGoogleClientRequest<?> request) throws IOException { super.initialize(request); initializeProtoRequest((AbstractGoogleProtoClientRequest<?>) request); } /** * Initializes a Google protocol buffer client request. * * <p> * Default implementation does nothing. Called from * {@link #initialize(AbstractGoogleClientRequest)}. * </p> * * @throws IOException I/O exception */ protected void initializeProtoRequest(AbstractGoogleProtoClientRequest<?> request) throws IOException { } }
Java
/* * Copyright (c) 2013 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Contains the basis for the generated service-specific libraries based on the Protobuf format. * * @since 1.16 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.services.protobuf;
Java
/* * Copyright (c) 2013 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 com.google.api.client.googleapis.services.protobuf; import com.google.api.client.googleapis.batch.BatchCallback; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.UriTemplate; import com.google.api.client.http.protobuf.ProtoHttpContent; import com.google.api.client.util.Beta; import com.google.protobuf.MessageLite; import java.io.IOException; /** * {@link Beta} <br/> * Google protocol buffer request for a {@link AbstractGoogleProtoClient}. * * <p> * Implementation is not thread-safe. * </p> * * @param <T> type of the response * @since 1.16 * @author Yaniv Inbar */ @Beta public abstract class AbstractGoogleProtoClientRequest<T> extends AbstractGoogleClientRequest<T> { /** Message to serialize or {@code null} for none. */ private final MessageLite message; /** * @param abstractGoogleProtoClient Google protocol buffer client * @param requestMethod HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param message message to serialize or {@code null} for none * @param responseClass response class to parse into */ protected AbstractGoogleProtoClientRequest(AbstractGoogleProtoClient abstractGoogleProtoClient, String requestMethod, String uriTemplate, MessageLite message, Class<T> responseClass) { super(abstractGoogleProtoClient, requestMethod, uriTemplate, message == null ? null : new ProtoHttpContent(message), responseClass); this.message = message; } @Override public AbstractGoogleProtoClient getAbstractGoogleClient() { return (AbstractGoogleProtoClient) super.getAbstractGoogleClient(); } @Override public AbstractGoogleProtoClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (AbstractGoogleProtoClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public AbstractGoogleProtoClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (AbstractGoogleProtoClientRequest<T>) super.setRequestHeaders(headers); } /** * Queues the request into the specified batch request container. * * <p> * Batched requests are then executed when {@link BatchRequest#execute()} is called. * </p> * <p> * Example usage: * </p> * * <pre> * request.queue(batchRequest, new BatchCallback{@literal <}SomeResponseType, Void{@literal >}() { public void onSuccess(SomeResponseType content, HttpHeaders responseHeaders) { log("Success"); } public void onFailure(Void unused, HttpHeaders responseHeaders) { log(e.getMessage()); } }); * </pre> * * * @param batchRequest batch request container * @param callback batch callback */ public final void queue(BatchRequest batchRequest, BatchCallback<T, Void> callback) throws IOException { super.queue(batchRequest, Void.class, callback); } /** Returns the message to serialize or {@code null} for none. */ public Object getMessage() { return message; } @Override public AbstractGoogleProtoClientRequest<T> set(String fieldName, Object value) { return (AbstractGoogleProtoClientRequest<T>) super.set(fieldName, value); } }
Java
/* * Copyright (c) 2013 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 com.google.api.client.googleapis.services.protobuf; import com.google.api.client.googleapis.services.AbstractGoogleClient; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.protobuf.ProtoObjectParser; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe Google protocol buffer client. * * @since 1.16 * @author Yaniv Inbar */ @Beta public abstract class AbstractGoogleProtoClient extends AbstractGoogleClient { /** * @param builder builder */ protected AbstractGoogleProtoClient(Builder builder) { super(builder); } @Override public ProtoObjectParser getObjectParser() { return (ProtoObjectParser) super.getObjectParser(); } /** * {@link Beta} <br/> * Builder for {@link AbstractGoogleProtoClient}. * * <p> * Implementation is not thread-safe. * </p> * @since 1.16 */ @Beta public abstract static class Builder extends AbstractGoogleClient.Builder { /** * @param transport HTTP transport * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ protected Builder(HttpTransport transport, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer) { super(transport, rootUrl, servicePath, new ProtoObjectParser(), httpRequestInitializer); } @Override public final ProtoObjectParser getObjectParser() { return (ProtoObjectParser) super.getObjectParser(); } @Override public abstract AbstractGoogleProtoClient build(); @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
Java
/* * Copyright (c) 2012 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Utilities for Account Manager for Google accounts on Android Eclair (SDK 2.1) and later. * * @since 1.11 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.android.accounts;
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.extensions.android.accounts; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; /** * {@link Beta} <br/> * Account manager wrapper for Google accounts. * * @since 1.11 * @author Yaniv Inbar */ @Beta public final class GoogleAccountManager { /** Google account type. */ public static final String ACCOUNT_TYPE = "com.google"; /** Account manager. */ private final AccountManager manager; /** * @param accountManager account manager */ public GoogleAccountManager(AccountManager accountManager) { this.manager = Preconditions.checkNotNull(accountManager); } /** * @param context context from which to retrieve the account manager */ public GoogleAccountManager(Context context) { this(AccountManager.get(context)); } /** * Returns the account manager. * * @since 1.8 */ public AccountManager getAccountManager() { return manager; } /** * Returns all Google accounts. * * @return array of Google accounts */ public Account[] getAccounts() { return manager.getAccountsByType("com.google"); } /** * Returns the Google account of the given {@link Account#name}. * * @param accountName Google account name or {@code null} for {@code null} result * @return Google account or {@code null} for none found or for {@code null} input */ public Account getAccountByName(String accountName) { if (accountName != null) { for (Account account : getAccounts()) { if (accountName.equals(account.name)) { return account; } } } return null; } /** * Invalidates the given Google auth token by removing it from the account manager's cache (if * necessary) for example if the auth token has expired or otherwise become invalid. * * @param authToken auth token */ public void invalidateAuthToken(String authToken) { manager.invalidateAuthToken(ACCOUNT_TYPE, authToken); } }
Java
/* * 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 com.google.api.client.googleapis.extensions.android.gms.auth; import com.google.android.gms.auth.GooglePlayServicesAvailabilityException; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.api.client.util.Beta; import android.app.Activity; import java.io.IOException; /** * {@link Beta} <br/> * Wraps a {@link GooglePlayServicesAvailabilityException} into an {@link IOException} so it can be * caught directly. * * <p> * Use {@link #getConnectionStatusCode()} to display the error dialog. Alternatively, use * {@link #getCause()} to get the wrapped {@link GooglePlayServicesAvailabilityException}. Example * usage: * </p> * * <pre> } catch (final GooglePlayServicesAvailabilityIOException availabilityException) { myActivity.runOnUiThread(new Runnable() { public void run() { Dialog dialog = GooglePlayServicesUtil.getErrorDialog( availabilityException.getConnectionStatusCode(), myActivity, MyActivity.REQUEST_GOOGLE_PLAY_SERVICES); dialog.show(); } }); * </pre> * * @since 1.12 * @author Yaniv Inbar */ @Beta public class GooglePlayServicesAvailabilityIOException extends UserRecoverableAuthIOException { private static final long serialVersionUID = 1L; GooglePlayServicesAvailabilityIOException(GooglePlayServicesAvailabilityException wrapped) { super(wrapped); } @Override public GooglePlayServicesAvailabilityException getCause() { return (GooglePlayServicesAvailabilityException) super.getCause(); } /** * Returns the error code to use with * {@link GooglePlayServicesUtil#getErrorDialog(int, Activity, int)}. */ public final int getConnectionStatusCode() { return getCause().getConnectionStatusCode(); } }
Java
/* * 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Utilities based on <a href="https://developers.google.com/android/google-play-services/">Google * Play services</a>. * * @since 1.12 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.android.gms.auth;
Java
/* * 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 com.google.api.client.googleapis.extensions.android.gms.auth; import com.google.android.gms.auth.GoogleAuthException; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import java.io.IOException; /** * {@link Beta} <br/> * Wraps a {@link GoogleAuthException} into an {@link IOException} so it can be caught directly. * * <p> * Use {@link #getCause()} to get the wrapped {@link GoogleAuthException}. * </p> * * @since 1.12 * @author Yaniv Inbar */ @Beta public class GoogleAuthIOException extends IOException { private static final long serialVersionUID = 1L; /** * @param wrapped wrapped {@link GoogleAuthException} */ GoogleAuthIOException(GoogleAuthException wrapped) { initCause(Preconditions.checkNotNull(wrapped)); } @Override public GoogleAuthException getCause() { return (GoogleAuthException) super.getCause(); } }
Java
/* * 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 com.google.api.client.googleapis.extensions.android.gms.auth; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.api.client.util.Beta; import android.app.Activity; import android.content.Intent; import java.io.IOException; /** * {@link Beta} <br/> * Wraps a {@link UserRecoverableAuthException} into an {@link IOException} so it can be caught * directly. * * <p> * Use {@link #getIntent()} to allow user interaction to recover. Alternatively, use * {@link #getCause()} to get the wrapped {@link UserRecoverableAuthException}. Example usage: * </p> * * <pre> } catch (UserRecoverableAuthIOException userRecoverableException) { myActivity.startActivityForResult( userRecoverableException.getIntent(), MyActivity.REQUEST_AUTHORIZATION); } * </pre> * * @since 1.12 * @author Yaniv Inbar */ @Beta public class UserRecoverableAuthIOException extends GoogleAuthIOException { private static final long serialVersionUID = 1L; UserRecoverableAuthIOException(UserRecoverableAuthException wrapped) { super(wrapped); } @Override public UserRecoverableAuthException getCause() { return (UserRecoverableAuthException) super.getCause(); } /** * Returns the {@link Intent} that when supplied to * {@link Activity#startActivityForResult(Intent, int)} will allow user intervention. */ public final Intent getIntent() { return getCause().getIntent(); } }
Java
/* * 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 com.google.api.client.googleapis.extensions.android.gms.auth; import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.auth.GooglePlayServicesAvailabilityException; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.android.gms.common.AccountPicker; import com.google.api.client.googleapis.extensions.android.accounts.GoogleAccountManager; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.util.BackOff; import com.google.api.client.util.BackOffUtils; import com.google.api.client.util.Beta; import com.google.api.client.util.ExponentialBackOff; import com.google.api.client.util.Joiner; import com.google.api.client.util.Preconditions; import com.google.api.client.util.Sleeper; import android.accounts.Account; import android.content.Context; import android.content.Intent; import java.io.IOException; import java.util.Collection; /** * {@link Beta} <br/> * Manages authorization and account selection for Google accounts. * * <p> * When fetching a token, any thrown {@link GoogleAuthException} would be wrapped: * <ul> * <li>{@link GooglePlayServicesAvailabilityException} would be wrapped inside of * {@link GooglePlayServicesAvailabilityIOException}</li> * <li>{@link UserRecoverableAuthException} would be wrapped inside of * {@link UserRecoverableAuthIOException}</li> * <li>{@link GoogleAuthException} when be wrapped inside of {@link GoogleAuthIOException}</li> * </ul> * </p> * * <p> * Upgrade warning: in prior version 1.14 exponential back-off was enabled by default when I/O * exception was thrown inside {@link #getToken}, but starting with version 1.15 you need to call * {@link #setBackOff} with {@link ExponentialBackOff} to enable it. * </p> * * @since 1.12 * @author Yaniv Inbar */ @Beta public class GoogleAccountCredential implements HttpRequestInitializer { /** Context. */ final Context context; /** Scope to use on {@link GoogleAuthUtil#getToken}. */ final String scope; /** Google account manager. */ private final GoogleAccountManager accountManager; /** * Selected Google account name (e-mail address), for example {@code "johndoe@gmail.com"}, or * {@code null} for none. */ private String accountName; /** Selected Google account or {@code null} for none. */ private Account selectedAccount; /** Sleeper. */ private Sleeper sleeper = Sleeper.DEFAULT; /** * Back-off policy which is used when an I/O exception is thrown inside {@link #getToken} or * {@code null} for none. */ private BackOff backOff; /** * @param context context * @param scope scope to use on {@link GoogleAuthUtil#getToken} */ public GoogleAccountCredential(Context context, String scope) { accountManager = new GoogleAccountManager(context); this.context = context; this.scope = scope; } /** * Constructs a new instance using OAuth 2.0 scopes. * * @param context context * @param scopes non empty OAuth 2.0 scope list * @return new instance * * @since 1.15 */ public static GoogleAccountCredential usingOAuth2(Context context, Collection<String> scopes) { Preconditions.checkArgument(scopes != null && scopes.iterator().hasNext()); String scopesStr = "oauth2: " + Joiner.on(' ').join(scopes); return new GoogleAccountCredential(context, scopesStr); } /** * Sets the audience scope to use with Google Cloud Endpoints. * * @param context context * @param audience audience * @return new instance */ public static GoogleAccountCredential usingAudience(Context context, String audience) { Preconditions.checkArgument(audience.length() != 0); return new GoogleAccountCredential(context, "audience:" + audience); } /** * Sets the selected Google account name (e-mail address) -- for example * {@code "johndoe@gmail.com"} -- or {@code null} for none. */ public final GoogleAccountCredential setSelectedAccountName(String accountName) { selectedAccount = accountManager.getAccountByName(accountName); // check if account has been deleted this.accountName = selectedAccount == null ? null : accountName; return this; } public void initialize(HttpRequest request) { RequestHandler handler = new RequestHandler(); request.setInterceptor(handler); request.setUnsuccessfulResponseHandler(handler); } /** Returns the context. */ public final Context getContext() { return context; } /** Returns the scope to use on {@link GoogleAuthUtil#getToken}. */ public final String getScope() { return scope; } /** Returns the Google account manager. */ public final GoogleAccountManager getGoogleAccountManager() { return accountManager; } /** Returns all Google accounts or {@code null} for none. */ public final Account[] getAllAccounts() { return accountManager.getAccounts(); } /** Returns the selected Google account or {@code null} for none. */ public final Account getSelectedAccount() { return selectedAccount; } /** * Returns the back-off policy which is used when an I/O exception is thrown inside * {@link #getToken} or {@code null} for none. * * @since 1.15 */ public BackOff getBackOff() { return backOff; } /** * Sets the back-off policy which is used when an I/O exception is thrown inside {@link #getToken} * or {@code null} for none. * * @since 1.15 */ public GoogleAccountCredential setBackOff(BackOff backOff) { this.backOff = backOff; return this; } /** * Returns the sleeper. * * @since 1.15 */ public final Sleeper getSleeper() { return sleeper; } /** * Sets the sleeper. The default value is {@link Sleeper#DEFAULT}. * * @since 1.15 */ public final GoogleAccountCredential setSleeper(Sleeper sleeper) { this.sleeper = Preconditions.checkNotNull(sleeper); return this; } /** * Returns the selected Google account name (e-mail address), for example * {@code "johndoe@gmail.com"}, or {@code null} for none. */ public final String getSelectedAccountName() { return accountName; } /** * Returns an intent to show the user to select a Google account, or create a new one if there are * none on the device yet. * * <p> * Must be run from the main UI thread. * </p> */ public final Intent newChooseAccountIntent() { return AccountPicker.newChooseAccountIntent(selectedAccount, null, new String[] {GoogleAccountManager.ACCOUNT_TYPE}, true, null, null, null, null); } /** * Returns an OAuth 2.0 access token. * * <p> * Must be run from a background thread, not the main UI thread. * </p> */ public String getToken() throws IOException, GoogleAuthException { if (backOff != null) { backOff.reset(); } while (true) { try { return GoogleAuthUtil.getToken(context, accountName, scope); } catch (IOException e) { // network or server error, so retry using back-off policy try { if (backOff == null || !BackOffUtils.next(sleeper, backOff)) { throw e; } } catch (InterruptedException e2) { // ignore } } } } @Beta class RequestHandler implements HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler { /** Whether we've received a 401 error code indicating the token is invalid. */ boolean received401; String token; public void intercept(HttpRequest request) throws IOException { try { token = getToken(); request.getHeaders().setAuthorization("Bearer " + token); } catch (GooglePlayServicesAvailabilityException e) { throw new GooglePlayServicesAvailabilityIOException(e); } catch (UserRecoverableAuthException e) { throw new UserRecoverableAuthIOException(e); } catch (GoogleAuthException e) { throw new GoogleAuthIOException(e); } } public boolean handleResponse( HttpRequest request, HttpResponse response, boolean supportsRetry) { if (response.getStatusCode() == 401 && !received401) { received401 = true; GoogleAuthUtil.invalidateToken(context, token); return true; } return false; } } }
Java
/* * Copyright (c) 2014 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 com.google.api.client.googleapis.extensions.appengine.auth.oauth2; import com.google.appengine.api.appidentity.AppIdentityService; import com.google.appengine.api.appidentity.AppIdentityServiceFailureException; import com.google.appengine.api.appidentity.PublicCertificate; import java.util.Collection; /** * Mock implementation of AppIdentityService interface for testing. * */ public class MockAppIdentityService implements AppIdentityService { private int getAccessTokenCallCount = 0; private String accessTokenText = null; public MockAppIdentityService() { } public int getGetAccessTokenCallCount() { return getAccessTokenCallCount; } public String getAccessTokenText() { return accessTokenText; } public void setAccessTokenText(String text) { accessTokenText = text; } @Override public SigningResult signForApp(byte[] signBlob) { return null; } @Override public Collection<PublicCertificate> getPublicCertificatesForApp() { return null; } @Override public GetAccessTokenResult getAccessToken(Iterable<String> scopes) { getAccessTokenCallCount++; int scopeCount = 0; for (String scope : scopes) { if (scope != null) { scopeCount++; } } if (scopeCount == 0) { throw new AppIdentityServiceFailureException("No scopes specified."); } return new GetAccessTokenResult(accessTokenText, null); } @Override public GetAccessTokenResult getAccessTokenUncached(Iterable<String> scopes) { return null; } @Override public String getServiceAccountName() { return null; } @Override public ParsedAppId parseFullAppId(String fullAppId) { return null; } }
Java
/* * Copyright (c) 2012 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. */ /** * Google App Engine utilities for OAuth 2.0 for Google APIs. * * @since 1.7 * @author Yaniv Inbar */ package com.google.api.client.googleapis.extensions.appengine.auth.oauth2;
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.extensions.appengine.auth.oauth2; import com.google.api.client.auth.oauth2.BearerToken; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import com.google.appengine.api.appidentity.AppIdentityService; import com.google.appengine.api.appidentity.AppIdentityServiceFactory; import java.io.IOException; import java.util.Collection; import java.util.Collections; /** * OAuth 2.0 credential in which a client Google App Engine application needs to access data that it * owns, based on <a href="https://developers.google.com/appengine/docs/java/appidentity/ * #Java_Asserting_identity_to_Google_APIs">Asserting Identity to Google APIs</a> * * <p> * Intercepts the request by using the access token obtained from * {@link AppIdentityService#getAccessToken(Iterable)}. * </p> * * <p> * Sample usage: * </p> * * <pre> public static HttpRequestFactory createRequestFactory( HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) { return transport.createRequestFactory( new AppIdentityCredential("https://www.googleapis.com/auth/urlshortener")); } * </pre> * * <p> * Implementation is immutable and thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class AppIdentityCredential implements HttpRequestInitializer, HttpExecuteInterceptor { /** App Identity Service that provides the access token. */ private final AppIdentityService appIdentityService; /** OAuth scopes (unmodifiable). */ private final Collection<String> scopes; /** * @param scopes OAuth scopes * @since 1.15 */ public AppIdentityCredential(Collection<String> scopes) { this(new Builder(scopes)); } /** * @param builder builder * * @since 1.14 */ protected AppIdentityCredential(Builder builder) { // Lazily retrieved rather than setting as the default value in order to not add runtime // dependencies on AppIdentityServiceFactory unless it is actually being used. appIdentityService = builder.appIdentityService == null ? AppIdentityServiceFactory.getAppIdentityService() : builder.appIdentityService; scopes = builder.scopes; } @Override public void initialize(HttpRequest request) throws IOException { request.setInterceptor(this); } @Override public void intercept(HttpRequest request) throws IOException { String accessToken = appIdentityService.getAccessToken(scopes).getAccessToken(); BearerToken.authorizationHeaderAccessMethod().intercept(request, accessToken); } /** * Gets the App Identity Service that provides the access token. * * @since 1.12 */ public final AppIdentityService getAppIdentityService() { return appIdentityService; } /** * Gets the OAuth scopes (unmodifiable). * * @since 1.12 */ public final Collection<String> getScopes() { return scopes; } /** * Builder for {@link AppIdentityCredential}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.12 */ public static class Builder { /** * App Identity Service that provides the access token or {@code null} to use * {@link AppIdentityServiceFactory#getAppIdentityService()}. */ AppIdentityService appIdentityService; /** OAuth scopes (unmodifiable). */ final Collection<String> scopes; /** * Returns an instance of a new builder. * * @param scopes OAuth scopes * @since 1.15 */ public Builder(Collection<String> scopes) { this.scopes = Collections.unmodifiableCollection(scopes); } /** * Returns the App Identity Service that provides the access token or {@code null} to use * {@link AppIdentityServiceFactory#getAppIdentityService()}. * * @since 1.14 */ public final AppIdentityService getAppIdentityService() { return appIdentityService; } /** * Sets the App Identity Service that provides the access token or {@code null} to use * {@link AppIdentityServiceFactory#getAppIdentityService()}. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setAppIdentityService(AppIdentityService appIdentityService) { this.appIdentityService = appIdentityService; return this; } /** * Returns a new {@link AppIdentityCredential}. */ public AppIdentityCredential build() { return new AppIdentityCredential(this); } /** * Returns the OAuth scopes (unmodifiable). * * @since 1.14 */ public final Collection<String> getScopes() { return scopes; } } /** * {@link Beta} <br/> * Credential wrapper for application identity that inherits from GoogleCredential. */ @Beta public static class AppEngineCredentialWrapper extends GoogleCredential { private final AppIdentityCredential appIdentity; private final boolean scopesRequired; /** * Constructs the wrapper using the default AppIdentityService. * * @param transport the transport for Http calls. * @param jsonFactory the factory for Json parsing and formatting. * @throws IOException if the credential cannot be created for the current environment, * such as when the AppIndentityService is not available. */ public AppEngineCredentialWrapper(HttpTransport transport, JsonFactory jsonFactory) throws IOException { // May be called via reflection to test whether running on App Engine, so fail even if // the type can be loaded but the service is not available. this(getCheckedAppIdentityCredential(), Preconditions.checkNotNull(transport), Preconditions.checkNotNull(jsonFactory)); } AppEngineCredentialWrapper( AppIdentityCredential appIdentity, HttpTransport transport, JsonFactory jsonFactory) { super(new GoogleCredential.Builder() .setRequestInitializer(appIdentity) .setTransport(transport) .setJsonFactory(jsonFactory)); this.appIdentity = appIdentity; Collection<String> scopes = appIdentity.getScopes(); scopesRequired = (scopes == null || scopes.isEmpty()); } private static AppIdentityCredential getCheckedAppIdentityCredential() throws IOException { Collection<String> emptyScopes = Collections.emptyList(); AppIdentityCredential appIdentity = new AppIdentityCredential(emptyScopes); // May be called via reflection to test whether running on App Engine, so fail even if // the type can be loaded but the service is not available. if (appIdentity.getAppIdentityService() == null) { throw new IOException("AppIdentityService not available."); } return appIdentity; } @Override public void intercept(HttpRequest request) throws IOException { appIdentity.intercept(request); } @Override public boolean createScopedRequired() { return scopesRequired; } @Override public GoogleCredential createScoped(Collection<String> scopes) { return new AppEngineCredentialWrapper( new AppIdentityCredential.Builder(scopes) .setAppIdentityService(appIdentity.getAppIdentityService()) .build(), getTransport(), getJsonFactory()); } } }
Java
/* * Copyright (c) 2013 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for subscribing to topics and receiving notifications on servlet-based platforms. * * @since 1.16 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.appengine.notifications;
Java
/* * Copyright (c) 2013 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 com.google.api.client.googleapis.extensions.appengine.notifications; import com.google.api.client.extensions.appengine.datastore.AppEngineDataStoreFactory; import com.google.api.client.googleapis.extensions.servlet.notifications.WebhookUtils; import com.google.api.client.util.Beta; import com.google.api.client.util.store.DataStoreFactory; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link Beta} <br/> * Thread-safe Webhook App Engine Servlet to receive notifications. * * <p> * In order to use this servlet you need to register the servlet in your web.xml. You may optionally * extend {@link AppEngineNotificationServlet} with custom behavior. * </p> * * <p> * It is a simple wrapper around {@link WebhookUtils#processWebhookNotification(HttpServletRequest, * HttpServletResponse, DataStoreFactory)} that uses * {@link AppEngineDataStoreFactory#getDefaultInstance()}, so you may alternatively call that method * instead from your {@link HttpServlet#doPost} with no loss of functionality. * </p> * * <b>Sample web.xml setup:</b> * * <pre> {@literal <}servlet{@literal >} {@literal <}servlet-name{@literal >}AppEngineNotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}servlet-class{@literal >}com.google.api.client.googleapis.extensions.appengine.notifications.AppEngineNotificationServlet{@literal <}/servlet-class{@literal >} {@literal <}/servlet{@literal >} {@literal <}servlet-mapping{@literal >} {@literal <}servlet-name{@literal >}AppEngineNotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}url-pattern{@literal >}/notifications{@literal <}/url-pattern{@literal >} {@literal <}/servlet-mapping{@literal >} * </pre> * * @author Yaniv Inbar * @since 1.16 */ @Beta public class AppEngineNotificationServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { WebhookUtils.processWebhookNotification( req, resp, AppEngineDataStoreFactory.getDefaultInstance()); } }
Java
/* * Copyright (c) 2014 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.googleapis.TestUtils; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.json.GenericJson; import com.google.api.client.json.Json; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; import com.google.api.client.testing.http.MockHttpTransport; import com.google.api.client.testing.http.MockLowLevelHttpRequest; import com.google.api.client.testing.http.MockLowLevelHttpResponse; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * A test transport that simulates Google's token server for refresh tokens and service accounts. */ class MockTokenServerTransport extends MockHttpTransport { static final String EXPECTED_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; static final JsonFactory JSON_FACTORY = new JacksonFactory(); Map<String, String> serviceAccounts = new HashMap<String, String>(); Map<String, String> clients = new HashMap<String, String>(); Map<String, String> refreshTokens = new HashMap<String, String>(); public MockTokenServerTransport() { } public void addServiceAccount(String email, String accessToken) { serviceAccounts.put(email, accessToken); } void addClient(String clientId, String clientSecret) { clients.put(clientId, clientSecret); } void addRefreshToken(String refreshToken, String accessTokenToReturn) { refreshTokens.put(refreshToken, accessTokenToReturn); } @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { if (url.equals(GoogleOAuthConstants.TOKEN_SERVER_URL)) { MockLowLevelHttpRequest request = new MockLowLevelHttpRequest(url) { @Override public LowLevelHttpResponse execute() throws IOException { String content = this.getContentAsString(); Map<String, String> query = TestUtils.parseQuery(content); String accessToken = null; String foundId = query.get("client_id"); if (foundId != null) { if (!clients.containsKey(foundId)) { throw new IOException("Client ID not found."); } String foundSecret = query.get("client_secret"); String expectedSecret = clients.get(foundId); if (foundSecret == null || !foundSecret.equals(expectedSecret)) { throw new IOException("Client secret not found."); } String foundRefresh = query.get("refresh_token"); if (!refreshTokens.containsKey(foundRefresh)) { throw new IOException("Refresh Token not found."); } accessToken = refreshTokens.get(foundRefresh); } else if (query.containsKey("grant_type")) { String grantType = query.get("grant_type"); if (!EXPECTED_GRANT_TYPE.equals(grantType)) { throw new IOException("Unexpected Grant Type."); } String assertion = query.get("assertion"); JsonWebSignature signature = JsonWebSignature.parse(JSON_FACTORY, assertion); String foundEmail = signature.getPayload().getIssuer(); if (!serviceAccounts.containsKey(foundEmail)) { throw new IOException("Service Account Email not found as issuer."); } accessToken = serviceAccounts.get(foundEmail); String foundScopes = (String) signature.getPayload().get("scope"); if (foundScopes == null || foundScopes.length() == 0) { throw new IOException("Scopes not found."); } } else { throw new IOException("Uknown token type."); } // Create the JSon response GenericJson refreshContents = new GenericJson(); refreshContents.setFactory(JSON_FACTORY); refreshContents.put("access_token", accessToken); refreshContents.put("expires_in", 3600000); refreshContents.put("token_type", "Bearer"); String refreshText = refreshContents.toPrettyString(); MockLowLevelHttpResponse response = new MockLowLevelHttpResponse() .setContentType(Json.MEDIA_TYPE) .setContent(refreshText); return response; } }; return request; } return super.buildRequest(method, url); } }
Java
/* * Copyright (c) 2014 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 com.google.api.client.googleapis.compute; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.json.GenericJson; import com.google.api.client.json.Json; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.testing.http.MockHttpTransport; import com.google.api.client.testing.http.MockLowLevelHttpRequest; import com.google.api.client.testing.http.MockLowLevelHttpResponse; import java.io.IOException; /** * Transport that simulates the GCE metadata server for access tokens * */ public class MockMetadataServerTransport extends MockHttpTransport { private final static String METADATA_SERVER_URL = "http://metadata/computeMetadata/v1/instance/service-accounts/default/token"; static final JsonFactory JSON_FACTORY = new JacksonFactory(); String accessToken; public MockMetadataServerTransport(String accessToken) { this.accessToken = accessToken; } @Override public LowLevelHttpRequest buildRequest(String method, String url) throws IOException { if (url.equals(METADATA_SERVER_URL)) { MockLowLevelHttpRequest request = new MockLowLevelHttpRequest(url) { @Override public LowLevelHttpResponse execute() throws IOException { String metadataRequestHeader = getFirstHeaderValue("X-Google-Metadata-Request"); if (!"true".equals(metadataRequestHeader)) { throw new IOException("Metadata request header not found."); } // Create the JSon response GenericJson refreshContents = new GenericJson(); refreshContents.setFactory(JSON_FACTORY); refreshContents.put("access_token", accessToken); refreshContents.put("expires_in", 3600000); refreshContents.put("token_type", "Bearer"); String refreshText = refreshContents.toPrettyString(); MockLowLevelHttpResponse response = new MockLowLevelHttpResponse() .setContentType(Json.MEDIA_TYPE) .setContent(refreshText); return response; } }; return request; } return super.buildRequest(method, url); } }
Java
/* * Copyright (c) 2010 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. */ /** * Google APIs. * * @since 1.0 * @author Yaniv Inbar */ package com.google.api.client.googleapis;
Java
/* * Copyright (c) 2013 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. */ /** * Google API's support based on the {@code java.net} package. * * @since 1.14 * @author Yaniv Inbar */ package com.google.api.client.googleapis.javanet;
Java
/* * Copyright (c) 2013 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 com.google.api.client.googleapis.javanet; import com.google.api.client.googleapis.GoogleUtils; import com.google.api.client.http.javanet.NetHttpTransport; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; /** * Utilities for Google APIs based on {@link NetHttpTransport}. * * @since 1.14 * @author Yaniv Inbar */ public class GoogleNetHttpTransport { /** * Returns a new instance of {@link NetHttpTransport} that uses * {@link GoogleUtils#getCertificateTrustStore()} for the trusted certificates using * {@link com.google.api.client.http.javanet.NetHttpTransport.Builder#trustCertificates(KeyStore)} * . * * <p> * This helper method doesn't provide for customization of the {@link NetHttpTransport}, such as * the ability to specify a proxy. To do use, use * {@link com.google.api.client.http.javanet.NetHttpTransport.Builder}, for example: * </p> * * <pre> static HttpTransport newProxyTransport() throws GeneralSecurityException, IOException { NetHttpTransport.Builder builder = new NetHttpTransport.Builder(); builder.trustCertificates(GoogleUtils.getCertificateTrustStore()); builder.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128))); return builder.build(); } * </pre> */ public static NetHttpTransport newTrustedTransport() throws GeneralSecurityException, IOException { return new NetHttpTransport.Builder().trustCertificates(GoogleUtils.getCertificateTrustStore()) .build(); } private GoogleNetHttpTransport() { } }
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.batch; import com.google.api.client.http.HttpHeaders; import java.io.IOException; /** * Callback for an individual batch response. * * <p> * Sample use: * </p> * * <pre> batch.queue(volumesList.buildHttpRequest(), Volumes.class, GoogleJsonErrorContainer.class, new BatchCallback&lt;Volumes, GoogleJsonErrorContainer&gt;() { public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) { log("Success"); printVolumes(volumes.getItems()); } public void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) { log(e.getError().getMessage()); } }); * </pre> * * @param <T> Type of the data model class * @param <E> Type of the error data model class * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ public interface BatchCallback<T, E> { /** * Called if the individual batch response is successful. * * @param t instance of the parsed data model class * @param responseHeaders Headers of the batch response */ void onSuccess(T t, HttpHeaders responseHeaders) throws IOException; /** * Called if the individual batch response is unsuccessful. * * @param e instance of data class representing the error response content * @param responseHeaders Headers of the batch response */ void onFailure(E e, HttpHeaders responseHeaders) throws IOException; }
Java
/* * Copyright (c) 2012 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. */ /** * Batch for Google API's. * * @since 1.9 * @author Ravi Mistry */ package com.google.api.client.googleapis.batch;
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.batch; import com.google.api.client.http.BackOffPolicy; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.http.MultipartContent; import com.google.api.client.util.Preconditions; import com.google.api.client.util.Sleeper; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * An instance of this class represents a single batch of requests. * * <p> * Sample use: * </p> * * <pre> BatchRequest batch = new BatchRequest(transport, httpRequestInitializer); batch.queue(volumesList, Volumes.class, GoogleJsonErrorContainer.class, new BatchCallback&lt;Volumes, GoogleJsonErrorContainer&gt;() { public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) { log("Success"); printVolumes(volumes.getItems()); } public void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) { log(e.getError().getMessage()); } }); batch.queue(volumesList, Volumes.class, GoogleJsonErrorContainer.class, new BatchCallback&lt;Volumes, GoogleJsonErrorContainer&gt;() { public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) { log("Success"); printVolumes(volumes.getItems()); } public void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) { log(e.getError().getMessage()); } }); batch.execute(); * </pre> * * <p> * The content of each individual response is stored in memory. There is thus a potential of * encountering an {@link OutOfMemoryError} for very large responses. * </p> * * <p> * Redirects are currently not followed in {@link BatchRequest}. * </p> * * <p> * Implementation is not thread-safe. * </p> * * <p> * Note: When setting an {@link HttpUnsuccessfulResponseHandler} by calling to * {@link HttpRequest#setUnsuccessfulResponseHandler}, the handler is called for each unsuccessful * part. As a result it's not recommended to use {@link HttpBackOffUnsuccessfulResponseHandler} on a * batch request, since the back-off policy is invoked for each unsuccessful part. * </p> * * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ @SuppressWarnings("deprecation") public final class BatchRequest { /** The URL where batch requests are sent. */ private GenericUrl batchUrl = new GenericUrl("https://www.googleapis.com/batch"); /** The request factory for connections to the server. */ private final HttpRequestFactory requestFactory; /** The list of queued request infos. */ List<RequestInfo<?, ?>> requestInfos = new ArrayList<RequestInfo<?, ?>>(); /** Sleeper. */ private Sleeper sleeper = Sleeper.DEFAULT; /** A container class used to hold callbacks and data classes. */ static class RequestInfo<T, E> { final BatchCallback<T, E> callback; final Class<T> dataClass; final Class<E> errorClass; final HttpRequest request; RequestInfo(BatchCallback<T, E> callback, Class<T> dataClass, Class<E> errorClass, HttpRequest request) { this.callback = callback; this.dataClass = dataClass; this.errorClass = errorClass; this.request = request; } } /** * Construct the {@link BatchRequest}. * * @param transport The transport to use for requests * @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or * {@code null} for none */ public BatchRequest(HttpTransport transport, HttpRequestInitializer httpRequestInitializer) { this.requestFactory = httpRequestInitializer == null ? transport.createRequestFactory() : transport.createRequestFactory(httpRequestInitializer); } /** * Sets the URL that will be hit when {@link #execute()} is called. The default value is * {@code https://www.googleapis.com/batch}. */ public BatchRequest setBatchUrl(GenericUrl batchUrl) { this.batchUrl = batchUrl; return this; } /** Returns the URL that will be hit when {@link #execute()} is called. */ public GenericUrl getBatchUrl() { return batchUrl; } /** * Returns the sleeper. * * @since 1.15 */ public Sleeper getSleeper() { return sleeper; } /** * Sets the sleeper. The default value is {@link Sleeper#DEFAULT}. * * @since 1.15 */ public BatchRequest setSleeper(Sleeper sleeper) { this.sleeper = Preconditions.checkNotNull(sleeper); return this; } /** * Queues the specified {@link HttpRequest} for batched execution. Batched requests are executed * when {@link #execute()} is called. * * @param <T> destination class type * @param <E> error class type * @param httpRequest HTTP Request * @param dataClass Data class the response will be parsed into or {@code Void.class} to ignore * the content * @param errorClass Data class the unsuccessful response will be parsed into or * {@code Void.class} to ignore the content * @param callback Batch Callback * @return this Batch request * @throws IOException If building the HTTP Request fails */ public <T, E> BatchRequest queue(HttpRequest httpRequest, Class<T> dataClass, Class<E> errorClass, BatchCallback<T, E> callback) throws IOException { Preconditions.checkNotNull(httpRequest); // TODO(rmistry): Add BatchUnparsedCallback with onResponse(InputStream content, HttpHeaders). Preconditions.checkNotNull(callback); Preconditions.checkNotNull(dataClass); Preconditions.checkNotNull(errorClass); requestInfos.add(new RequestInfo<T, E>(callback, dataClass, errorClass, httpRequest)); return this; } /** * Returns the number of queued requests in this batch request. */ public int size() { return requestInfos.size(); } /** * Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks. * * <p> * Calling {@link #execute()} executes and clears the queued requests. This means that the * {@link BatchRequest} object can be reused to {@link #queue} and {@link #execute()} requests * again. * </p> */ public void execute() throws IOException { boolean retryAllowed; Preconditions.checkState(!requestInfos.isEmpty()); HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null); // NOTE: batch does not support gzip encoding HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor(); batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor)); int retriesRemaining = batchRequest.getNumberOfRetries(); BackOffPolicy backOffPolicy = batchRequest.getBackOffPolicy(); if (backOffPolicy != null) { // Reset the BackOffPolicy at the start of each execute. backOffPolicy.reset(); } do { retryAllowed = retriesRemaining > 0; MultipartContent batchContent = new MultipartContent(); batchContent.getMediaType().setSubType("mixed"); int contentId = 1; for (RequestInfo<?, ?> requestInfo : requestInfos) { batchContent.addPart(new MultipartContent.Part( new HttpHeaders().setAcceptEncoding(null).set("Content-ID", contentId++), new HttpRequestContent(requestInfo.request))); } batchRequest.setContent(batchContent); HttpResponse response = batchRequest.execute(); BatchUnparsedResponse batchResponse; try { // Find the boundary from the Content-Type header. String boundary = "--" + response.getMediaType().getParameter("boundary"); // Parse the content stream. InputStream contentStream = response.getContent(); batchResponse = new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed); while (batchResponse.hasNext) { batchResponse.parseNextResponse(); } } finally { response.disconnect(); } List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos; if (!unsuccessfulRequestInfos.isEmpty()) { requestInfos = unsuccessfulRequestInfos; // backOff if required. if (batchResponse.backOffRequired && backOffPolicy != null) { long backOffTime = backOffPolicy.getNextBackOffMillis(); if (backOffTime != BackOffPolicy.STOP) { try { sleeper.sleep(backOffTime); } catch (InterruptedException exception) { // ignore } } } } else { break; } retriesRemaining--; } while (retryAllowed); requestInfos.clear(); } /** * Batch HTTP request execute interceptor that loops through all individual HTTP requests and runs * their interceptors. */ class BatchInterceptor implements HttpExecuteInterceptor { private HttpExecuteInterceptor originalInterceptor; BatchInterceptor(HttpExecuteInterceptor originalInterceptor) { this.originalInterceptor = originalInterceptor; } public void intercept(HttpRequest batchRequest) throws IOException { if (originalInterceptor != null) { originalInterceptor.intercept(batchRequest); } for (RequestInfo<?, ?> requestInfo : requestInfos) { HttpExecuteInterceptor interceptor = requestInfo.request.getInterceptor(); if (interceptor != null) { interceptor.intercept(requestInfo.request); } } } } }
Java
/* * Copyright (c) 2013 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 com.google.api.client.googleapis.batch; import com.google.api.client.http.AbstractHttpContent; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; /** * HTTP request wrapped as a content part of a multipart/mixed request. * * @author Yaniv Inbar */ class HttpRequestContent extends AbstractHttpContent { static final String NEWLINE = "\r\n"; /** HTTP request. */ private final HttpRequest request; HttpRequestContent(HttpRequest request) { super("application/http"); this.request = request; } public void writeTo(OutputStream out) throws IOException { Writer writer = new OutputStreamWriter(out, getCharset()); // write method and URL writer.write(request.getRequestMethod()); writer.write(" "); writer.write(request.getUrl().build()); writer.write(NEWLINE); // write headers HttpHeaders headers = new HttpHeaders(); headers.fromHttpHeaders(request.getHeaders()); headers.setAcceptEncoding(null).setUserAgent(null) .setContentEncoding(null).setContentType(null).setContentLength(null); // analyze the content HttpContent content = request.getContent(); if (content != null) { headers.setContentType(content.getType()); // NOTE: batch does not support gzip encoding long contentLength = content.getLength(); if (contentLength != -1) { headers.setContentLength(contentLength); } } HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer); // write content if (content != null) { writer.write(NEWLINE); writer.flush(); content.writeTo(out); } } }
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.batch.json; import com.google.api.client.googleapis.batch.BatchCallback; import com.google.api.client.googleapis.json.GoogleJsonError; import com.google.api.client.googleapis.json.GoogleJsonErrorContainer; import com.google.api.client.http.HttpHeaders; import java.io.IOException; /** * Callback for an individual batch JSON response. * * <p> * Sample use: * </p> * * <pre> batch.queue(volumesList.buildHttpRequest(), Volumes.class, GoogleJsonErrorContainer.class, new JsonBatchCallback&lt;Volumes&gt;() { public void onSuccess(Volumes volumes, HttpHeaders responseHeaders) { log("Success"); printVolumes(volumes.getItems()); } public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) { log(e.getMessage()); } }); * </pre> * * @param <T> Type of the data model class * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ public abstract class JsonBatchCallback<T> implements BatchCallback<T, GoogleJsonErrorContainer> { public final void onFailure(GoogleJsonErrorContainer e, HttpHeaders responseHeaders) throws IOException { onFailure(e.getError(), responseHeaders); } /** * Called if the individual batch response is unsuccessful. * * @param e Google JSON error response content * @param responseHeaders Headers of the batch response */ public abstract void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException; }
Java
/* * Copyright (c) 2012 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. */ /** * JSON batch for Google API's. * * @since 1.9 * @author Ravi Mistry */ package com.google.api.client.googleapis.batch.json;
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.batch; import com.google.api.client.googleapis.batch.BatchRequest.RequestInfo; import com.google.api.client.http.BackOffPolicy; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpStatusCodes; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; import com.google.api.client.util.StringUtils; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; /** * The unparsed batch response. * * @author rmistry@google.com (Ravi Mistry) */ @SuppressWarnings("deprecation") final class BatchUnparsedResponse { /** The boundary used in the batch response to separate individual responses. */ private final String boundary; /** List of request infos. */ private final List<RequestInfo<?, ?>> requestInfos; /** Buffers characters from the input stream. */ private final BufferedReader bufferedReader; /** Determines whether there are any responses to be parsed. */ boolean hasNext = true; /** List of unsuccessful HTTP requests that can be retried. */ List<RequestInfo<?, ?>> unsuccessfulRequestInfos = new ArrayList<RequestInfo<?, ?>>(); /** Indicates if back off is required before the next retry. */ boolean backOffRequired; /** The content Id the response is currently at. */ private int contentId = 0; /** Whether unsuccessful HTTP requests can be retried. */ private final boolean retryAllowed; /** * Construct the {@link BatchUnparsedResponse}. * * @param inputStream Input stream that contains the batch response * @param boundary The boundary of the batch response * @param requestInfos List of request infos * @param retryAllowed Whether unsuccessful HTTP requests can be retried */ BatchUnparsedResponse(InputStream inputStream, String boundary, List<RequestInfo<?, ?>> requestInfos, boolean retryAllowed) throws IOException { this.boundary = boundary; this.requestInfos = requestInfos; this.retryAllowed = retryAllowed; this.bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); // First line in the stream will be the boundary. checkForFinalBoundary(bufferedReader.readLine()); } /** * Parses the next response in the queue if a data class and a {@link BatchCallback} is specified. * * <p> * This method closes the input stream if there are no more individual responses left. * </p> */ void parseNextResponse() throws IOException { contentId++; // Extract the outer headers. String line; while ((line = bufferedReader.readLine()) != null && !line.equals("")) { // Do nothing. } // Extract the status code. String statusLine = bufferedReader.readLine(); String[] statusParts = statusLine.split(" "); int statusCode = Integer.parseInt(statusParts[1]); // Extract and store the inner headers. // TODO(rmistry): Handle inner headers that span multiple lines. More details here: // http://tools.ietf.org/html/rfc2616#section-2.2 List<String> headerNames = new ArrayList<String>(); List<String> headerValues = new ArrayList<String>(); while ((line = bufferedReader.readLine()) != null && !line.equals("")) { String[] headerParts = line.split(": ", 2); headerNames.add(headerParts[0]); headerValues.add(headerParts[1]); } // Extract the response part content. // TODO(rmistry): Investigate a way to use the stream directly. This is to reduce the chance of // an OutOfMemoryError and will make parsing more efficient. StringBuilder partContent = new StringBuilder(); while ((line = bufferedReader.readLine()) != null && !line.startsWith(boundary)) { partContent.append(line); } HttpResponse response = getFakeResponse(statusCode, partContent.toString(), headerNames, headerValues); parseAndCallback(requestInfos.get(contentId - 1), statusCode, contentId, response); checkForFinalBoundary(line); } /** * Parse an object into a new instance of the data class using * {@link HttpResponse#parseAs(java.lang.reflect.Type)}. */ private <T, E> void parseAndCallback( RequestInfo<T, E> requestInfo, int statusCode, int contentID, HttpResponse response) throws IOException { BatchCallback<T, E> callback = requestInfo.callback; HttpHeaders responseHeaders = response.getHeaders(); HttpUnsuccessfulResponseHandler unsuccessfulResponseHandler = requestInfo.request.getUnsuccessfulResponseHandler(); BackOffPolicy backOffPolicy = requestInfo.request.getBackOffPolicy(); // Reset backOff flag. backOffRequired = false; if (HttpStatusCodes.isSuccess(statusCode)) { if (callback == null) { // No point in parsing if there is no callback. return; } T parsed = getParsedDataClass( requestInfo.dataClass, response, requestInfo, responseHeaders.getContentType()); callback.onSuccess(parsed, responseHeaders); } else { HttpContent content = requestInfo.request.getContent(); boolean retrySupported = retryAllowed && (content == null || content.retrySupported()); boolean errorHandled = false; boolean redirectRequest = false; if (unsuccessfulResponseHandler != null) { errorHandled = unsuccessfulResponseHandler.handleResponse( requestInfo.request, response, retrySupported); } if (!errorHandled) { if (requestInfo.request.handleRedirect(response.getStatusCode(), response.getHeaders())) { redirectRequest = true; } else if (retrySupported && backOffPolicy != null && backOffPolicy.isBackOffRequired(response.getStatusCode())) { backOffRequired = true; } } if (retrySupported && (errorHandled || backOffRequired || redirectRequest)) { unsuccessfulRequestInfos.add(requestInfo); } else { if (callback == null) { // No point in parsing if there is no callback. return; } E parsed = getParsedDataClass( requestInfo.errorClass, response, requestInfo, responseHeaders.getContentType()); callback.onFailure(parsed, responseHeaders); } } } private <A, T, E> A getParsedDataClass( Class<A> dataClass, HttpResponse response, RequestInfo<T, E> requestInfo, String contentType) throws IOException { // TODO(yanivi): Remove the HttpResponse reference and directly parse the InputStream if (dataClass == Void.class) { return null; } return requestInfo.request.getParser().parseAndClose( response.getContent(), response.getContentCharset(), dataClass); } /** Create a fake HTTP response object populated with the partContent and the statusCode. */ private HttpResponse getFakeResponse(final int statusCode, final String partContent, List<String> headerNames, List<String> headerValues) throws IOException { HttpRequest request = new FakeResponseHttpTransport( statusCode, partContent, headerNames, headerValues).createRequestFactory() .buildPostRequest(new GenericUrl("http://google.com/"), null); request.setLoggingEnabled(false); request.setThrowExceptionOnExecuteError(false); return request.execute(); } /** * If the boundary line consists of the boundary and "--" then there are no more individual * responses left to be parsed and the input stream is closed. */ private void checkForFinalBoundary(String boundaryLine) throws IOException { if (boundaryLine.equals(boundary + "--")) { hasNext = false; bufferedReader.close(); } } private static class FakeResponseHttpTransport extends HttpTransport { private int statusCode; private String partContent; private List<String> headerNames; private List<String> headerValues; FakeResponseHttpTransport( int statusCode, String partContent, List<String> headerNames, List<String> headerValues) { super(); this.statusCode = statusCode; this.partContent = partContent; this.headerNames = headerNames; this.headerValues = headerValues; } @Override protected LowLevelHttpRequest buildRequest(String method, String url) { return new FakeLowLevelHttpRequest(partContent, statusCode, headerNames, headerValues); } } private static class FakeLowLevelHttpRequest extends LowLevelHttpRequest { // TODO(rmistry): Read in partContent as bytes instead of String for efficiency. private String partContent; private int statusCode; private List<String> headerNames; private List<String> headerValues; FakeLowLevelHttpRequest( String partContent, int statusCode, List<String> headerNames, List<String> headerValues) { this.partContent = partContent; this.statusCode = statusCode; this.headerNames = headerNames; this.headerValues = headerValues; } @Override public void addHeader(String name, String value) { } @Override public LowLevelHttpResponse execute() { FakeLowLevelHttpResponse response = new FakeLowLevelHttpResponse(new ByteArrayInputStream( StringUtils.getBytesUtf8(partContent)), statusCode, headerNames, headerValues); return response; } } private static class FakeLowLevelHttpResponse extends LowLevelHttpResponse { private InputStream partContent; private int statusCode; private List<String> headerNames = new ArrayList<String>(); private List<String> headerValues = new ArrayList<String>(); FakeLowLevelHttpResponse(InputStream partContent, int statusCode, List<String> headerNames, List<String> headerValues) { this.partContent = partContent; this.statusCode = statusCode; this.headerNames = headerNames; this.headerValues = headerValues; } @Override public InputStream getContent() { return partContent; } @Override public int getStatusCode() { return statusCode; } @Override public String getContentEncoding() { return null; } @Override public long getContentLength() { return 0; } @Override public String getContentType() { return null; } @Override public String getStatusLine() { return null; } @Override public String getReasonPhrase() { return null; } @Override public int getHeaderCount() { return headerNames.size(); } @Override public String getHeaderName(int index) { return headerNames.get(index); } @Override public String getHeaderValue(int index) { return headerValues.get(index); } } }
Java
/* * Copyright (c) 2010 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 com.google.api.client.googleapis.auth.clientlogin; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.UrlEncodedContent; import com.google.api.client.util.Beta; import com.google.api.client.util.Key; import com.google.api.client.util.StringUtils; import com.google.api.client.util.Strings; import java.io.IOException; /** * {@link Beta} <br/> * Client Login authentication method as described in <a * href="http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html" >ClientLogin for * Installed Applications</a>. * * @since 1.0 * @author Yaniv Inbar */ @Beta public final class ClientLogin { /** * HTTP transport required for executing request in {@link #authenticate()}. * * @since 1.3 */ public HttpTransport transport; /** * URL for the Client Login authorization server. * * <p> * By default this is {@code "https://www.google.com"}, but it may be overridden for testing * purposes. * </p> * * @since 1.3 */ public GenericUrl serverUrl = new GenericUrl("https://www.google.com"); /** * Short string identifying your application for logging purposes of the form: * "companyName-applicationName-versionID". */ @Key("source") public String applicationName; /** * Name of the Google service you're requesting authorization for, for example {@code "cl"} for * Google Calendar. */ @Key("service") public String authTokenType; /** User's full email address. */ @Key("Email") public String username; /** User's password. */ @Key("Passwd") public String password; /** * Type of account to request authorization for. Possible values are: * * <ul> * <li>GOOGLE (get authorization for a Google account only)</li> * <li>HOSTED (get authorization for a hosted account only)</li> * <li>HOSTED_OR_GOOGLE (get authorization first for a hosted account; if attempt fails, get * authorization for a Google account)</li> * </ul> * * Use HOSTED_OR_GOOGLE if you're not sure which type of account you want authorization for. If * the user information matches both a hosted and a Google account, only the hosted account is * authorized. * * @since 1.1 */ @Key public String accountType; /** (optional) Token representing the specific CAPTCHA challenge. */ @Key("logintoken") public String captchaToken; /** (optional) String entered by the user as an answer to a CAPTCHA challenge. */ @Key("logincaptcha") public String captchaAnswer; /** * Key/value data to parse a success response. * * <p> * Sample usage, taking advantage that this class implements {@link HttpRequestInitializer}: * </p> * * <pre> public static HttpRequestFactory createRequestFactory( HttpTransport transport, Response response) { return transport.createRequestFactory(response); } * </pre> * * <p> * If you have a custom request initializer, take a look at the sample usage for * {@link HttpExecuteInterceptor}, which this class also implements. * </p> */ public static final class Response implements HttpExecuteInterceptor, HttpRequestInitializer { /** Authentication token. */ @Key("Auth") public String auth; /** Returns the authorization header value to use based on the authentication token. */ public String getAuthorizationHeaderValue() { return ClientLogin.getAuthorizationHeaderValue(auth); } public void initialize(HttpRequest request) { request.setInterceptor(this); } public void intercept(HttpRequest request) { request.getHeaders().setAuthorization(getAuthorizationHeaderValue()); } } /** Key/value data to parse an error response. */ public static final class ErrorInfo { @Key("Error") public String error; @Key("Url") public String url; @Key("CaptchaToken") public String captchaToken; @Key("CaptchaUrl") public String captchaUrl; } /** * Authenticates based on the provided field values. * * @throws ClientLoginResponseException if the authentication response has an error code, such as * for a CAPTCHA challenge. */ public Response authenticate() throws IOException { GenericUrl url = serverUrl.clone(); url.appendRawPath("/accounts/ClientLogin"); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new UrlEncodedContent(this)); request.setParser(AuthKeyValueParser.INSTANCE); request.setContentLoggingLimit(0); request.setThrowExceptionOnExecuteError(false); HttpResponse response = request.execute(); // check for an HTTP success response (2xx) if (response.isSuccessStatusCode()) { return response.parseAs(Response.class); } HttpResponseException.Builder builder = new HttpResponseException.Builder( response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); // On error, throw a ClientLoginResponseException with the parsed error details ErrorInfo details = response.parseAs(ErrorInfo.class); String detailString = details.toString(); StringBuilder message = HttpResponseException.computeMessageBuffer(response); if (!Strings.isNullOrEmpty(detailString)) { message.append(StringUtils.LINE_SEPARATOR).append(detailString); builder.setContent(detailString); } builder.setMessage(message.toString()); throw new ClientLoginResponseException(builder, details); } /** * Returns Google Login {@code "Authorization"} header value based on the given authentication * token. * * @since 1.13 */ public static String getAuthorizationHeaderValue(String authToken) { return "GoogleLogin auth=" + authToken; } }
Java
/* * Copyright (c) 2010 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. */ /** * {@link com.google.api.client.util.Beta} <br/> * Google's legacy ClientLogin authentication method as described in <a * href="http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html">ClientLogin for * Installed Applications</a>. * * @since 1.0 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.auth.clientlogin;
Java
/* * Copyright (c) 2010 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 com.google.api.client.googleapis.auth.clientlogin; import com.google.api.client.http.HttpResponse; import com.google.api.client.util.Beta; import com.google.api.client.util.ClassInfo; import com.google.api.client.util.FieldInfo; import com.google.api.client.util.GenericData; import com.google.api.client.util.ObjectParser; import com.google.api.client.util.Types; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.util.Map; /** * {@link Beta} <br/> * HTTP parser for Google response to an Authorization request. * * @since 1.10 * @author Yaniv Inbar */ @Beta final class AuthKeyValueParser implements ObjectParser { /** Singleton instance. */ public static final AuthKeyValueParser INSTANCE = new AuthKeyValueParser(); public String getContentType() { return "text/plain"; } public <T> T parse(HttpResponse response, Class<T> dataClass) throws IOException { response.setContentLoggingLimit(0); InputStream content = response.getContent(); try { return parse(content, dataClass); } finally { content.close(); } } public <T> T parse(InputStream content, Class<T> dataClass) throws IOException { ClassInfo classInfo = ClassInfo.of(dataClass); T newInstance = Types.newInstance(dataClass); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); while (true) { String line = reader.readLine(); if (line == null) { break; } int equals = line.indexOf('='); String key = line.substring(0, equals); String value = line.substring(equals + 1); // get the field from the type information Field field = classInfo.getField(key); if (field != null) { Class<?> fieldClass = field.getType(); Object fieldValue; if (fieldClass == boolean.class || fieldClass == Boolean.class) { fieldValue = Boolean.valueOf(value); } else { fieldValue = value; } FieldInfo.setFieldValue(field, newInstance, fieldValue); } else if (GenericData.class.isAssignableFrom(dataClass)) { GenericData data = (GenericData) newInstance; data.set(key, value); } else if (Map.class.isAssignableFrom(dataClass)) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) newInstance; map.put(key, value); } } return newInstance; } private AuthKeyValueParser() { } public <T> T parseAndClose(InputStream in, Charset charset, Class<T> dataClass) throws IOException { Reader reader = new InputStreamReader(in, charset); return parseAndClose(reader, dataClass); } public Object parseAndClose(InputStream in, Charset charset, Type dataType) { throw new UnsupportedOperationException( "Type-based parsing is not yet supported -- use Class<T> instead"); } public <T> T parseAndClose(Reader reader, Class<T> dataClass) throws IOException { try { ClassInfo classInfo = ClassInfo.of(dataClass); T newInstance = Types.newInstance(dataClass); BufferedReader breader = new BufferedReader(reader); while (true) { String line = breader.readLine(); if (line == null) { break; } int equals = line.indexOf('='); String key = line.substring(0, equals); String value = line.substring(equals + 1); // get the field from the type information Field field = classInfo.getField(key); if (field != null) { Class<?> fieldClass = field.getType(); Object fieldValue; if (fieldClass == boolean.class || fieldClass == Boolean.class) { fieldValue = Boolean.valueOf(value); } else { fieldValue = value; } FieldInfo.setFieldValue(field, newInstance, fieldValue); } else if (GenericData.class.isAssignableFrom(dataClass)) { GenericData data = (GenericData) newInstance; data.set(key, value); } else if (Map.class.isAssignableFrom(dataClass)) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) newInstance; map.put(key, value); } } return newInstance; } finally { reader.close(); } } public Object parseAndClose(Reader reader, Type dataType) { throw new UnsupportedOperationException( "Type-based parsing is not yet supported -- use Class<T> instead"); } }
Java
/* * Copyright (c) 2011 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 com.google.api.client.googleapis.auth.clientlogin; import com.google.api.client.googleapis.auth.clientlogin.ClientLogin.ErrorInfo; import com.google.api.client.http.HttpResponseException; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Exception thrown when an error status code is detected in an HTTP response to a Google * ClientLogin request in {@link ClientLogin} . * * <p> * To get the structured details, use {@link #getDetails()}. * </p> * * @since 1.7 * @author Yaniv Inbar */ @Beta public class ClientLoginResponseException extends HttpResponseException { private static final long serialVersionUID = 4974317674023010928L; /** Error details or {@code null} for none. */ private final transient ErrorInfo details; /** * @param builder builder * @param details error details or {@code null} for none */ ClientLoginResponseException(Builder builder, ErrorInfo details) { super(builder); this.details = details; } /** Return the error details or {@code null} for none. */ public final ErrorInfo getDetails() { return details; } }
Java
/* * Copyright (c) 2011 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.util.Beta; /** * Constants for Google's OAuth 2.0 implementation. * * @since 1.7 * @author Yaniv Inbar */ public class GoogleOAuthConstants { /** Encoded URL of Google's end-user authorization server. */ public static final String AUTHORIZATION_SERVER_URL = "https://accounts.google.com/o/oauth2/auth"; /** Encoded URL of Google's token server. */ public static final String TOKEN_SERVER_URL = "https://accounts.google.com/o/oauth2/token"; /** * {@link Beta} <br/> * Encoded URL of Google's public certificates. * * @since 1.15 */ @Beta public static final String DEFAULT_PUBLIC_CERTS_ENCODED_URL = "https://www.googleapis.com/oauth2/v1/certs"; /** * Redirect URI to use for an installed application as specified in <a * href="http://code.google.com/apis/accounts/docs/OAuth2InstalledApp.html">Using OAuth 2.0 for * Installed Applications</a>. */ public static final String OOB_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"; private GoogleOAuthConstants() { } }
Java
/* * Copyright (c) 2013 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonParser; import com.google.api.client.json.JsonToken; import com.google.api.client.util.Beta; import com.google.api.client.util.Clock; import com.google.api.client.util.Preconditions; import com.google.api.client.util.SecurityUtils; import com.google.api.client.util.StringUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PublicKey; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * {@link Beta} <br/> * Thread-safe Google public keys manager. * * <p> * The public keys are loaded from the public certificates endpoint at * {@link #getPublicCertsEncodedUrl} and cached in this instance. Therefore, for maximum efficiency, * applications should use a single globally-shared instance of the {@link GooglePublicKeysManager}. * </p> * * @since 1.17 */ @Beta public class GooglePublicKeysManager { /** Number of milliseconds before expiration time to force a refresh. */ private static final long REFRESH_SKEW_MILLIS = 300000; /** Pattern for the max-age header element of Cache-Control. */ private static final Pattern MAX_AGE_PATTERN = Pattern.compile("\\s*max-age\\s*=\\s*(\\d+)\\s*"); /** JSON factory. */ private final JsonFactory jsonFactory; /** Unmodifiable view of the public keys or {@code null} for none. */ private List<PublicKey> publicKeys; /** * Expiration time in milliseconds to be used with {@link Clock#currentTimeMillis()} or {@code 0} * for none. */ private long expirationTimeMilliseconds; /** HTTP transport. */ private final HttpTransport transport; /** Lock on the public keys. */ private final Lock lock = new ReentrantLock(); /** Clock to use for expiration checks. */ private final Clock clock; /** Public certificates encoded URL. */ private final String publicCertsEncodedUrl; /** * @param transport HTTP transport * @param jsonFactory JSON factory */ public GooglePublicKeysManager(HttpTransport transport, JsonFactory jsonFactory) { this(new Builder(transport, jsonFactory)); } /** * @param builder builder */ protected GooglePublicKeysManager(Builder builder) { transport = builder.transport; jsonFactory = builder.jsonFactory; clock = builder.clock; publicCertsEncodedUrl = builder.publicCertsEncodedUrl; } /** Returns the HTTP transport. */ public final HttpTransport getTransport() { return transport; } /** Returns the JSON factory. */ public final JsonFactory getJsonFactory() { return jsonFactory; } /** Returns the public certificates encoded URL. */ public final String getPublicCertsEncodedUrl() { return publicCertsEncodedUrl; } /** Returns the clock. */ public final Clock getClock() { return clock; } /** * Returns an unmodifiable view of the public keys. * * <p> * For efficiency, an in-memory cache of the public keys is used here. If this method is called * for the first time, or the certificates have expired since last time it has been called (or are * within 5 minutes of expiring), {@link #refresh()} will be called before returning the value. * </p> */ public final List<PublicKey> getPublicKeys() throws GeneralSecurityException, IOException { lock.lock(); try { if (publicKeys == null || clock.currentTimeMillis() + REFRESH_SKEW_MILLIS > expirationTimeMilliseconds) { refresh(); } return publicKeys; } finally { lock.unlock(); } } /** * Returns the expiration time in milliseconds to be used with {@link Clock#currentTimeMillis()} * or {@code 0} for none. */ public final long getExpirationTimeMilliseconds() { return expirationTimeMilliseconds; } /** * Forces a refresh of the public certificates downloaded from {@link #getPublicCertsEncodedUrl}. * * <p> * This method is automatically called from {@link #getPublicKeys()} if the public keys have not * yet been initialized or if the expiration time is very close, so normally this doesn't need to * be called. Only call this method to explicitly force the public keys to be updated. * </p> */ public GooglePublicKeysManager refresh() throws GeneralSecurityException, IOException { lock.lock(); try { publicKeys = new ArrayList<PublicKey>(); // HTTP request to public endpoint CertificateFactory factory = SecurityUtils.getX509CertificateFactory(); HttpResponse certsResponse = transport.createRequestFactory() .buildGetRequest(new GenericUrl(publicCertsEncodedUrl)).execute(); expirationTimeMilliseconds = clock.currentTimeMillis() + getCacheTimeInSec(certsResponse.getHeaders()) * 1000; // parse each public key in the JSON response JsonParser parser = jsonFactory.createJsonParser(certsResponse.getContent()); JsonToken currentToken = parser.getCurrentToken(); // token is null at start, so get next token if (currentToken == null) { currentToken = parser.nextToken(); } Preconditions.checkArgument(currentToken == JsonToken.START_OBJECT); try { while (parser.nextToken() != JsonToken.END_OBJECT) { parser.nextToken(); String certValue = parser.getText(); X509Certificate x509Cert = (X509Certificate) factory.generateCertificate( new ByteArrayInputStream(StringUtils.getBytesUtf8(certValue))); publicKeys.add(x509Cert.getPublicKey()); } publicKeys = Collections.unmodifiableList(publicKeys); } finally { parser.close(); } return this; } finally { lock.unlock(); } } /** * Gets the cache time in seconds. "max-age" in "Cache-Control" header and "Age" header are * considered. * * @param httpHeaders the http header of the response * @return the cache time in seconds or zero if the response should not be cached */ long getCacheTimeInSec(HttpHeaders httpHeaders) { long cacheTimeInSec = 0; if (httpHeaders.getCacheControl() != null) { for (String arg : httpHeaders.getCacheControl().split(",")) { Matcher m = MAX_AGE_PATTERN.matcher(arg); if (m.matches()) { cacheTimeInSec = Long.valueOf(m.group(1)); break; } } } if (httpHeaders.getAge() != null) { cacheTimeInSec -= httpHeaders.getAge(); } return Math.max(0, cacheTimeInSec); } /** * {@link Beta} <br/> * Builder for {@link GooglePublicKeysManager}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.17 */ @Beta public static class Builder { /** Clock. */ Clock clock = Clock.SYSTEM; /** HTTP transport. */ final HttpTransport transport; /** JSON factory. */ final JsonFactory jsonFactory; /** Public certificates encoded URL. */ String publicCertsEncodedUrl = GoogleOAuthConstants.DEFAULT_PUBLIC_CERTS_ENCODED_URL; /** * Returns an instance of a new builder. * * @param transport HTTP transport * @param jsonFactory JSON factory */ public Builder(HttpTransport transport, JsonFactory jsonFactory) { this.transport = Preconditions.checkNotNull(transport); this.jsonFactory = Preconditions.checkNotNull(jsonFactory); } /** Builds a new instance of {@link GooglePublicKeysManager}. */ public GooglePublicKeysManager build() { return new GooglePublicKeysManager(this); } /** Returns the HTTP transport. */ public final HttpTransport getTransport() { return transport; } /** Returns the JSON factory. */ public final JsonFactory getJsonFactory() { return jsonFactory; } /** Returns the public certificates encoded URL. */ public final String getPublicCertsEncodedUrl() { return publicCertsEncodedUrl; } /** * Sets the public certificates encoded URL. * * <p> * The default value is {@link GoogleOAuthConstants#DEFAULT_PUBLIC_CERTS_ENCODED_URL}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setPublicCertsEncodedUrl(String publicCertsEncodedUrl) { this.publicCertsEncodedUrl = Preconditions.checkNotNull(publicCertsEncodedUrl); return this; } /** Returns the clock. */ public final Clock getClock() { return clock; } /** * Sets the clock. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setClock(Clock clock) { this.clock = Preconditions.checkNotNull(clock); return this; } } }
Java
/* * Copyright (c) 2011 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.BearerToken; import com.google.api.client.auth.oauth2.ClientParametersAuthentication; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.auth.oauth2.CredentialRefreshListener; import com.google.api.client.auth.oauth2.DataStoreCredentialRefreshListener; import com.google.api.client.auth.oauth2.TokenRequest; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.googleapis.GoogleUtils; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.Details; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import com.google.api.client.json.webtoken.JsonWebSignature; import com.google.api.client.json.webtoken.JsonWebToken; import com.google.api.client.util.Beta; import com.google.api.client.util.Clock; import com.google.api.client.util.Joiner; import com.google.api.client.util.PemReader; import com.google.api.client.util.PemReader.Section; import com.google.api.client.util.Preconditions; import com.google.api.client.util.SecurityUtils; import com.google.api.client.util.store.DataStoreFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Collection; import java.util.Collections; /** * Thread-safe Google-specific implementation of the OAuth 2.0 helper for accessing protected * resources using an access token, as well as optionally refreshing the access token when it * expires using a refresh token. * * <p> * There are three modes supported: access token only, refresh token flow, and service account flow * (with or without impersonating a user). * </p> * * <p> * If all you have is an access token, you simply pass the {@link TokenResponse} to the credential * using {@link Builder#setFromTokenResponse(TokenResponse)}. Google credential uses * {@link BearerToken#authorizationHeaderAccessMethod()} as the access method. Sample usage: * </p> * * <pre> public static GoogleCredential createCredentialWithAccessTokenOnly(TokenResponse tokenResponse) { return new GoogleCredential().setFromTokenResponse(tokenResponse); } * </pre> * * <p> * If you have a refresh token, it is similar to the case of access token only, but you additionally * need to pass the credential the client secrets using * {@link Builder#setClientSecrets(GoogleClientSecrets)} or * {@link Builder#setClientSecrets(String, String)}. Google credential uses * {@link GoogleOAuthConstants#TOKEN_SERVER_URL} as the token server URL, and * {@link ClientParametersAuthentication} with the client ID and secret as the client * authentication. Sample usage: * </p> * * <pre> public static GoogleCredential createCredentialWithRefreshToken(HttpTransport transport, JsonFactory jsonFactory, GoogleClientSecrets clientSecrets, TokenResponse tokenResponse) { return new GoogleCredential.Builder().setTransport(transport) .setJsonFactory(jsonFactory) .setClientSecrets(clientSecrets) .build() .setFromTokenResponse(tokenResponse); } * </pre> * * <p> * The <a href="https://developers.google.com/accounts/docs/OAuth2ServiceAccount">service account * flow</a> is used when you want to access data owned by your client application. You download the * private key in a {@code .p12} file from the Google APIs Console. Use * {@link Builder#setServiceAccountId(String)}, * {@link Builder#setServiceAccountPrivateKeyFromP12File(File)}, and * {@link Builder#setServiceAccountScopes(Collection)}. Sample usage: * </p> * * <pre> public static GoogleCredential createCredentialForServiceAccount( HttpTransport transport, JsonFactory jsonFactory, String serviceAccountId, Collection&lt;String&gt; serviceAccountScopes, File p12File) throws GeneralSecurityException, IOException { return new GoogleCredential.Builder().setTransport(transport) .setJsonFactory(jsonFactory) .setServiceAccountId(serviceAccountId) .setServiceAccountScopes(serviceAccountScopes) .setServiceAccountPrivateKeyFromP12File(p12File) .build(); } * </pre> * * <p> * You can also use the service account flow to impersonate a user in a domain that you own. This is * very similar to the service account flow above, but you additionally call * {@link Builder#setServiceAccountUser(String)}. Sample usage: * </p> * * <pre> public static GoogleCredential createCredentialForServiceAccountImpersonateUser( HttpTransport transport, JsonFactory jsonFactory, String serviceAccountId, Collection&lt;String&gt; serviceAccountScopes, File p12File, String serviceAccountUser) throws GeneralSecurityException, IOException { return new GoogleCredential.Builder().setTransport(transport) .setJsonFactory(jsonFactory) .setServiceAccountId(serviceAccountId) .setServiceAccountScopes(serviceAccountScopes) .setServiceAccountPrivateKeyFromP12File(p12File) .setServiceAccountUser(serviceAccountUser) .build(); } * </pre> * * <p> * If you need to persist the access token in a data store, use {@link DataStoreFactory} and * {@link Builder#addRefreshListener(CredentialRefreshListener)} with * {@link DataStoreCredentialRefreshListener}. * </p> * * <p> * If you have a custom request initializer, request execute interceptor, or unsuccessful response * handler, take a look at the sample usage for {@link HttpExecuteInterceptor} and * {@link HttpUnsuccessfulResponseHandler}, which are interfaces that this class also implements. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleCredential extends Credential { static final String USER_FILE_TYPE = "authorized_user"; static final String SERVICE_ACCOUNT_FILE_TYPE = "service_account"; @Beta private static DefaultCredentialProvider defaultCredentialProvider = new DefaultCredentialProvider(); /** * {@link Beta} <br/> * Returns a default credential for the application. * * <p>Returns the built-in service account's credential for the application if running on * Google App Engine or Google Compute Engine, or returns the credential pointed to by the * environment variable GOOGLE_CREDENTIALS_DEFAULT. * </p> * * @return the credential instance. * @throws IOException if the credential cannot be created in the current environment. */ @Beta public static GoogleCredential getDefault() throws IOException { return getDefault(GoogleUtils.getDefaultTransport(), GoogleUtils.getDefaultJsonFactory()); } /** * {@link Beta} <br/> * Returns a default credential for the application. * * <p>Returns the built-in service account's credential for the application if running on * Google App Engine or Google Compute Engine, or returns the credential pointed to by the * environment variable GOOGLE_CREDENTIALS_DEFAULT. * </p> * * @param transport the transport for Http calls. * @param jsonFactory the factory for Json parsing and formatting. * @return the credential instance. * @throws IOException if the credential cannot be created in the current environment. */ @Beta public static GoogleCredential getDefault(HttpTransport transport, JsonFactory jsonFactory) throws IOException { Preconditions.checkNotNull(transport); Preconditions.checkNotNull(jsonFactory); return defaultCredentialProvider.getDefaultCredential(transport, jsonFactory); } /** * {@link Beta} <br/> * Return a credential defined by a Json file. * * @param credentialStream the stream with the credential definition. * @return the credential defined by the credentialStream. * @throws IOException if the credential cannot be created from the stream. */ @Beta public static GoogleCredential fromStream(InputStream credentialStream) throws IOException { return fromStream( credentialStream, GoogleUtils.getDefaultTransport(), GoogleUtils.getDefaultJsonFactory()); } /** * {@link Beta} <br/> * Return a credential defined by a Json file. * * @param credentialStream the stream with the credential definition. * @param transport the transport for Http calls. * @param jsonFactory the factory for Json parsing and formatting. * @return the credential defined by the credentialStream. * @throws IOException if the credential cannot be created from the stream. */ @Beta public static GoogleCredential fromStream(InputStream credentialStream, HttpTransport transport, JsonFactory jsonFactory) throws IOException { Preconditions.checkNotNull(credentialStream); Preconditions.checkNotNull(transport); Preconditions.checkNotNull(jsonFactory); JsonObjectParser parser = new JsonObjectParser(jsonFactory); GenericJson fileContents = parser.parseAndClose( credentialStream, OAuth2Utils.UTF_8, GenericJson.class); String fileType = (String) fileContents.get("type"); if (fileType == null) { throw new IOException("Error reading credentials from stream, 'type' field not specified."); } if (USER_FILE_TYPE.equals(fileType)) { return fromStreamUser(fileContents, transport, jsonFactory); } if (SERVICE_ACCOUNT_FILE_TYPE.equals(fileType)) { return fromStreamServiceAccount(fileContents, transport, jsonFactory); } throw new IOException(String.format( "Error reading credentials from stream, 'type' value '%s' not recognized." + " Expecting '%s' or '%s'.", fileType, USER_FILE_TYPE, SERVICE_ACCOUNT_FILE_TYPE)); } /** * Service account ID (typically an e-mail address) or {@code null} if not using the service * account flow. */ private String serviceAccountId; /** * Collection of OAuth scopes to use with the the service account flow or {@code null} if not * using the service account flow. */ private Collection<String> serviceAccountScopes; /** * Private key to use with the the service account flow or {@code null} if not using the service * account flow. */ private PrivateKey serviceAccountPrivateKey; /** * Email address of the user the application is trying to impersonate in the service account flow * or {@code null} for none or if not using the service account flow. */ private String serviceAccountUser; /** * Constructor with the ability to access protected resources, but not refresh tokens. * * <p> * To use with the ability to refresh tokens, use {@link Builder}. * </p> */ public GoogleCredential() { this(new Builder()); } /** * @param builder Google credential builder * * @since 1.14 */ protected GoogleCredential(Builder builder) { super(builder); if (builder.serviceAccountPrivateKey == null) { Preconditions.checkArgument(builder.serviceAccountId == null && builder.serviceAccountScopes == null && builder.serviceAccountUser == null); } else { serviceAccountId = Preconditions.checkNotNull(builder.serviceAccountId); serviceAccountScopes = Collections.unmodifiableCollection(builder.serviceAccountScopes); serviceAccountPrivateKey = builder.serviceAccountPrivateKey; serviceAccountUser = builder.serviceAccountUser; } } @Override public GoogleCredential setAccessToken(String accessToken) { return (GoogleCredential) super.setAccessToken(accessToken); } @Override public GoogleCredential setRefreshToken(String refreshToken) { if (refreshToken != null) { Preconditions.checkArgument( getJsonFactory() != null && getTransport() != null && getClientAuthentication() != null, "Please use the Builder and call setJsonFactory, setTransport and setClientSecrets"); } return (GoogleCredential) super.setRefreshToken(refreshToken); } @Override public GoogleCredential setExpirationTimeMilliseconds(Long expirationTimeMilliseconds) { return (GoogleCredential) super.setExpirationTimeMilliseconds(expirationTimeMilliseconds); } @Override public GoogleCredential setExpiresInSeconds(Long expiresIn) { return (GoogleCredential) super.setExpiresInSeconds(expiresIn); } @Override public GoogleCredential setFromTokenResponse(TokenResponse tokenResponse) { return (GoogleCredential) super.setFromTokenResponse(tokenResponse); } @Override @Beta protected TokenResponse executeRefreshToken() throws IOException { if (serviceAccountPrivateKey == null) { return super.executeRefreshToken(); } // service accounts: no refresh token; instead use private key to request new access token JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); JsonWebToken.Payload payload = new JsonWebToken.Payload(); long currentTime = getClock().currentTimeMillis(); payload.setIssuer(serviceAccountId); payload.setAudience(getTokenServerEncodedUrl()); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + 3600); payload.setSubject(serviceAccountUser); payload.put("scope", Joiner.on(' ').join(serviceAccountScopes)); try { String assertion = JsonWebSignature.signUsingRsaSha256( serviceAccountPrivateKey, getJsonFactory(), header, payload); TokenRequest request = new TokenRequest( getTransport(), getJsonFactory(), new GenericUrl(getTokenServerEncodedUrl()), "urn:ietf:params:oauth:grant-type:jwt-bearer"); request.put("assertion", assertion); return request.execute(); } catch (GeneralSecurityException exception) { IOException e = new IOException(); e.initCause(exception); throw e; } } /** * {@link Beta} <br/> * Returns the service account ID (typically an e-mail address) or {@code null} if not using the * service account flow. */ @Beta public final String getServiceAccountId() { return serviceAccountId; } /** * {@link Beta} <br/> * Returns a collection of OAuth scopes to use with the the service account flow or {@code null} * if not using the service account flow. */ @Beta public final Collection<String> getServiceAccountScopes() { return serviceAccountScopes; } /** * {@link Beta} <br/> * Returns the space-separated OAuth scopes to use with the the service account flow or * {@code null} if not using the service account flow. * * @since 1.15 */ @Beta public final String getServiceAccountScopesAsString() { return serviceAccountScopes == null ? null : Joiner.on(' ').join(serviceAccountScopes); } /** * {@link Beta} <br/> * Returns the private key to use with the the service account flow or {@code null} if not using * the service account flow. */ @Beta public final PrivateKey getServiceAccountPrivateKey() { return serviceAccountPrivateKey; } /** * {@link Beta} <br/> * Returns the email address of the user the application is trying to impersonate in the service * account flow or {@code null} for none or if not using the service account flow. */ @Beta public final String getServiceAccountUser() { return serviceAccountUser; } /** * {@link Beta} <br/> * Indicates whether the credential requires scopes to be specified by calling createScoped * before use. */ @Beta public boolean createScopedRequired() { if (serviceAccountPrivateKey == null) { return false; } return (serviceAccountScopes == null || serviceAccountScopes.isEmpty()); } /** * {@link Beta} <br/> * For credentials that require scopes, creates a copy of the credential with the specified * scopes. */ @Beta public GoogleCredential createScoped(Collection<String> scopes) { if (serviceAccountPrivateKey == null) { return this; } return new GoogleCredential.Builder() .setServiceAccountPrivateKey(serviceAccountPrivateKey) .setServiceAccountId(serviceAccountId) .setServiceAccountUser(serviceAccountUser) .setServiceAccountScopes(scopes) .setTransport(getTransport()) .setJsonFactory(getJsonFactory()) .setClock(getClock()) .build(); } /** * Google credential builder. * * <p> * Implementation is not thread-safe. * </p> */ public static class Builder extends Credential.Builder { /** Service account ID (typically an e-mail address) or {@code null} for none. */ String serviceAccountId; /** * Collection of OAuth scopes to use with the the service account flow or {@code null} for none. */ Collection<String> serviceAccountScopes; /** Private key to use with the the service account flow or {@code null} for none. */ PrivateKey serviceAccountPrivateKey; /** * Email address of the user the application is trying to impersonate in the service account * flow or {@code null} for none. */ String serviceAccountUser; public Builder() { super(BearerToken.authorizationHeaderAccessMethod()); setTokenServerEncodedUrl(GoogleOAuthConstants.TOKEN_SERVER_URL); } @Override public GoogleCredential build() { return new GoogleCredential(this); } @Override public Builder setTransport(HttpTransport transport) { return (Builder) super.setTransport(transport); } @Override public Builder setJsonFactory(JsonFactory jsonFactory) { return (Builder) super.setJsonFactory(jsonFactory); } /** * @since 1.9 */ @Override public Builder setClock(Clock clock) { return (Builder) super.setClock(clock); } /** * Sets the client identifier and secret. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setClientSecrets(String clientId, String clientSecret) { setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret)); return this; } /** * Sets the client secrets. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setClientSecrets(GoogleClientSecrets clientSecrets) { Details details = clientSecrets.getDetails(); setClientAuthentication( new ClientParametersAuthentication(details.getClientId(), details.getClientSecret())); return this; } /** * {@link Beta} <br/> * Returns the service account ID (typically an e-mail address) or {@code null} for none. */ @Beta public final String getServiceAccountId() { return serviceAccountId; } /** * {@link Beta} <br/> * Sets the service account ID (typically an e-mail address) or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ @Beta public Builder setServiceAccountId(String serviceAccountId) { this.serviceAccountId = serviceAccountId; return this; } /** * {@link Beta} <br/> * Returns a collection of OAuth scopes to use with the the service account flow or {@code null} * for none. */ @Beta public final Collection<String> getServiceAccountScopes() { return serviceAccountScopes; } /** * {@link Beta} <br/> * Sets the space-separated OAuth scopes to use with the the service account flow or * {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param serviceAccountScopes collection of scopes to be joined by a space separator (or a * single value containing multiple space-separated scopes) * @since 1.15 */ @Beta public Builder setServiceAccountScopes(Collection<String> serviceAccountScopes) { this.serviceAccountScopes = serviceAccountScopes; return this; } /** * {@link Beta} <br/> * Returns the private key to use with the the service account flow or {@code null} for none. */ @Beta public final PrivateKey getServiceAccountPrivateKey() { return serviceAccountPrivateKey; } /** * {@link Beta} <br/> * Sets the private key to use with the the service account flow or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ @Beta public Builder setServiceAccountPrivateKey(PrivateKey serviceAccountPrivateKey) { this.serviceAccountPrivateKey = serviceAccountPrivateKey; return this; } /** * {@link Beta} <br/> * Sets the private key to use with the the service account flow or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param p12File input stream to the p12 file (closed at the end of this method in a finally * block) */ @Beta public Builder setServiceAccountPrivateKeyFromP12File(File p12File) throws GeneralSecurityException, IOException { serviceAccountPrivateKey = SecurityUtils.loadPrivateKeyFromKeyStore( SecurityUtils.getPkcs12KeyStore(), new FileInputStream(p12File), "notasecret", "privatekey", "notasecret"); return this; } /** * {@link Beta} <br/> * Sets the private key to use with the the service account flow or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @param pemFile input stream to the PEM file (closed at the end of this method in a finally * block) * @since 1.13 */ @Beta public Builder setServiceAccountPrivateKeyFromPemFile(File pemFile) throws GeneralSecurityException, IOException { byte[] bytes = PemReader.readFirstSectionAndClose(new FileReader(pemFile), "PRIVATE KEY") .getBase64DecodedBytes(); serviceAccountPrivateKey = SecurityUtils.getRsaKeyFactory().generatePrivate(new PKCS8EncodedKeySpec(bytes)); return this; } /** * {@link Beta} <br/> * Returns the email address of the user the application is trying to impersonate in the service * account flow or {@code null} for none. */ @Beta public final String getServiceAccountUser() { return serviceAccountUser; } /** * {@link Beta} <br/> * Sets the email address of the user the application is trying to impersonate in the service * account flow or {@code null} for none. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ @Beta public Builder setServiceAccountUser(String serviceAccountUser) { this.serviceAccountUser = serviceAccountUser; return this; } @Override public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) { return (Builder) super.setRequestInitializer(requestInitializer); } @Override public Builder addRefreshListener(CredentialRefreshListener refreshListener) { return (Builder) super.addRefreshListener(refreshListener); } @Override public Builder setRefreshListeners(Collection<CredentialRefreshListener> refreshListeners) { return (Builder) super.setRefreshListeners(refreshListeners); } @Override public Builder setTokenServerUrl(GenericUrl tokenServerUrl) { return (Builder) super.setTokenServerUrl(tokenServerUrl); } @Override public Builder setTokenServerEncodedUrl(String tokenServerEncodedUrl) { return (Builder) super.setTokenServerEncodedUrl(tokenServerEncodedUrl); } @Override public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { return (Builder) super.setClientAuthentication(clientAuthentication); } } @Beta private static GoogleCredential fromStreamUser(GenericJson fileContents, HttpTransport transport, JsonFactory jsonFactory) throws IOException { String clientId = (String) fileContents.get("client_id"); String clientSecret = (String) fileContents.get("client_secret"); String refreshToken = (String) fileContents.get("refresh_token"); if (clientId == null || clientSecret == null || refreshToken == null) { throw new IOException("Error reading user credential from stream, " + " expecting 'client_id', 'client_secret' and 'refresh_token'."); } GoogleCredential credential = new GoogleCredential.Builder() .setClientSecrets(clientId, clientSecret) .setTransport(transport) .setJsonFactory(jsonFactory) .build(); credential.setRefreshToken(refreshToken); // Do a refresh so we can fail early rather than return an unusable credential credential.refreshToken(); return credential; } @Beta private static GoogleCredential fromStreamServiceAccount(GenericJson fileContents, HttpTransport transport, JsonFactory jsonFactory) throws IOException { String clientId = (String) fileContents.get("client_id"); String clientEmail = (String) fileContents.get("client_email"); String privateKeyPem = (String) fileContents.get("private_key"); String privateKeyId = (String) fileContents.get("private_key_id"); if (clientId == null || clientEmail == null || privateKeyPem == null || privateKeyId == null) { throw new IOException("Error reading service account credential from stream, " + "expecting 'client_id', 'client_email', 'private_key' and 'private_key_id'."); } PrivateKey privateKey = privateKeyFromPkcs8(privateKeyPem); Collection<String> emptyScopes = Collections.emptyList(); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(transport) .setJsonFactory(jsonFactory) .setServiceAccountId(clientEmail) .setServiceAccountScopes(emptyScopes) .setServiceAccountPrivateKey(privateKey) .build(); // Don't do a refresh at this point, as it will always fail before the scopes are added. return credential; } @Beta private static PrivateKey privateKeyFromPkcs8(String privateKeyPem) throws IOException { Reader reader = new StringReader(privateKeyPem); Section section = PemReader.readFirstSectionAndClose(reader, "PRIVATE KEY"); if (section == null) { throw new IOException("Invalid PKCS8 data."); } byte[] bytes = section.getBase64DecodedBytes(); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); Exception unexpectedException = null; try { KeyFactory keyFactory = SecurityUtils.getRsaKeyFactory(); PrivateKey privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } catch (NoSuchAlgorithmException exception) { unexpectedException = exception; } catch (InvalidKeySpecException exception) { unexpectedException = exception; } throw OAuth2Utils.exceptionWithCause( new IOException("Unexpected exception reading PKCS data"), unexpectedException); } }
Java
/* * Copyright (c) 2011 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.BrowserClientRequestUrl; import com.google.api.client.util.Key; import com.google.api.client.util.Preconditions; import java.util.Collection; /** * Google-specific implementation of the OAuth 2.0 URL builder for an authorization web page to * allow the end user to authorize the application to access their protected resources and that * returns the access token to a browser client using a scripting language such as JavaScript, as * specified in <a href="https://developers.google.com/accounts/docs/OAuth2UserAgent">Using OAuth * 2.0 for Client-side Applications</a>. * * <p> * The default for {@link #getResponseTypes()} is {@code "token"}. * </p> * * <p> * Sample usage for a web application: * </p> * * <pre> public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String url = new GoogleBrowserClientRequestUrl("812741506391.apps.googleusercontent.com", "https://oauth2-login-demo.appspot.com/oauthcallback", Arrays.asList( "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile")).setState("/profile").build(); response.sendRedirect(url); } * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleBrowserClientRequestUrl extends BrowserClientRequestUrl { /** * Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to * force the approval UI to show) or {@code null} for the default behavior. */ @Key("approval_prompt") private String approvalPrompt; /** * @param clientId client identifier * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Collection)}) * * @since 1.15 */ public GoogleBrowserClientRequestUrl( String clientId, String redirectUri, Collection<String> scopes) { super(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId); setRedirectUri(redirectUri); setScopes(scopes); } /** * @param clientSecrets OAuth 2.0 client secrets JSON model as specified in <a * href="http://code.google.com/p/google-api-python-client/wiki/ClientSecrets"> * client_secrets.json file format</a> * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Collection)}) * * @since 1.15 */ public GoogleBrowserClientRequestUrl( GoogleClientSecrets clientSecrets, String redirectUri, Collection<String> scopes) { this(clientSecrets.getDetails().getClientId(), redirectUri, scopes); } /** * Returns the approval prompt behavior ({@code "auto"} to request auto-approval or * {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of * {@code "auto"}. */ public final String getApprovalPrompt() { return approvalPrompt; } /** * Sets the approval prompt behavior ({@code "auto"} to request auto-approval or {@code "force"} * to force the approval UI to show) or {@code null} for the default behavior of {@code "auto"}. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public GoogleBrowserClientRequestUrl setApprovalPrompt(String approvalPrompt) { this.approvalPrompt = approvalPrompt; return this; } @Override public GoogleBrowserClientRequestUrl setResponseTypes(Collection<String> responseTypes) { return (GoogleBrowserClientRequestUrl) super.setResponseTypes(responseTypes); } @Override public GoogleBrowserClientRequestUrl setRedirectUri(String redirectUri) { return (GoogleBrowserClientRequestUrl) super.setRedirectUri(redirectUri); } @Override public GoogleBrowserClientRequestUrl setScopes(Collection<String> scopes) { Preconditions.checkArgument(scopes.iterator().hasNext()); return (GoogleBrowserClientRequestUrl) super.setScopes(scopes); } @Override public GoogleBrowserClientRequestUrl setClientId(String clientId) { return (GoogleBrowserClientRequestUrl) super.setClientId(clientId); } @Override public GoogleBrowserClientRequestUrl setState(String state) { return (GoogleBrowserClientRequestUrl) super.setState(state); } @Override public GoogleBrowserClientRequestUrl set(String fieldName, Object value) { return (GoogleBrowserClientRequestUrl) super.set(fieldName, value); } @Override public GoogleBrowserClientRequestUrl clone() { return (GoogleBrowserClientRequestUrl) super.clone(); } }
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.AuthorizationCodeFlow; import com.google.api.client.auth.oauth2.BearerToken; import com.google.api.client.auth.oauth2.ClientParametersAuthentication; import com.google.api.client.auth.oauth2.Credential.AccessMethod; import com.google.api.client.auth.oauth2.CredentialRefreshListener; import com.google.api.client.auth.oauth2.CredentialStore; import com.google.api.client.auth.oauth2.StoredCredential; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import com.google.api.client.util.Clock; import com.google.api.client.util.Preconditions; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import java.io.IOException; import java.util.Collection; /** * Thread-safe Google OAuth 2.0 authorization code flow that manages and persists end-user * credentials. * * <p> * This is designed to simplify the flow in which an end-user authorizes the application to access * their protected data, and then the application has access to their data based on an access token * and a refresh token to refresh that access token when it expires. * </p> * * <p> * The first step is to call {@link #loadCredential(String)} based on the known user ID to check if * the end-user's credentials are already known. If not, call {@link #newAuthorizationUrl()} and * direct the end-user's browser to an authorization page. The web browser will then redirect to the * redirect URL with a {@code "code"} query parameter which can then be used to request an access * token using {@link #newTokenRequest(String)}. Finally, use * {@link #createAndStoreCredential(TokenResponse, String)} to store and obtain a credential for * accessing protected resources. * </p> * * <p> * The default for the {@code approval_prompt} and {@code access_type} parameters is {@code null}. * For web applications that means {@code "approval_prompt=auto&access_type=online"} and for * installed applications that means {@code "approval_prompt=force&access_type=offline"}. To * override the default, you need to explicitly call {@link Builder#setApprovalPrompt(String)} and * {@link Builder#setAccessType(String)}. * </p> * * @author Yaniv Inbar * @since 1.7 */ @SuppressWarnings("deprecation") public class GoogleAuthorizationCodeFlow extends AuthorizationCodeFlow { /** * Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to * force the approval UI to show) or {@code null} for the default behavior. */ private final String approvalPrompt; /** * Access type ({@code "online"} to request online access or {@code "offline"} to request offline * access) or {@code null} for the default behavior. */ private final String accessType; /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param clientId client identifier * @param clientSecret client secret * @param scopes collection of scopes to be joined by a space separator * * @since 1.15 */ public GoogleAuthorizationCodeFlow(HttpTransport transport, JsonFactory jsonFactory, String clientId, String clientSecret, Collection<String> scopes) { this(new Builder(transport, jsonFactory, clientId, clientSecret, scopes)); } /** * @param builder Google authorization code flow builder * * @since 1.14 */ protected GoogleAuthorizationCodeFlow(Builder builder) { super(builder); accessType = builder.accessType; approvalPrompt = builder.approvalPrompt; } @Override public GoogleAuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) { // don't need to specify clientId & clientSecret because specifying clientAuthentication // don't want to specify redirectUri to give control of it to user of this class return new GoogleAuthorizationCodeTokenRequest(getTransport(), getJsonFactory(), getTokenServerEncodedUrl(), "", "", authorizationCode, "").setClientAuthentication( getClientAuthentication()) .setRequestInitializer(getRequestInitializer()).setScopes(getScopes()); } @Override public GoogleAuthorizationCodeRequestUrl newAuthorizationUrl() { // don't want to specify redirectUri to give control of it to user of this class return new GoogleAuthorizationCodeRequestUrl( getAuthorizationServerEncodedUrl(), getClientId(), "", getScopes()).setAccessType( accessType).setApprovalPrompt(approvalPrompt); } /** * Returns the approval prompt behavior ({@code "auto"} to request auto-approval or * {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of * {@code "auto"}. */ public final String getApprovalPrompt() { return approvalPrompt; } /** * Returns the access type ({@code "online"} to request online access or {@code "offline"} to * request offline access) or {@code null} for the default behavior of {@code "online"}. */ public final String getAccessType() { return accessType; } /** * Google authorization code flow builder. * * <p> * Implementation is not thread-safe. * </p> */ public static class Builder extends AuthorizationCodeFlow.Builder { /** * Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to * force the approval UI to show) or {@code null} for the default behavior. */ String approvalPrompt; /** * Access type ({@code "online"} to request online access or {@code "offline"} to request * offline access) or {@code null} for the default behavior. */ String accessType; /** * * @param transport HTTP transport * @param jsonFactory JSON factory * @param clientId client identifier * @param clientSecret client secret * @param scopes collection of scopes to be joined by a space separator (or a single value * containing multiple space-separated scopes) * * @since 1.15 */ public Builder(HttpTransport transport, JsonFactory jsonFactory, String clientId, String clientSecret, Collection<String> scopes) { super(BearerToken.authorizationHeaderAccessMethod(), transport, jsonFactory, new GenericUrl( GoogleOAuthConstants.TOKEN_SERVER_URL), new ClientParametersAuthentication( clientId, clientSecret), clientId, GoogleOAuthConstants.AUTHORIZATION_SERVER_URL); setScopes(scopes); } /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param clientSecrets Google client secrets * @param scopes collection of scopes to be joined by a space separator * * @since 1.15 */ public Builder(HttpTransport transport, JsonFactory jsonFactory, GoogleClientSecrets clientSecrets, Collection<String> scopes) { super(BearerToken.authorizationHeaderAccessMethod(), transport, jsonFactory, new GenericUrl( GoogleOAuthConstants.TOKEN_SERVER_URL), new ClientParametersAuthentication( clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret()), clientSecrets.getDetails().getClientId(), GoogleOAuthConstants.AUTHORIZATION_SERVER_URL); setScopes(scopes); } @Override public GoogleAuthorizationCodeFlow build() { return new GoogleAuthorizationCodeFlow(this); } @Override public Builder setDataStoreFactory(DataStoreFactory dataStore) throws IOException { return (Builder) super.setDataStoreFactory(dataStore); } @Override public Builder setCredentialDataStore(DataStore<StoredCredential> typedDataStore) { return (Builder) super.setCredentialDataStore(typedDataStore); } @Override public Builder setCredentialCreatedListener( CredentialCreatedListener credentialCreatedListener) { return (Builder) super.setCredentialCreatedListener(credentialCreatedListener); } @Beta @Override @Deprecated public Builder setCredentialStore(CredentialStore credentialStore) { return (Builder) super.setCredentialStore(credentialStore); } @Override public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) { return (Builder) super.setRequestInitializer(requestInitializer); } @Override public Builder setScopes(Collection<String> scopes) { Preconditions.checkState(!scopes.isEmpty()); return (Builder) super.setScopes(scopes); } /** * @since 1.11 */ @Override public Builder setMethod(AccessMethod method) { return (Builder) super.setMethod(method); } /** * @since 1.11 */ @Override public Builder setTransport(HttpTransport transport) { return (Builder) super.setTransport(transport); } /** * @since 1.11 */ @Override public Builder setJsonFactory(JsonFactory jsonFactory) { return (Builder) super.setJsonFactory(jsonFactory); } /** * @since 1.11 */ @Override public Builder setTokenServerUrl(GenericUrl tokenServerUrl) { return (Builder) super.setTokenServerUrl(tokenServerUrl); } /** * @since 1.11 */ @Override public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { return (Builder) super.setClientAuthentication(clientAuthentication); } /** * @since 1.11 */ @Override public Builder setClientId(String clientId) { return (Builder) super.setClientId(clientId); } /** * @since 1.11 */ @Override public Builder setAuthorizationServerEncodedUrl(String authorizationServerEncodedUrl) { return (Builder) super.setAuthorizationServerEncodedUrl(authorizationServerEncodedUrl); } /** * @since 1.11 */ @Override public Builder setClock(Clock clock) { return (Builder) super.setClock(clock); } @Override public Builder addRefreshListener(CredentialRefreshListener refreshListener) { return (Builder) super.addRefreshListener(refreshListener); } @Override public Builder setRefreshListeners(Collection<CredentialRefreshListener> refreshListeners) { return (Builder) super.setRefreshListeners(refreshListeners); } /** * Sets the approval prompt behavior ({@code "auto"} to request auto-approval or {@code "force"} * to force the approval UI to show) or {@code null} for the default behavior ({@code "auto"} * for web applications and {@code "force"} for installed applications). * * <p> * By default this has the value {@code null}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setApprovalPrompt(String approvalPrompt) { this.approvalPrompt = approvalPrompt; return this; } /** * Returns the approval prompt behavior ({@code "auto"} to request auto-approval or * {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of * {@code "auto"}. */ public final String getApprovalPrompt() { return approvalPrompt; } /** * Sets the access type ({@code "online"} to request online access or {@code "offline"} to * request offline access) or {@code null} for the default behavior ({@code "online"} for web * applications and {@code "offline"} for installed applications). * * <p> * By default this has the value {@code null}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public Builder setAccessType(String accessType) { this.accessType = accessType; return this; } /** * Returns the access type ({@code "online"} to request online access or {@code "offline"} to * request offline access) or {@code null} for the default behavior of {@code "online"}. */ public final String getAccessType() { return accessType; } } }
Java
/* * Copyright (c) 2011 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.json.GenericJson; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Key; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.io.Reader; import java.util.List; /** * OAuth 2.0 client secrets JSON model as specified in <a * href="http://code.google.com/p/google-api-python-client/wiki/ClientSecrets">client_secrets.json * file format</a>. * * <p> * Sample usage: * </p> * * <pre> static GoogleClientSecrets loadClientSecretsResource(JsonFactory jsonFactory) throws IOException { return GoogleClientSecrets.load( jsonFactory, SampleClass.class.getResourceAsStream("/client_secrets.json")); } * </pre> * * @since 1.7 * @author Yaniv Inbar */ public final class GoogleClientSecrets extends GenericJson { /** Details for installed applications. */ @Key private Details installed; /** Details for web applications. */ @Key private Details web; /** Returns the details for installed applications. */ public Details getInstalled() { return installed; } /** Sets the details for installed applications. */ public GoogleClientSecrets setInstalled(Details installed) { this.installed = installed; return this; } /** Returns the details for web applications. */ public Details getWeb() { return web; } /** Sets the details for web applications. */ public GoogleClientSecrets setWeb(Details web) { this.web = web; return this; } /** Returns the details for either installed or web applications. */ public Details getDetails() { // that web or installed, but not both Preconditions.checkArgument((web == null) != (installed == null)); return web == null ? installed : web; } /** Client credential details. */ public static final class Details extends GenericJson { /** Client ID. */ @Key("client_id") private String clientId; /** Client secret. */ @Key("client_secret") private String clientSecret; /** Redirect URIs. */ @Key("redirect_uris") private List<String> redirectUris; /** Authorization server URI. */ @Key("auth_uri") private String authUri; /** Token server URI. */ @Key("token_uri") private String tokenUri; /** Returns the client ID. */ public String getClientId() { return clientId; } /** Sets the client ID. */ public Details setClientId(String clientId) { this.clientId = clientId; return this; } /** Returns the client secret. */ public String getClientSecret() { return clientSecret; } /** Sets the client secret. */ public Details setClientSecret(String clientSecret) { this.clientSecret = clientSecret; return this; } /** Returns the redirect URIs. */ public List<String> getRedirectUris() { return redirectUris; } /** Sets the redirect URIs. */ public Details setRedirectUris(List<String> redirectUris) { this.redirectUris = redirectUris; return this; } /** Returns the authorization server URI. */ public String getAuthUri() { return authUri; } /** Sets the authorization server URI. */ public Details setAuthUri(String authUri) { this.authUri = authUri; return this; } /** Returns the token server URI. */ public String getTokenUri() { return tokenUri; } /** Sets the token server URI. */ public Details setTokenUri(String tokenUri) { this.tokenUri = tokenUri; return this; } @Override public Details set(String fieldName, Object value) { return (Details) super.set(fieldName, value); } @Override public Details clone() { return (Details) super.clone(); } } @Override public GoogleClientSecrets set(String fieldName, Object value) { return (GoogleClientSecrets) super.set(fieldName, value); } @Override public GoogleClientSecrets clone() { return (GoogleClientSecrets) super.clone(); } /** * Loads the {@code client_secrets.json} file from the given reader. * * @since 1.15 */ public static GoogleClientSecrets load(JsonFactory jsonFactory, Reader reader) throws IOException { return jsonFactory.fromReader(reader, GoogleClientSecrets.class); } }
Java
/* * Copyright (c) 2011 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. */ /** * Google's additions to OAuth 2.0 authorization as specified in <a * href="http://code.google.com/apis/accounts/docs/OAuth2.html">Using OAuth 2.0 to Access Google * APIs</a>. * * <p> * Before using this library, you must register your application at the <a * href="https://code.google.com/apis/console#access">APIs Console</a>. The result of this * registration process is a set of values that are known to both Google and your application, such * as the "Client ID", "Client Secret", and "Redirect URIs". * </p> * * <p> * These are the typical steps of the web server flow based on an authorization code, as specified * in <a href="http://code.google.com/apis/accounts/docs/OAuth2WebServer.html">Using OAuth 2.0 for * Web Server Applications</a>: * <ul> * <li>Redirect the end user in the browser to the authorization page using * {@link com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl} to grant * your application access to the end user's protected data.</li> * <li>Process the authorization response using * {@link com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl} to parse the authorization * code.</li> * <li>Request an access token and possibly a refresh token using * {@link com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest}.</li> * <li>Access protected resources using * {@link com.google.api.client.googleapis.auth.oauth2.GoogleCredential}. Expired access tokens will * automatically be refreshed using the refresh token (if applicable).</li> * </ul> * </p> * * <p> * These are the typical steps of the the browser-based client flow specified in <a * href="http://code.google.com/apis/accounts/docs/OAuth2UserAgent.html">Using OAuth 2.0 for * Client-side Applications</a>: * <ul> * <li>Redirect the end user in the browser to the authorization page using * {@link com.google.api.client.googleapis.auth.oauth2.GoogleBrowserClientRequestUrl} to grant your * browser application access to the end user's protected data.</li> * <li>Use the <a href="http://code.google.com/p/google-api-javascript-client/">Google API Client * library for JavaScript</a> to process the access token found in the URL fragment at the redirect * URI registered at the <a href="https://code.google.com/apis/console#access">APIs Console</a>. * </li> * </ul> * </p> * * @since 1.7 * @author Yaniv Inbar */ package com.google.api.client.googleapis.auth.oauth2;
Java
/* * Copyright (c) 2011 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.ClientParametersAuthentication; import com.google.api.client.auth.oauth2.RefreshTokenRequest; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.auth.oauth2.TokenResponseException; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import java.io.IOException; import java.util.Collection; /** * Google-specific implementation of the OAuth 2.0 request to refresh an access token using a * refresh token as specified in <a href="http://tools.ietf.org/html/rfc6749#section-6">Refreshing * an Access Token</a>. * * <p> * Use {@link GoogleCredential} to access protected resources from the resource server using the * {@link TokenResponse} returned by {@link #execute()}. On error, it will instead throw * {@link TokenResponseException}. * </p> * * <p> * Sample usage: * </p> * * <pre> static void refreshAccessToken() throws IOException { try { TokenResponse response = new GoogleRefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(), "tGzv3JOkF0XG5Qx2TlKWIA", "s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw").execute(); System.out.println("Access token: " + response.getAccessToken()); } catch (TokenResponseException e) { if (e.getDetails() != null) { System.err.println("Error: " + e.getDetails().getError()); if (e.getDetails().getErrorDescription() != null) { System.err.println(e.getDetails().getErrorDescription()); } if (e.getDetails().getErrorUri() != null) { System.err.println(e.getDetails().getErrorUri()); } } else { System.err.println(e.getMessage()); } } } * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleRefreshTokenRequest extends RefreshTokenRequest { /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param refreshToken refresh token issued to the client * @param clientId client identifier issued to the client during the registration process * @param clientSecret client secret */ public GoogleRefreshTokenRequest(HttpTransport transport, JsonFactory jsonFactory, String refreshToken, String clientId, String clientSecret) { super(transport, jsonFactory, new GenericUrl(GoogleOAuthConstants.TOKEN_SERVER_URL), refreshToken); setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret)); } @Override public GoogleRefreshTokenRequest setRequestInitializer( HttpRequestInitializer requestInitializer) { return (GoogleRefreshTokenRequest) super.setRequestInitializer(requestInitializer); } @Override public GoogleRefreshTokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) { return (GoogleRefreshTokenRequest) super.setTokenServerUrl(tokenServerUrl); } @Override public GoogleRefreshTokenRequest setScopes(Collection<String> scopes) { return (GoogleRefreshTokenRequest) super.setScopes(scopes); } @Override public GoogleRefreshTokenRequest setGrantType(String grantType) { return (GoogleRefreshTokenRequest) super.setGrantType(grantType); } @Override public GoogleRefreshTokenRequest setClientAuthentication( HttpExecuteInterceptor clientAuthentication) { return (GoogleRefreshTokenRequest) super.setClientAuthentication(clientAuthentication); } @Override public GoogleRefreshTokenRequest setRefreshToken(String refreshToken) { return (GoogleRefreshTokenRequest) super.setRefreshToken(refreshToken); } @Override public GoogleTokenResponse execute() throws IOException { return executeUnparsed().parseAs(GoogleTokenResponse.class); } @Override public GoogleRefreshTokenRequest set(String fieldName, Object value) { return (GoogleRefreshTokenRequest) super.set(fieldName, value); } }
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.auth.openidconnect.IdToken; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.webtoken.JsonWebSignature; import com.google.api.client.util.Beta; import com.google.api.client.util.Key; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; /** * {@link Beta} <br/> * Google ID tokens as specified in <a * href="https://developers.google.com/accounts/docs/OAuth2Login">Using OAuth 2.0 for Login</a>. * * <p> * Google ID tokens contain useful information about the authorized end user. Google ID tokens are * signed and the signature must be verified using {@link #verify(GoogleIdTokenVerifier)}. * </p> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ @SuppressWarnings("javadoc") @Beta public class GoogleIdToken extends IdToken { /** * Parses the given ID token string and returns the parsed {@link GoogleIdToken}. * * @param jsonFactory JSON factory * @param idTokenString ID token string * @return parsed Google ID token */ public static GoogleIdToken parse(JsonFactory jsonFactory, String idTokenString) throws IOException { JsonWebSignature jws = JsonWebSignature.parser(jsonFactory).setPayloadClass(Payload.class).parse(idTokenString); return new GoogleIdToken(jws.getHeader(), (Payload) jws.getPayload(), jws.getSignatureBytes(), jws.getSignedContentBytes()); } /** * @param header header * @param payload payload * @param signatureBytes bytes of the signature * @param signedContentBytes bytes of the signature content */ public GoogleIdToken( Header header, Payload payload, byte[] signatureBytes, byte[] signedContentBytes) { super(header, payload, signatureBytes, signedContentBytes); } /** * Verifies that this ID token is valid using {@link GoogleIdTokenVerifier#verify(GoogleIdToken)}. */ public boolean verify(GoogleIdTokenVerifier verifier) throws GeneralSecurityException, IOException { return verifier.verify(this); } @Override public Payload getPayload() { return (Payload) super.getPayload(); } /** * {@link Beta} <br/> * Google ID token payload. */ @Beta public static class Payload extends IdToken.Payload { /** Hosted domain name if asserted user is a domain managed user or {@code null} for none. */ @Key("hd") private String hostedDomain; /** E-mail of the user or {@code null} if not requested. */ @Key("email") private String email; /** * {@code true} if the email is verified. * TODO(mwan): change the type of the field to Boolean and the handling in * {@link #getEmailVerified()} accordingly after Google OpenID Connect endpoint fixes the * type of the field in ID Token. */ @Key("email_verified") private Object emailVerified; public Payload() { } /** * Returns the obfuscated Google user id or {@code null} for none. * * @deprecated (scheduled to be removed in 1.18) Use {@link #getSubject()} instead. */ @Deprecated public String getUserId() { return getSubject(); } /** * Sets the obfuscated Google user id or {@code null} for none. * * @deprecated (scheduled to be removed in 1.18) Use {@link #setSubject(String)} instead. */ @Deprecated public Payload setUserId(String userId) { return setSubject(userId); } /** * Returns the client ID of issuee or {@code null} for none. * * @deprecated (scheduled to be removed in 1.18) Use {@link #getAuthorizedParty()} instead. */ @Deprecated public String getIssuee() { return getAuthorizedParty(); } /** * Sets the client ID of issuee or {@code null} for none. * * @deprecated (scheduled to be removed in 1.18) Use {@link #setAuthorizedParty(String)} * instead. */ @Deprecated public Payload setIssuee(String issuee) { return setAuthorizedParty(issuee); } /** * Returns the hosted domain name if asserted user is a domain managed user or {@code null} for * none. */ public String getHostedDomain() { return hostedDomain; } /** * Sets the hosted domain name if asserted user is a domain managed user or {@code null} for * none. */ public Payload setHostedDomain(String hostedDomain) { this.hostedDomain = hostedDomain; return this; } /** * Returns the e-mail address of the user or {@code null} if it was not requested. * * <p> * Requires the {@code "https://www.googleapis.com/auth/userinfo.email"} scope. * </p> * * @since 1.10 */ public String getEmail() { return email; } /** * Sets the e-mail address of the user or {@code null} if it was not requested. * * <p> * Used in conjunction with the {@code "https://www.googleapis.com/auth/userinfo.email"} scope. * </p> * * @since 1.10 */ public Payload setEmail(String email) { this.email = email; return this; } /** * Returns {@code true} if the users e-mail address has been verified by Google. * * <p> * Requires the {@code "https://www.googleapis.com/auth/userinfo.email"} scope. * </p> * * @since 1.10 * * <p> * Upgrade warning: in prior version 1.16 this method accessed {@code "verified_email"} * and returns a boolean, but starting with verison 1.17, it now accesses * {@code "email_verified"} and returns a Boolean. Previously, if this value was not * specified, this method would return {@code false}, but now it returns {@code null}. * </p> */ public Boolean getEmailVerified() { if (emailVerified == null) { return null; } if (emailVerified instanceof Boolean) { return (Boolean) emailVerified; } return Boolean.valueOf((String) emailVerified); } /** * Sets whether the users e-mail address has been verified by Google or not. * * <p> * Used in conjunction with the {@code "https://www.googleapis.com/auth/userinfo.email"} scope. * </p> * * @since 1.10 * * <p> * Upgrade warning: in prior version 1.16 this method accessed {@code "verified_email"} and * required a boolean parameter, but starting with verison 1.17, it now accesses * {@code "email_verified"} and requires a Boolean parameter. * </p> */ public Payload setEmailVerified(Boolean emailVerified) { this.emailVerified = emailVerified; return this; } @Override public Payload setAuthorizationTimeSeconds(Long authorizationTimeSeconds) { return (Payload) super.setAuthorizationTimeSeconds(authorizationTimeSeconds); } @Override public Payload setAuthorizedParty(String authorizedParty) { return (Payload) super.setAuthorizedParty(authorizedParty); } @Override public Payload setNonce(String nonce) { return (Payload) super.setNonce(nonce); } @Override public Payload setAccessTokenHash(String accessTokenHash) { return (Payload) super.setAccessTokenHash(accessTokenHash); } @Override public Payload setClassReference(String classReference) { return (Payload) super.setClassReference(classReference); } @Override public Payload setMethodsReferences(List<String> methodsReferences) { return (Payload) super.setMethodsReferences(methodsReferences); } @Override public Payload setExpirationTimeSeconds(Long expirationTimeSeconds) { return (Payload) super.setExpirationTimeSeconds(expirationTimeSeconds); } @Override public Payload setNotBeforeTimeSeconds(Long notBeforeTimeSeconds) { return (Payload) super.setNotBeforeTimeSeconds(notBeforeTimeSeconds); } @Override public Payload setIssuedAtTimeSeconds(Long issuedAtTimeSeconds) { return (Payload) super.setIssuedAtTimeSeconds(issuedAtTimeSeconds); } @Override public Payload setIssuer(String issuer) { return (Payload) super.setIssuer(issuer); } @Override public Payload setAudience(Object audience) { return (Payload) super.setAudience(audience); } @Override public Payload setJwtId(String jwtId) { return (Payload) super.setJwtId(jwtId); } @Override public Payload setType(String type) { return (Payload) super.setType(type); } @Override public Payload setSubject(String subject) { return (Payload) super.setSubject(subject); } @Override public Payload set(String fieldName, Object value) { return (Payload) super.set(fieldName, value); } @Override public Payload clone() { return (Payload) super.clone(); } } }
Java
/* * Copyright (c) 2011 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest; import com.google.api.client.auth.oauth2.ClientParametersAuthentication; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.auth.oauth2.TokenResponseException; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpExecuteInterceptor; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.util.Collection; /** * Google-specific implementation of the OAuth 2.0 request for an access token based on an * authorization code (as specified in <a * href="http://code.google.com/apis/accounts/docs/OAuth2WebServer.html">Using OAuth 2.0 for Web * Server Applications</a>). * * <p> * Use {@link GoogleCredential} to access protected resources from the resource server using the * {@link TokenResponse} returned by {@link #execute()}. On error, it will instead throw * {@link TokenResponseException}. * </p> * * <p> * Sample usage: * </p> * * <pre> static void requestAccessToken() throws IOException { try { GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(), "812741506391.apps.googleusercontent.com", "{client_secret}", "4/P7q7W91a-oMsCeLvIaQm6bTrgtp7", "https://oauth2-login-demo.appspot.com/code") .execute(); System.out.println("Access token: " + response.getAccessToken()); } catch (TokenResponseException e) { if (e.getDetails() != null) { System.err.println("Error: " + e.getDetails().getError()); if (e.getDetails().getErrorDescription() != null) { System.err.println(e.getDetails().getErrorDescription()); } if (e.getDetails().getErrorUri() != null) { System.err.println(e.getDetails().getErrorUri()); } } else { System.err.println(e.getMessage()); } } } * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleAuthorizationCodeTokenRequest extends AuthorizationCodeTokenRequest { /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param clientId client identifier issued to the client during the registration process * @param clientSecret client secret * @param code authorization code generated by the authorization server * @param redirectUri redirect URL parameter matching the redirect URL parameter in the * authorization request (see {@link #setRedirectUri(String)} */ public GoogleAuthorizationCodeTokenRequest(HttpTransport transport, JsonFactory jsonFactory, String clientId, String clientSecret, String code, String redirectUri) { this(transport, jsonFactory, GoogleOAuthConstants.TOKEN_SERVER_URL, clientId, clientSecret, code, redirectUri); } /** * @param transport HTTP transport * @param jsonFactory JSON factory * @param tokenServerEncodedUrl token server encoded URL * @param clientId client identifier issued to the client during the registration process * @param clientSecret client secret * @param code authorization code generated by the authorization server * @param redirectUri redirect URL parameter matching the redirect URL parameter in the * authorization request (see {@link #setRedirectUri(String)} * * @since 1.12 */ public GoogleAuthorizationCodeTokenRequest(HttpTransport transport, JsonFactory jsonFactory, String tokenServerEncodedUrl, String clientId, String clientSecret, String code, String redirectUri) { super(transport, jsonFactory, new GenericUrl(tokenServerEncodedUrl), code); setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret)); setRedirectUri(redirectUri); } @Override public GoogleAuthorizationCodeTokenRequest setRequestInitializer( HttpRequestInitializer requestInitializer) { return (GoogleAuthorizationCodeTokenRequest) super.setRequestInitializer(requestInitializer); } @Override public GoogleAuthorizationCodeTokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) { return (GoogleAuthorizationCodeTokenRequest) super.setTokenServerUrl(tokenServerUrl); } @Override public GoogleAuthorizationCodeTokenRequest setScopes(Collection<String> scopes) { return (GoogleAuthorizationCodeTokenRequest) super.setScopes(scopes); } @Override public GoogleAuthorizationCodeTokenRequest setGrantType(String grantType) { return (GoogleAuthorizationCodeTokenRequest) super.setGrantType(grantType); } @Override public GoogleAuthorizationCodeTokenRequest setClientAuthentication( HttpExecuteInterceptor clientAuthentication) { Preconditions.checkNotNull(clientAuthentication); return (GoogleAuthorizationCodeTokenRequest) super.setClientAuthentication( clientAuthentication); } @Override public GoogleAuthorizationCodeTokenRequest setCode(String code) { return (GoogleAuthorizationCodeTokenRequest) super.setCode(code); } @Override public GoogleAuthorizationCodeTokenRequest setRedirectUri(String redirectUri) { Preconditions.checkNotNull(redirectUri); return (GoogleAuthorizationCodeTokenRequest) super.setRedirectUri(redirectUri); } @Override public GoogleTokenResponse execute() throws IOException { return executeUnparsed().parseAs(GoogleTokenResponse.class); } @Override public GoogleAuthorizationCodeTokenRequest set(String fieldName, Object value) { return (GoogleAuthorizationCodeTokenRequest) super.set(fieldName, value); } }
Java
/* * Copyright (c) 2011 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl; import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl; import com.google.api.client.util.Key; import com.google.api.client.util.Preconditions; import java.util.Collection; /** * Google-specific implementation of the OAuth 2.0 URL builder for an authorization web page to * allow the end user to authorize the application to access their protected resources and that * returns an authorization code, as specified in <a * href="https://developers.google.com/accounts/docs/OAuth2WebServer">Using OAuth 2.0 for Web Server * Applications</a>. * * <p> * The default for {@link #getResponseTypes()} is {@code "code"}. Use * {@link AuthorizationCodeResponseUrl} to parse the redirect response after the end user * grants/denies the request. Using the authorization code in this response, use * {@link GoogleAuthorizationCodeTokenRequest} to request the access token. * </p> * * <p> * Sample usage for a web application: * </p> * * <pre> public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String url = new GoogleAuthorizationCodeRequestUrl("812741506391.apps.googleusercontent.com", "https://oauth2-login-demo.appspot.com/code", Arrays.asList( "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile")).setState("/profile").build(); response.sendRedirect(url); } * </pre> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleAuthorizationCodeRequestUrl extends AuthorizationCodeRequestUrl { /** * Prompt for consent behavior ({@code "auto"} to request auto-approval or {@code "force"} to * force the approval UI to show) or {@code null} for the default behavior. */ @Key("approval_prompt") private String approvalPrompt; /** * Access type ({@code "online"} to request online access or {@code "offline"} to request offline * access) or {@code null} for the default behavior. */ @Key("access_type") private String accessType; /** * @param clientId client identifier * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Collection)}) * * @since 1.15 */ public GoogleAuthorizationCodeRequestUrl( String clientId, String redirectUri, Collection<String> scopes) { this(GoogleOAuthConstants.AUTHORIZATION_SERVER_URL, clientId, redirectUri, scopes); } /** * @param authorizationServerEncodedUrl authorization server encoded URL * @param clientId client identifier * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Collection)}) * * @since 1.15 */ public GoogleAuthorizationCodeRequestUrl(String authorizationServerEncodedUrl, String clientId, String redirectUri, Collection<String> scopes) { super(authorizationServerEncodedUrl, clientId); setRedirectUri(redirectUri); setScopes(scopes); } /** * @param clientSecrets OAuth 2.0 client secrets JSON model as specified in <a * href="http://code.google.com/p/google-api-python-client/wiki/ClientSecrets"> * client_secrets.json file format</a> * @param redirectUri URI that the authorization server directs the resource owner's user-agent * back to the client after a successful authorization grant * @param scopes scopes (see {@link #setScopes(Collection)}) * * @since 1.15 */ public GoogleAuthorizationCodeRequestUrl( GoogleClientSecrets clientSecrets, String redirectUri, Collection<String> scopes) { this(clientSecrets.getDetails().getClientId(), redirectUri, scopes); } /** * Returns the approval prompt behavior ({@code "auto"} to request auto-approval or * {@code "force"} to force the approval UI to show) or {@code null} for the default behavior of * {@code "auto"}. */ public final String getApprovalPrompt() { return approvalPrompt; } /** * Sets the approval prompt behavior ({@code "auto"} to request auto-approval or {@code "force"} * to force the approval UI to show) or {@code null} for the default behavior of {@code "auto"}. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public GoogleAuthorizationCodeRequestUrl setApprovalPrompt(String approvalPrompt) { this.approvalPrompt = approvalPrompt; return this; } /** * Returns the access type ({@code "online"} to request online access or {@code "offline"} to * request offline access) or {@code null} for the default behavior of {@code "online"}. */ public final String getAccessType() { return accessType; } /** * Sets the access type ({@code "online"} to request online access or {@code "offline"} to request * offline access) or {@code null} for the default behavior of {@code "online"}. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ public GoogleAuthorizationCodeRequestUrl setAccessType(String accessType) { this.accessType = accessType; return this; } @Override public GoogleAuthorizationCodeRequestUrl setResponseTypes(Collection<String> responseTypes) { return (GoogleAuthorizationCodeRequestUrl) super.setResponseTypes(responseTypes); } @Override public GoogleAuthorizationCodeRequestUrl setRedirectUri(String redirectUri) { Preconditions.checkNotNull(redirectUri); return (GoogleAuthorizationCodeRequestUrl) super.setRedirectUri(redirectUri); } @Override public GoogleAuthorizationCodeRequestUrl setScopes(Collection<String> scopes) { Preconditions.checkArgument(scopes.iterator().hasNext()); return (GoogleAuthorizationCodeRequestUrl) super.setScopes(scopes); } @Override public GoogleAuthorizationCodeRequestUrl setClientId(String clientId) { return (GoogleAuthorizationCodeRequestUrl) super.setClientId(clientId); } @Override public GoogleAuthorizationCodeRequestUrl setState(String state) { return (GoogleAuthorizationCodeRequestUrl) super.setState(state); } @Override public GoogleAuthorizationCodeRequestUrl set(String fieldName, Object value) { return (GoogleAuthorizationCodeRequestUrl) super.set(fieldName, value); } @Override public GoogleAuthorizationCodeRequestUrl clone() { return (GoogleAuthorizationCodeRequestUrl) super.clone(); } }
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import com.google.api.client.util.Key; import com.google.api.client.util.Preconditions; import java.io.IOException; /** * Google OAuth 2.0 JSON model for a successful access token response as specified in <a * href="http://tools.ietf.org/html/rfc6749#section-5.1">Successful Response</a>, including an ID * token as specified in <a href="http://openid.net/specs/openid-connect-session-1_0.html">OpenID * Connect Session Management 1.0</a>. * * <p> * This response object is the result of {@link GoogleAuthorizationCodeTokenRequest#execute()} and * {@link GoogleRefreshTokenRequest#execute()}. Use {@link #parseIdToken()} to parse the * {@link GoogleIdToken} and then call {@link GoogleIdTokenVerifier#verify(GoogleIdToken)}. * </p> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.7 * @author Yaniv Inbar */ public class GoogleTokenResponse extends TokenResponse { /** ID token. */ @Key("id_token") private String idToken; @Override public GoogleTokenResponse setAccessToken(String accessToken) { return (GoogleTokenResponse) super.setAccessToken(accessToken); } @Override public GoogleTokenResponse setTokenType(String tokenType) { return (GoogleTokenResponse) super.setTokenType(tokenType); } @Override public GoogleTokenResponse setExpiresInSeconds(Long expiresIn) { return (GoogleTokenResponse) super.setExpiresInSeconds(expiresIn); } @Override public GoogleTokenResponse setRefreshToken(String refreshToken) { return (GoogleTokenResponse) super.setRefreshToken(refreshToken); } @Override public GoogleTokenResponse setScope(String scope) { return (GoogleTokenResponse) super.setScope(scope); } /** * {@link Beta} <br/> * Returns the ID token. */ @Beta public final String getIdToken() { return idToken; } /** * {@link Beta} <br/> * Sets the ID token. * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> */ @Beta public GoogleTokenResponse setIdToken(String idToken) { this.idToken = Preconditions.checkNotNull(idToken); return this; } /** * {@link Beta} <br/> * Parses using {@link GoogleIdToken#parse(JsonFactory, String)} based on the {@link #getFactory() * JSON factory} and {@link #getIdToken() ID token}. */ @Beta public GoogleIdToken parseIdToken() throws IOException { return GoogleIdToken.parse(getFactory(), getIdToken()); } @Override public GoogleTokenResponse set(String fieldName, Object value) { return (GoogleTokenResponse) super.set(fieldName, value); } @Override public GoogleTokenResponse clone() { return (GoogleTokenResponse) super.clone(); } }
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.auth.openidconnect.IdToken; import com.google.api.client.auth.openidconnect.IdTokenVerifier; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.util.Beta; import com.google.api.client.util.Clock; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PublicKey; import java.util.Collection; import java.util.List; /** * {@link Beta} <br/> * Thread-safe Google ID token verifier. * * <p> * Call {@link #verify(IdToken)} to verify a ID token. Use the constructor * {@link #GoogleIdTokenVerifier(HttpTransport, JsonFactory)} for the typical simpler case if your * application has only a single instance of {@link GoogleIdTokenVerifier}. Otherwise, ideally you * should use {@link #GoogleIdTokenVerifier(GooglePublicKeysManager)} with a shared global instance * of the {@link GooglePublicKeysManager} since that way the Google public keys are cached. Sample * usage: * </p> * * <pre> GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory) .setAudience(Arrays.asList("myClientId")) .build(); ... if (!verifier.verify(googleIdToken)) {...} * </pre> * * @since 1.7 */ @Beta public class GoogleIdTokenVerifier extends IdTokenVerifier { /** Google public keys manager. */ private final GooglePublicKeysManager publicKeys; /** * @param transport HTTP transport * @param jsonFactory JSON factory */ public GoogleIdTokenVerifier(HttpTransport transport, JsonFactory jsonFactory) { this(new Builder(transport, jsonFactory)); } /** * @param publicKeys Google public keys manager * * @since 1.17 */ public GoogleIdTokenVerifier(GooglePublicKeysManager publicKeys) { this(new Builder(publicKeys)); } /** * @param builder builder * * @since 1.14 */ protected GoogleIdTokenVerifier(Builder builder) { super(builder); publicKeys = builder.publicKeys; } /** * Returns the Google public keys manager. * * @since 1.17 */ public final GooglePublicKeysManager getPublicKeysManager() { return publicKeys; } /** * Returns the HTTP transport. * * @since 1.14 */ public final HttpTransport getTransport() { return publicKeys.getTransport(); } /** Returns the JSON factory. */ public final JsonFactory getJsonFactory() { return publicKeys.getJsonFactory(); } /** * Returns the public certificates encoded URL. * * @since 1.15 * @deprecated (scheduled to be removed in 1.18) Use {@link #getPublicKeysManager()} and * {@link GooglePublicKeysManager#getPublicCertsEncodedUrl()} instead. */ @Deprecated public final String getPublicCertsEncodedUrl() { return publicKeys.getPublicCertsEncodedUrl(); } /** * Returns the public keys. * * <p> * Upgrade warning: in prior version 1.16 it may return {@code null} and not throw any exceptions, * but starting with version 1.17 it cannot return {@code null} and may throw * {@link GeneralSecurityException} or {@link IOException}. * </p> * * @deprecated (scheduled to be removed in 1.18) Use {@link #getPublicKeysManager()} and * {@link GooglePublicKeysManager#getPublicCertsEncodedUrl()} instead. */ @Deprecated public final List<PublicKey> getPublicKeys() throws GeneralSecurityException, IOException { return publicKeys.getPublicKeys(); } /** * Returns the expiration time in milliseconds to be used with {@link Clock#currentTimeMillis()} * or {@code 0} for none. * * @deprecated (scheduled to be removed in 1.18) Use {@link #getPublicKeysManager()} and * {@link GooglePublicKeysManager#getExpirationTimeMilliseconds()} instead. */ @Deprecated public final long getExpirationTimeMilliseconds() { return publicKeys.getExpirationTimeMilliseconds(); } /** * Verifies that the given ID token is valid using the cached public keys. * * It verifies: * * <ul> * <li>The RS256 signature, which uses RSA and SHA-256 based on the public keys downloaded from * the public certificate endpoint.</li> * <li>The current time against the issued at and expiration time (allowing for a 5 minute clock * skew).</li> * <li>The issuer is {@code "accounts.google.com"}.</li> * </ul> * * @param googleIdToken Google ID token * @return {@code true} if verified successfully or {@code false} if failed */ public boolean verify(GoogleIdToken googleIdToken) throws GeneralSecurityException, IOException { // check the payload if (!super.verify(googleIdToken)) { return false; } // verify signature for (PublicKey publicKey : publicKeys.getPublicKeys()) { if (googleIdToken.verifySignature(publicKey)) { return true; } } return false; } /** * Verifies that the given ID token is valid using {@link #verify(GoogleIdToken)} and returns the * ID token if succeeded. * * @param idTokenString Google ID token string * @return Google ID token if verified successfully or {@code null} if failed * @since 1.9 */ public GoogleIdToken verify(String idTokenString) throws GeneralSecurityException, IOException { GoogleIdToken idToken = GoogleIdToken.parse(getJsonFactory(), idTokenString); return verify(idToken) ? idToken : null; } /** * Downloads the public keys from the public certificates endpoint at * {@link #getPublicCertsEncodedUrl}. * * <p> * This method is automatically called if the public keys have not yet been initialized or if the * expiration time is very close, so normally this doesn't need to be called. Only call this * method explicitly to force the public keys to be updated. * </p> * * @deprecated (scheduled to be removed in 1.18) Use {@link #getPublicKeysManager()} and * {@link GooglePublicKeysManager#refresh()} instead. */ @Deprecated public GoogleIdTokenVerifier loadPublicCerts() throws GeneralSecurityException, IOException { publicKeys.refresh(); return this; } /** * {@link Beta} <br/> * Builder for {@link GoogleIdTokenVerifier}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.9 */ @Beta public static class Builder extends IdTokenVerifier.Builder { /** Google public keys manager. */ GooglePublicKeysManager publicKeys; /** * @param transport HTTP transport * @param jsonFactory JSON factory */ public Builder(HttpTransport transport, JsonFactory jsonFactory) { this(new GooglePublicKeysManager(transport, jsonFactory)); } /** * @param publicKeys Google public keys manager * * @since 1.17 */ public Builder(GooglePublicKeysManager publicKeys) { this.publicKeys = Preconditions.checkNotNull(publicKeys); setIssuer("accounts.google.com"); } /** Builds a new instance of {@link GoogleIdTokenVerifier}. */ @Override public GoogleIdTokenVerifier build() { return new GoogleIdTokenVerifier(this); } /** * Returns the Google public keys manager. * * @since 1.17 */ public final GooglePublicKeysManager getPublicCerts() { return publicKeys; } /** Returns the HTTP transport. */ public final HttpTransport getTransport() { return publicKeys.getTransport(); } /** Returns the JSON factory. */ public final JsonFactory getJsonFactory() { return publicKeys.getJsonFactory(); } /** * Returns the public certificates encoded URL. * * @since 1.15 * @deprecated (scheduled to be removed in 1.18) Use {@link #getPublicCerts()} and * {@link GooglePublicKeysManager#getPublicCertsEncodedUrl()} instead. */ @Deprecated public final String getPublicCertsEncodedUrl() { return publicKeys.getPublicCertsEncodedUrl(); } /** * Sets the public certificates encoded URL. * * <p> * The default value is {@link GoogleOAuthConstants#DEFAULT_PUBLIC_CERTS_ENCODED_URL}. * </p> * * <p> * Overriding is only supported for the purpose of calling the super implementation and changing * the return type, but nothing else. * </p> * * @since 1.15 * @deprecated (scheduled to be removed in 1.18) Use * {@link GooglePublicKeysManager.Builder#setPublicCertsEncodedUrl(String)} instead. */ @Deprecated public Builder setPublicCertsEncodedUrl(String publicKeysEncodedUrl) { // TODO(yanivi): make publicKeys field final when this method is removed publicKeys = new GooglePublicKeysManager.Builder( getTransport(), getJsonFactory()).setPublicCertsEncodedUrl(publicKeysEncodedUrl) .setClock(publicKeys.getClock()).build(); return this; } @Override public Builder setIssuer(String issuer) { return (Builder) super.setIssuer(issuer); } @Override public Builder setAudience(Collection<String> audience) { return (Builder) super.setAudience(audience); } @Override public Builder setAcceptableTimeSkewSeconds(long acceptableTimeSkewSeconds) { return (Builder) super.setAcceptableTimeSkewSeconds(acceptableTimeSkewSeconds); } @Override public Builder setClock(Clock clock) { return (Builder) super.setClock(clock); } } }
Java
/* * Copyright (c) 2014 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 com.google.api.client.googleapis.auth.oauth2; import java.nio.charset.Charset; /** * Utilities used by the com.google.api.client.googleapis.auth.oauth2 namespace * */ class OAuth2Utils { static final Charset UTF_8 = Charset.forName("UTF-8"); static <T extends Throwable> T exceptionWithCause(T exception, Throwable cause) { exception.initCause(cause); return exception; } private OAuth2Utils() { } }
Java
/* * Copyright (c) 2014 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 com.google.api.client.googleapis.auth.oauth2; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.JsonObjectParser; import com.google.api.client.util.Beta; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.security.AccessControlException; import java.util.Locale; /** * {@link Beta} <br/> * Provides a default credential available from the host or from an environment variable. * * <p>An instance represents the per-process state used to get and cache the credential and * allows overriding the state and environment for testing purposes. */ @Beta class DefaultCredentialProvider { static final String CREDENTIAL_ENV_VAR = "GOOGLE_CREDENTIALS_DEFAULT"; static final String WELL_KNOWN_CREDENTIALS_FILE = "credentials_default.json"; static final String CLOUDSDK_CONFIG_DIRECTORY = "gcloud"; static final String HELP_PERMALINK = "https://developers.google.com/accounts/docs/default-credential"; static final String APP_ENGINE_CREDENTIAL_CLASS = "com.google.api.client.googleapis.extensions.appengine.auth.oauth2" + ".AppIdentityCredential$AppEngineCredentialWrapper"; // These variables should only be accessed inside a synchronized block private GoogleCredential cachedCredential = null; private boolean checkedAppEngine = false; private boolean checkedComputeEngine = false; DefaultCredentialProvider() {} /** * {@link Beta} <br/> * Returns a default credential for the application. * * <p>Returns the built-in service account's credential for the application if running on * Google App Engine or Google Compute Engine, or returns the credential pointed to by the * environment variable GOOGLE_CREDENTIALS_DEFAULT. * </p> * * @param transport the transport for Http calls. * @param jsonFactory the factory for Json parsing and formatting. * @return the credential instance. * @throws IOException if the credential cannot be created in the current environment. * */ final GoogleCredential getDefaultCredential(HttpTransport transport, JsonFactory jsonFactory) throws IOException { synchronized (this) { if (cachedCredential == null) { cachedCredential = getDefaultCredentialUnsynchronized(transport, jsonFactory); } if (cachedCredential != null) { return cachedCredential; } } throw new IOException(String.format( "The default credential is not available. This is available if running" + " in Google App Engine or Google Compute Engine. Otherwise, the environment" + " variable %s must be defined pointing to a file defining the credentials." + " See %s for details.", CREDENTIAL_ENV_VAR, HELP_PERMALINK)); } private final GoogleCredential getDefaultCredentialUnsynchronized( HttpTransport transport, JsonFactory jsonFactory) throws IOException { // First try the environment variable GoogleCredential credential = null; String credentialsPath = getEnv(CREDENTIAL_ENV_VAR); if (credentialsPath != null && credentialsPath.length() > 0) { InputStream credentialsStream = null; try { File credentialsFile = new File(credentialsPath); if (!credentialsFile.exists() || credentialsFile.isDirectory()) { // Path will get in the message from the catch block below throw new IOException("File does not exist."); } credentialsStream = new FileInputStream(credentialsFile); credential = GoogleCredential.fromStream(credentialsStream, transport, jsonFactory); } catch (IOException e) { // Although it is also the cause, the message of the caught exception can have very // important information for diagnosing errors, so include its message in the // outer exception message also throw OAuth2Utils.exceptionWithCause(new IOException(String.format( "Error reading credential file from environment variable %s, value '%s': %s", CREDENTIAL_ENV_VAR, credentialsPath, e.getMessage())), e); } catch (AccessControlException expected) { // Exception querying file system is expected on App-Engine } finally { if (credentialsStream != null) { credentialsStream.close(); } } } // Then try the well-known file File wellKnownFileLocation = getWellKnownCredentialsFile(); try { if (fileExists(wellKnownFileLocation)) { InputStream credentialsStream = null; try { credentialsStream = new FileInputStream(wellKnownFileLocation); credential = GoogleCredential.fromStream(credentialsStream, transport, jsonFactory); } catch (IOException e) { throw new IOException(String.format( "Error reading credential file from location %s: %s", wellKnownFileLocation, e.getMessage())); } finally { if (credentialsStream != null) { credentialsStream.close(); } } } } catch (AccessControlException expected) { // Exception querying file system is expected on App-Engine } // Then try App Engine if (credential == null) { credential = tryGetAppEngineCredential(transport, jsonFactory); } // Then try Compute Engine if (credential == null) { credential = tryGetComputeCredential(transport, jsonFactory); } return credential; } private final File getWellKnownCredentialsFile() { File cloudConfigPath = null; String os = getProperty("os.name", "").toLowerCase(Locale.US); if (os.indexOf("windows") >= 0) { File appDataPath = new File(getEnv("APPDATA")); cloudConfigPath = new File(appDataPath, CLOUDSDK_CONFIG_DIRECTORY); } else { File configPath = new File(getProperty("user.home", ""), ".config"); cloudConfigPath = new File(configPath, CLOUDSDK_CONFIG_DIRECTORY); } File credentialFilePath = new File(cloudConfigPath, WELL_KNOWN_CREDENTIALS_FILE); return credentialFilePath; } /** * Override in test code to isolate from environment. */ String getEnv(String name) { return System.getenv(name); } /** * Override in test code to isolate from environment. */ boolean fileExists(File file) { return file.exists() && !file.isDirectory(); } /** * Override in test code to isolate from environment. */ String getProperty(String property, String def) { return System.getProperty(property, def); } /** * Override in test code to isolate from environment */ Class<?> forName(String className) throws ClassNotFoundException { return Class.forName(className); } private final GoogleCredential tryGetAppEngineCredential( HttpTransport transport, JsonFactory jsonFactory) { // Checking for App Engine requires a class load, so check only once if (checkedAppEngine) { return null; } checkedAppEngine = true; try { Class<?> credentialClass = forName(APP_ENGINE_CREDENTIAL_CLASS); Constructor<?> constructor = credentialClass .getConstructor(HttpTransport.class, JsonFactory.class); return (GoogleCredential) constructor.newInstance(transport, jsonFactory); } catch (ReflectiveOperationException expected) { // Expected when not running on App Engine } return null; } private final GoogleCredential tryGetComputeCredential( HttpTransport transport, JsonFactory jsonFactory) { // Checking compute engine requires a round-trip, so check only once if (checkedComputeEngine) { return null; } checkedComputeEngine = true; try { // To determine if we are running in compute engine, at least one call to the metadata // server is required. Attempt to refresh a token which will answer whether we // are on compute engine and if so, use the credential as the default. GoogleCredential computeCredential = new ComputeGoogleCredential(transport, jsonFactory); if (computeCredential.refreshToken()) { return computeCredential; } } catch (IOException expected) { // Exception is expected when not running on Google Compute Engine. } return null; } private static class ComputeGoogleCredential extends GoogleCredential { /** Metadata Service Account token server encoded URL. */ private static final String TOKEN_SERVER_ENCODED_URL = "http://metadata/computeMetadata/v1/instance/service-accounts/default/token"; ComputeGoogleCredential(HttpTransport transport, JsonFactory jsonFactory) { super(new GoogleCredential.Builder() .setTransport(transport) .setJsonFactory(jsonFactory) .setTokenServerEncodedUrl(TOKEN_SERVER_ENCODED_URL)); } @Override protected TokenResponse executeRefreshToken() throws IOException { GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl()); HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl); JsonObjectParser parser = new JsonObjectParser(getJsonFactory()); request.setParser(parser); request.getHeaders().set("X-Google-Metadata-Request", true); HttpResponse response = request.execute(); InputStream content = response.getContent(); if (content == null) { // Throw explicitly rather than allow a later null reference as default mock // transports return success codes with empty contents. throw new IOException("Empty content from metadata token server request."); } return parser.parseAndClose(content, response.getContentCharset(), TokenResponse.class); } } }
Java
/* * Copyright (c) 2010 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. */ /** * Media for Google API's. * * @since 1.9 * @author Ravi Mistry */ package com.google.api.client.googleapis.media;
Java
/* * Copyright (c) 2013 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 com.google.api.client.googleapis.media; import com.google.api.client.http.HttpIOExceptionHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.client.util.Beta; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * MediaUpload error handler handles an {@link IOException} and an abnormal HTTP response by calling * to {@link MediaHttpUploader#serverErrorCallback()}. * * @author Eyal Peled */ @Beta class MediaUploadErrorHandler implements HttpUnsuccessfulResponseHandler, HttpIOExceptionHandler { static final Logger LOGGER = Logger.getLogger(MediaUploadErrorHandler.class.getName()); /** The uploader to callback on if there is a server error. */ private final MediaHttpUploader uploader; /** The original {@link HttpIOExceptionHandler} of the HTTP request. */ private final HttpIOExceptionHandler originalIOExceptionHandler; /** The original {@link HttpUnsuccessfulResponseHandler} of the HTTP request. */ private final HttpUnsuccessfulResponseHandler originalUnsuccessfulHandler; /** * Constructs a new instance from {@link MediaHttpUploader} and {@link HttpRequest}. */ public MediaUploadErrorHandler(MediaHttpUploader uploader, HttpRequest request) { this.uploader = Preconditions.checkNotNull(uploader); originalIOExceptionHandler = request.getIOExceptionHandler(); originalUnsuccessfulHandler = request.getUnsuccessfulResponseHandler(); request.setIOExceptionHandler(this); request.setUnsuccessfulResponseHandler(this); } public boolean handleIOException(HttpRequest request, boolean supportsRetry) throws IOException { boolean handled = originalIOExceptionHandler != null && originalIOExceptionHandler.handleIOException(request, supportsRetry); // TODO(peleyal): figure out what is best practice - call serverErrorCallback only if I/O // exception was handled, or call it regardless if (handled) { try { uploader.serverErrorCallback(); } catch (IOException e) { LOGGER.log(Level.WARNING, "exception thrown while calling server callback", e); } } return handled; } public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException { boolean handled = originalUnsuccessfulHandler != null && originalUnsuccessfulHandler.handleResponse(request, response, supportsRetry); // TODO(peleyal): figure out what is best practice - call serverErrorCallback only if the // abnormal response was handled, or call it regardless if (handled && supportsRetry && response.getStatusCode() / 100 == 5) { try { uploader.serverErrorCallback(); } catch (IOException e) { LOGGER.log(Level.WARNING, "exception thrown while calling server callback", e); } } return handled; } }
Java
/* * Copyright (c) 2011 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 com.google.api.client.googleapis.media; import com.google.api.client.googleapis.MethodOverride; import com.google.api.client.http.AbstractInputStreamContent; import com.google.api.client.http.ByteArrayContent; import com.google.api.client.http.EmptyContent; import com.google.api.client.http.GZipEncoding; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpBackOffIOExceptionHandler; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpContent; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.InputStreamContent; import com.google.api.client.http.MultipartContent; import com.google.api.client.util.Beta; import com.google.api.client.util.ByteStreams; import com.google.api.client.util.Preconditions; import com.google.api.client.util.Sleeper; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; /** * Media HTTP Uploader, with support for both direct and resumable media uploads. Documentation is * available <a href='http://code.google.com/p/google-api-java-client/wiki/MediaUpload'>here</a>. * * <p> * For resumable uploads, when the media content length is known, if the provided * {@link InputStream} has {@link InputStream#markSupported} as {@code false} then it is wrapped in * an {@link BufferedInputStream} to support the {@link InputStream#mark} and * {@link InputStream#reset} methods required for handling server errors. If the media content * length is unknown then each chunk is stored temporarily in memory. This is required to determine * when the last chunk is reached. * </p> * * <p> * See {@link #setDisableGZipContent(boolean)} for information on when content is gzipped and how to * control that behavior. * </p> * * <p> * Back-off is disabled by default. To enable it for an abnormal HTTP response and an I/O exception * you should call {@link HttpRequest#setUnsuccessfulResponseHandler} with a new * {@link HttpBackOffUnsuccessfulResponseHandler} instance and * {@link HttpRequest#setIOExceptionHandler} with {@link HttpBackOffIOExceptionHandler}. * </p> * * <p> * Upgrade warning: in prior version 1.14 exponential back-off was enabled by default for an * abnormal HTTP response and there was a regular retry (without back-off) when I/O exception was * thrown. Starting with version 1.15 back-off is disabled and there is no retry on I/O exception by * default. * </p> * * <p> * Upgrade warning: in prior version 1.16 {@link #serverErrorCallback} was public but starting with * version 1.17 it has been removed from the public API, and changed to be package private. * </p> * * <p> * Implementation is not thread-safe. * </p> * * @since 1.9 * * @author rmistry@google.com (Ravi Mistry) * @author peleyal@google.com (Eyal Peled) */ @SuppressWarnings("deprecation") public final class MediaHttpUploader { /** * Upload content type header. * * @since 1.13 */ public static final String CONTENT_LENGTH_HEADER = "X-Upload-Content-Length"; /** * Upload content length header. * * @since 1.13 */ public static final String CONTENT_TYPE_HEADER = "X-Upload-Content-Type"; /** * Upload state associated with the Media HTTP uploader. */ public enum UploadState { /** The upload process has not started yet. */ NOT_STARTED, /** Set before the initiation request is sent. */ INITIATION_STARTED, /** Set after the initiation request completes. */ INITIATION_COMPLETE, /** Set after a media file chunk is uploaded. */ MEDIA_IN_PROGRESS, /** Set after the complete media file is successfully uploaded. */ MEDIA_COMPLETE } /** The current state of the uploader. */ private UploadState uploadState = UploadState.NOT_STARTED; static final int MB = 0x100000; private static final int KB = 0x400; /** * Minimum number of bytes that can be uploaded to the server (set to 256KB). */ public static final int MINIMUM_CHUNK_SIZE = 256 * KB; /** * Default maximum number of bytes that will be uploaded to the server in any single HTTP request * (set to 10 MB). */ public static final int DEFAULT_CHUNK_SIZE = 10 * MB; /** The HTTP content of the media to be uploaded. */ private final AbstractInputStreamContent mediaContent; /** The request factory for connections to the server. */ private final HttpRequestFactory requestFactory; /** The transport to use for requests. */ private final HttpTransport transport; /** HTTP content metadata of the media to be uploaded or {@code null} for none. */ private HttpContent metadata; /** * The length of the HTTP media content. * * <p> * {@code 0} before it is lazily initialized in {@link #getMediaContentLength()} after which it * could still be {@code 0} for empty media content. Will be {@code < 0} if the media content * length has not been specified. * </p> */ private long mediaContentLength; /** * Determines if media content length has been calculated yet in {@link #getMediaContentLength()}. */ private boolean isMediaContentLengthCalculated; /** * The HTTP method used for the initiation request. * * <p> * Can only be {@link HttpMethods#POST} (for media upload) or {@link HttpMethods#PUT} (for media * update). The default value is {@link HttpMethods#POST}. * </p> */ private String initiationRequestMethod = HttpMethods.POST; /** The HTTP headers used in the initiation request. */ private HttpHeaders initiationHeaders = new HttpHeaders(); /** * The HTTP request object that is currently used to send upload requests or {@code null} before * {@link #upload}. */ private HttpRequest currentRequest; /** An Input stream of the HTTP media content or {@code null} before {@link #upload}. */ private InputStream contentInputStream; /** * Determines whether direct media upload is enabled or disabled. If value is set to {@code true} * then a direct upload will be done where the whole media content is uploaded in a single request * If value is set to {@code false} then the upload uses the resumable media upload protocol to * upload in data chunks. Defaults to {@code false}. */ private boolean directUploadEnabled; /** * Progress listener to send progress notifications to or {@code null} for none. */ private MediaHttpUploaderProgressListener progressListener; /** * The media content length is used in the "Content-Range" header. If we reached the end of the * stream, this variable will be set with the length of the stream. This value is used only in * resumable media upload. */ String mediaContentLengthStr = "*"; /** * The number of bytes the server received so far. This value will not be calculated for direct * uploads when the content length is not known in advance. */ // TODO(rmistry): Figure out a way to compute the content length using CountingInputStream. private long totalBytesServerReceived; /** * Maximum size of individual chunks that will get uploaded by single HTTP requests. The default * value is {@link #DEFAULT_CHUNK_SIZE}. */ private int chunkSize = DEFAULT_CHUNK_SIZE; /** * Used to cache a single byte when the media content length is unknown or {@code null} for none. */ private Byte cachedByte; /** * The number of bytes the client had sent to the server so far or {@code 0} for none. It is used * for resumable media upload when the media content length is not specified. */ private long totalBytesClientSent; /** * The number of bytes of the current chunk which was sent to the server or {@code 0} for none. * This value equals to chunk size for each chunk the client send to the server, except for the * ending chunk. */ private int currentChunkLength; /** * The content buffer of the current request or {@code null} for none. It is used for resumable * media upload when the media content length is not specified. It is instantiated for every * request in {@link #setContentAndHeadersOnCurrentRequest} and is set to {@code null} when the * request is completed in {@link #upload}. */ private byte currentRequestContentBuffer[]; /** * Whether to disable GZip compression of HTTP content. * * <p> * The default value is {@code false}. * </p> */ private boolean disableGZipContent; /** Sleeper. **/ Sleeper sleeper = Sleeper.DEFAULT; /** * Construct the {@link MediaHttpUploader}. * * <p> * The input stream received by calling {@link AbstractInputStreamContent#getInputStream} is * closed when the upload process is successfully completed. For resumable uploads, when the media * content length is known, if the input stream has {@link InputStream#markSupported} as * {@code false} then it is wrapped in an {@link BufferedInputStream} to support the * {@link InputStream#mark} and {@link InputStream#reset} methods required for handling server * errors. If the media content length is unknown then each chunk is stored temporarily in memory. * This is required to determine when the last chunk is reached. * </p> * * @param mediaContent The Input stream content of the media to be uploaded * @param transport The transport to use for requests * @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or * {@code null} for none */ public MediaHttpUploader(AbstractInputStreamContent mediaContent, HttpTransport transport, HttpRequestInitializer httpRequestInitializer) { this.mediaContent = Preconditions.checkNotNull(mediaContent); this.transport = Preconditions.checkNotNull(transport); this.requestFactory = httpRequestInitializer == null ? transport.createRequestFactory() : transport.createRequestFactory(httpRequestInitializer); } /** * Executes a direct media upload or resumable media upload conforming to the specifications * listed <a href='http://code.google.com/apis/gdata/docs/resumable_upload.html'>here.</a> * * <p> * This method is not reentrant. A new instance of {@link MediaHttpUploader} must be instantiated * before upload called be called again. * </p> * * <p> * If an error is encountered during the request execution the caller is responsible for parsing * the response correctly. For example for JSON errors: * </p> * * <pre> if (!response.isSuccessStatusCode()) { throw GoogleJsonResponseException.from(jsonFactory, response); } * </pre> * * <p> * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the * response stream is properly closed. Example usage: * </p> * * <pre> HttpResponse response = batch.upload(initiationRequestUrl); try { // process the HTTP response object } finally { response.disconnect(); } * </pre> * * @param initiationRequestUrl The request URL where the initiation request will be sent * @return HTTP response */ public HttpResponse upload(GenericUrl initiationRequestUrl) throws IOException { Preconditions.checkArgument(uploadState == UploadState.NOT_STARTED); if (directUploadEnabled) { return directUpload(initiationRequestUrl); } return resumableUpload(initiationRequestUrl); } /** * Direct Uploads the media. * * @param initiationRequestUrl The request URL where the initiation request will be sent * @return HTTP response */ private HttpResponse directUpload(GenericUrl initiationRequestUrl) throws IOException { updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); HttpContent content = mediaContent; if (metadata != null) { content = new MultipartContent().setContentParts(Arrays.asList(metadata, mediaContent)); initiationRequestUrl.put("uploadType", "multipart"); } else { initiationRequestUrl.put("uploadType", "media"); } HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); request.getHeaders().putAll(initiationHeaders); // We do not have to do anything special here if media content length is unspecified because // direct media upload works even when the media content length == -1. HttpResponse response = executeCurrentRequest(request); boolean responseProcessed = false; try { if (isMediaLengthKnown()) { totalBytesServerReceived = getMediaContentLength(); } updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); responseProcessed = true; } finally { if (!responseProcessed) { response.disconnect(); } } return response; } /** * Uploads the media in a resumable manner. * * @param initiationRequestUrl The request URL where the initiation request will be sent * @return HTTP response */ private HttpResponse resumableUpload(GenericUrl initiationRequestUrl) throws IOException { // Make initial request to get the unique upload URL. HttpResponse initialResponse = executeUploadInitiation(initiationRequestUrl); if (!initialResponse.isSuccessStatusCode()) { // If the initiation request is not successful return it immediately. return initialResponse; } GenericUrl uploadUrl; try { uploadUrl = new GenericUrl(initialResponse.getHeaders().getLocation()); } finally { initialResponse.disconnect(); } // Convert media content into a byte stream to upload in chunks. contentInputStream = mediaContent.getInputStream(); if (!contentInputStream.markSupported() && isMediaLengthKnown()) { // If we know the media content length then wrap the stream into a Buffered input stream to // support the {@link InputStream#mark} and {@link InputStream#reset} methods required for // handling server errors. contentInputStream = new BufferedInputStream(contentInputStream); } HttpResponse response; // Upload the media content in chunks. while (true) { currentRequest = requestFactory.buildPutRequest(uploadUrl, null); setContentAndHeadersOnCurrentRequest(); // set mediaErrorHandler as I/O exception handler and as unsuccessful response handler for // calling to serverErrorCallback on an I/O exception or an abnormal HTTP response new MediaUploadErrorHandler(this, currentRequest); if (isMediaLengthKnown()) { // TODO(rmistry): Support gzipping content for the case where media content length is // known (https://code.google.com/p/google-api-java-client/issues/detail?id=691). response = executeCurrentRequestWithoutGZip(currentRequest); } else { response = executeCurrentRequest(currentRequest); } boolean returningResponse = false; try { if (response.isSuccessStatusCode()) { totalBytesServerReceived = getMediaContentLength(); if (mediaContent.getCloseInputStream()) { contentInputStream.close(); } updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); returningResponse = true; return response; } if (response.getStatusCode() != 308) { returningResponse = true; return response; } // Check to see if the upload URL has changed on the server. String updatedUploadUrl = response.getHeaders().getLocation(); if (updatedUploadUrl != null) { uploadUrl = new GenericUrl(updatedUploadUrl); } // we check the amount of bytes the server received so far, because the server may process // fewer bytes than the amount of bytes the client had sent long newBytesServerReceived = getNextByteIndex(response.getHeaders().getRange()); // the server can receive any amount of bytes from 0 to current chunk length long currentBytesServerReceived = newBytesServerReceived - totalBytesServerReceived; Preconditions.checkState( currentBytesServerReceived >= 0 && currentBytesServerReceived <= currentChunkLength); long copyBytes = currentChunkLength - currentBytesServerReceived; if (isMediaLengthKnown()) { if (copyBytes > 0) { // If the server didn't receive all the bytes the client sent the current position of // the input stream is incorrect. So we should reset the stream and skip those bytes // that the server had already received. // Otherwise (the server got all bytes the client sent), the stream is in its right // position, and we can continue from there contentInputStream.reset(); long actualSkipValue = contentInputStream.skip(currentBytesServerReceived); Preconditions.checkState(currentBytesServerReceived == actualSkipValue); } } else if (copyBytes == 0) { // server got all the bytes, so we don't need to use this buffer. Otherwise, we have to // keep the buffer and copy part (or all) of its bytes to the stream we are sending to the // server currentRequestContentBuffer = null; } totalBytesServerReceived = newBytesServerReceived; updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); } finally { if (!returningResponse) { response.disconnect(); } } } } /** * @return {@code true} if the media length is known, otherwise {@code false} */ private boolean isMediaLengthKnown() throws IOException { return getMediaContentLength() >= 0; } /** * Uses lazy initialization to compute the media content length. * * <p> * This is done to avoid throwing an {@link IOException} in the constructor. * </p> */ private long getMediaContentLength() throws IOException { if (!isMediaContentLengthCalculated) { mediaContentLength = mediaContent.getLength(); isMediaContentLengthCalculated = true; } return mediaContentLength; } /** * This method sends a POST request with empty content to get the unique upload URL. * * @param initiationRequestUrl The request URL where the initiation request will be sent */ private HttpResponse executeUploadInitiation(GenericUrl initiationRequestUrl) throws IOException { updateStateAndNotifyListener(UploadState.INITIATION_STARTED); initiationRequestUrl.put("uploadType", "resumable"); HttpContent content = metadata == null ? new EmptyContent() : metadata; HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); initiationHeaders.set(CONTENT_TYPE_HEADER, mediaContent.getType()); if (isMediaLengthKnown()) { initiationHeaders.set(CONTENT_LENGTH_HEADER, getMediaContentLength()); } request.getHeaders().putAll(initiationHeaders); HttpResponse response = executeCurrentRequest(request); boolean notificationCompleted = false; try { updateStateAndNotifyListener(UploadState.INITIATION_COMPLETE); notificationCompleted = true; } finally { if (!notificationCompleted) { response.disconnect(); } } return response; } /** * Executes the current request with some minimal common code. * * @param request current request * @return HTTP response */ private HttpResponse executeCurrentRequestWithoutGZip(HttpRequest request) throws IOException { // method override for non-POST verbs new MethodOverride().intercept(request); // don't throw an exception so we can let a custom Google exception be thrown request.setThrowExceptionOnExecuteError(false); // execute the request HttpResponse response = request.execute(); return response; } /** * Executes the current request with some common code that includes exponential backoff and GZip * encoding. * * @param request current request * @return HTTP response */ private HttpResponse executeCurrentRequest(HttpRequest request) throws IOException { // enable GZip encoding if necessary if (!disableGZipContent && !(request.getContent() instanceof EmptyContent)) { request.setEncoding(new GZipEncoding()); } // execute request HttpResponse response = executeCurrentRequestWithoutGZip(request); return response; } /** * Sets the HTTP media content chunk and the required headers that should be used in the upload * request. */ private void setContentAndHeadersOnCurrentRequest() throws IOException { int blockSize; if (isMediaLengthKnown()) { // We know exactly what the blockSize will be because we know the media content length. blockSize = (int) Math.min(chunkSize, getMediaContentLength() - totalBytesServerReceived); } else { // Use the chunkSize as the blockSize because we do know what what it is yet. blockSize = chunkSize; } AbstractInputStreamContent contentChunk; int actualBlockSize = blockSize; if (isMediaLengthKnown()) { // Mark the current position in case we need to retry the request. contentInputStream.mark(blockSize); InputStream limitInputStream = ByteStreams.limit(contentInputStream, blockSize); contentChunk = new InputStreamContent( mediaContent.getType(), limitInputStream).setRetrySupported(true) .setLength(blockSize).setCloseInputStream(false); mediaContentLengthStr = String.valueOf(getMediaContentLength()); } else { // If the media content length is not known we implement a custom buffered input stream that // enables us to detect the length of the media content when the last chunk is sent. We // accomplish this by always trying to read an extra byte further than the end of the current // chunk. int actualBytesRead; int bytesAllowedToRead; // amount of bytes which need to be copied from last chunk buffer int copyBytes = 0; if (currentRequestContentBuffer == null) { bytesAllowedToRead = cachedByte == null ? blockSize + 1 : blockSize; currentRequestContentBuffer = new byte[blockSize + 1]; if (cachedByte != null) { currentRequestContentBuffer[0] = cachedByte; } } else { // currentRequestContentBuffer is not null that means one of the following: // 1. This is a request to recover from a server error (e.g. 503) // or // 2. The server received less bytes than the amount of bytes the client had sent. For // example, the client sends bytes 100-199, but the server returns back status code 308, // and its "Range" header is "bytes=0-150". // In that case, the new request will be constructed from the previous request's byte buffer // plus new bytes from the stream. copyBytes = (int) (totalBytesClientSent - totalBytesServerReceived); // shift copyBytes bytes to the beginning - those are the bytes which weren't received by // the server in the last chunk. System.arraycopy(currentRequestContentBuffer, currentChunkLength - copyBytes, currentRequestContentBuffer, 0, copyBytes); if (cachedByte != null) { // add the last cached byte to the buffer currentRequestContentBuffer[copyBytes] = cachedByte; } bytesAllowedToRead = blockSize - copyBytes; } actualBytesRead = ByteStreams.read( contentInputStream, currentRequestContentBuffer, blockSize + 1 - bytesAllowedToRead, bytesAllowedToRead); if (actualBytesRead < bytesAllowedToRead) { actualBlockSize = copyBytes + Math.max(0, actualBytesRead); if (cachedByte != null) { actualBlockSize++; cachedByte = null; } if (mediaContentLengthStr.equals("*")) { // At this point we know we reached the media content length because we either read less // than the specified chunk size or there is no more data left to be read. mediaContentLengthStr = String.valueOf(totalBytesServerReceived + actualBlockSize); } } else { cachedByte = currentRequestContentBuffer[blockSize]; } contentChunk = new ByteArrayContent( mediaContent.getType(), currentRequestContentBuffer, 0, actualBlockSize); totalBytesClientSent = totalBytesServerReceived + actualBlockSize; } currentChunkLength = actualBlockSize; currentRequest.setContent(contentChunk); if (actualBlockSize == 0) { // special case of zero content media being uploaded currentRequest.getHeaders().setContentRange("bytes */0"); } else { currentRequest.getHeaders().setContentRange("bytes " + totalBytesServerReceived + "-" + (totalBytesServerReceived + actualBlockSize - 1) + "/" + mediaContentLengthStr); } } /** * {@link Beta} <br/> * The call back method that will be invoked on a server error or an I/O exception during * resumable upload inside {@link #upload}. * * <p> * This method changes the current request to query the current status of the upload to find how * many bytes were successfully uploaded before the server error occurred. * </p> */ @Beta void serverErrorCallback() throws IOException { Preconditions.checkNotNull(currentRequest, "The current request should not be null"); // Query the current status of the upload by issuing an empty PUT request on the upload URI. currentRequest.setContent(new EmptyContent()); currentRequest.getHeaders() .setContentRange("bytes */" + (isMediaLengthKnown() ? getMediaContentLength() : "*")); } /** * Returns the next byte index identifying data that the server has not yet received, obtained * from the HTTP Range header (E.g a header of "Range: 0-55" would cause 56 to be returned). * <code>null</code> or malformed headers cause 0 to be returned. * * @param rangeHeader in the HTTP response * @return the byte index beginning where the server has yet to receive data */ private long getNextByteIndex(String rangeHeader) { if (rangeHeader == null) { return 0L; } return Long.parseLong(rangeHeader.substring(rangeHeader.indexOf('-') + 1)) + 1; } /** Returns HTTP content metadata for the media request or {@code null} for none. */ public HttpContent getMetadata() { return metadata; } /** Sets HTTP content metadata for the media request or {@code null} for none. */ public MediaHttpUploader setMetadata(HttpContent metadata) { this.metadata = metadata; return this; } /** Returns the HTTP content of the media to be uploaded. */ public HttpContent getMediaContent() { return mediaContent; } /** Returns the transport to use for requests. */ public HttpTransport getTransport() { return transport; } /** * Sets whether direct media upload is enabled or disabled. * * <p> * If value is set to {@code true} then a direct upload will be done where the whole media content * is uploaded in a single request. If value is set to {@code false} then the upload uses the * resumable media upload protocol to upload in data chunks. * </p> * * <p> * Direct upload is recommended if the content size falls below a certain minimum limit. This is * because there's minimum block write size for some Google APIs, so if the resumable request * fails in the space of that first block, the client will have to restart from the beginning * anyway. * </p> * * <p> * Defaults to {@code false}. * </p> * * @since 1.9 */ public MediaHttpUploader setDirectUploadEnabled(boolean directUploadEnabled) { this.directUploadEnabled = directUploadEnabled; return this; } /** * Returns whether direct media upload is enabled or disabled. If value is set to {@code true} * then a direct upload will be done where the whole media content is uploaded in a single * request. If value is set to {@code false} then the upload uses the resumable media upload * protocol to upload in data chunks. Defaults to {@code false}. * * @since 1.9 */ public boolean isDirectUploadEnabled() { return directUploadEnabled; } /** * Sets the progress listener to send progress notifications to or {@code null} for none. */ public MediaHttpUploader setProgressListener(MediaHttpUploaderProgressListener progressListener) { this.progressListener = progressListener; return this; } /** * Returns the progress listener to send progress notifications to or {@code null} for none. */ public MediaHttpUploaderProgressListener getProgressListener() { return progressListener; } /** * Sets the maximum size of individual chunks that will get uploaded by single HTTP requests. The * default value is {@link #DEFAULT_CHUNK_SIZE}. * * <p> * The minimum allowable value is {@link #MINIMUM_CHUNK_SIZE} and the specified chunk size must be * a multiple of {@link #MINIMUM_CHUNK_SIZE}. * </p> */ public MediaHttpUploader setChunkSize(int chunkSize) { Preconditions.checkArgument(chunkSize > 0 && chunkSize % MINIMUM_CHUNK_SIZE == 0); this.chunkSize = chunkSize; return this; } /** * Returns the maximum size of individual chunks that will get uploaded by single HTTP requests. * The default value is {@link #DEFAULT_CHUNK_SIZE}. */ public int getChunkSize() { return chunkSize; } /** * Returns whether to disable GZip compression of HTTP content. * * @since 1.13 */ public boolean getDisableGZipContent() { return disableGZipContent; } /** * Sets whether to disable GZip compression of HTTP content. * * <p> * By default it is {@code false}. * </p> * * <p> * If {@link #setDisableGZipContent(boolean)} is set to false (the default value) then content is * gzipped for direct media upload and resumable media uploads when content length is not known. * Due to a current limitation, content is not gzipped for resumable media uploads when content * length is known; this limitation will be removed in the future. * </p> * * @since 1.13 */ public MediaHttpUploader setDisableGZipContent(boolean disableGZipContent) { this.disableGZipContent = disableGZipContent; return this; } /** * Returns the sleeper. * * @since 1.15 */ public Sleeper getSleeper() { return sleeper; } /** * Sets the sleeper. The default value is {@link Sleeper#DEFAULT}. * * @since 1.15 */ public MediaHttpUploader setSleeper(Sleeper sleeper) { this.sleeper = sleeper; return this; } /** * Returns the HTTP method used for the initiation request. * * <p> * The default value is {@link HttpMethods#POST}. * </p> * * @since 1.12 */ public String getInitiationRequestMethod() { return initiationRequestMethod; } /** * Sets the HTTP method used for the initiation request. * * <p> * Can only be {@link HttpMethods#POST} (for media upload) or {@link HttpMethods#PUT} (for media * update). The default value is {@link HttpMethods#POST}. * </p> * * @since 1.12 */ public MediaHttpUploader setInitiationRequestMethod(String initiationRequestMethod) { Preconditions.checkArgument(initiationRequestMethod.equals(HttpMethods.POST) || initiationRequestMethod.equals(HttpMethods.PUT)); this.initiationRequestMethod = initiationRequestMethod; return this; } /** Sets the HTTP headers used for the initiation request. */ public MediaHttpUploader setInitiationHeaders(HttpHeaders initiationHeaders) { this.initiationHeaders = initiationHeaders; return this; } /** Returns the HTTP headers used for the initiation request. */ public HttpHeaders getInitiationHeaders() { return initiationHeaders; } /** * Gets the total number of bytes the server received so far or {@code 0} for direct uploads when * the content length is not known. * * @return the number of bytes the server received so far */ public long getNumBytesUploaded() { return totalBytesServerReceived; } /** * Sets the upload state and notifies the progress listener. * * @param uploadState value to set to */ private void updateStateAndNotifyListener(UploadState uploadState) throws IOException { this.uploadState = uploadState; if (progressListener != null) { progressListener.progressChanged(this); } } /** * Gets the current upload state of the uploader. * * @return the upload state */ public UploadState getUploadState() { return uploadState; } /** * Gets the upload progress denoting the percentage of bytes that have been uploaded, represented * between 0.0 (0%) and 1.0 (100%). * * <p> * Do not use if the specified {@link AbstractInputStreamContent} has no content length specified. * Instead, consider using {@link #getNumBytesUploaded} to denote progress. * </p> * * @throws IllegalArgumentException if the specified {@link AbstractInputStreamContent} has no * content length * @return the upload progress */ public double getProgress() throws IOException { Preconditions.checkArgument(isMediaLengthKnown(), "Cannot call getProgress() if " + "the specified AbstractInputStreamContent has no content length. Use " + " getNumBytesUploaded() to denote progress instead."); return getMediaContentLength() == 0 ? 0 : (double) totalBytesServerReceived / getMediaContentLength(); } }
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.media; import java.io.IOException; /** * An interface for receiving progress notifications for downloads. * * <p> * Sample usage: * </p> * * <pre> public static class MyDownloadProgressListener implements MediaHttpDownloaderProgressListener { public void progressChanged(MediaHttpDownloader downloader) throws IOException { switch (downloader.getDownloadState()) { case MEDIA_IN_PROGRESS: System.out.println("Download in progress"); System.out.println("Download percentage: " + downloader.getProgress()); break; case MEDIA_COMPLETE: System.out.println("Download Completed!"); break; } } } * </pre> * * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ public interface MediaHttpDownloaderProgressListener { /** * Called to notify that progress has been changed. * * <p> * This method is called multiple times depending on how many chunks are downloaded. Once the * download completes it is called one final time. * </p> * * <p> * The download state can be queried by calling {@link MediaHttpDownloader#getDownloadState} and * the progress by calling {@link MediaHttpDownloader#getProgress}. * </p> * * @param downloader Media HTTP downloader */ public void progressChanged(MediaHttpDownloader downloader) throws IOException; }
Java
/* * Copyright (c) 2011 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 com.google.api.client.googleapis.media; import java.io.IOException; /** * An interface for receiving progress notifications for uploads. * * <p> * Sample usage (if media content length is provided, else consider using * {@link MediaHttpUploader#getNumBytesUploaded} instead of {@link MediaHttpUploader#getProgress}: * </p> * * <pre> public static class MyUploadProgressListener implements MediaHttpUploaderProgressListener { public void progressChanged(MediaHttpUploader uploader) throws IOException { switch (uploader.getUploadState()) { case INITIATION_STARTED: System.out.println("Initiation Started"); break; case INITIATION_COMPLETE: System.out.println("Initiation Completed"); break; case MEDIA_IN_PROGRESS: System.out.println("Upload in progress"); System.out.println("Upload percentage: " + uploader.getProgress()); break; case MEDIA_COMPLETE: System.out.println("Upload Completed!"); break; } } } * </pre> * * @since 1.9 * @author rmistry@google.com (Ravi Mistry) */ public interface MediaHttpUploaderProgressListener { /** * Called to notify that progress has been changed. * * <p> * This method is called once before and after the initiation request. For media uploads it is * called multiple times depending on how many chunks are uploaded. Once the upload completes it * is called one final time. * </p> * * <p> * The upload state can be queried by calling {@link MediaHttpUploader#getUploadState} and the * progress by calling {@link MediaHttpUploader#getProgress}. * </p> * * @param uploader Media HTTP uploader */ public void progressChanged(MediaHttpUploader uploader) throws IOException; }
Java
/* * Copyright (c) 2012 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 com.google.api.client.googleapis.media; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpBackOffIOExceptionHandler; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.IOUtils; import com.google.api.client.util.Preconditions; import java.io.IOException; import java.io.OutputStream; /** * Media HTTP Downloader, with support for both direct and resumable media downloads. Documentation * is available <a * href='http://code.google.com/p/google-api-java-client/wiki/MediaDownload'>here</a>. * * <p> * Implementation is not thread-safe. * </p> * * <p> * Back-off is disabled by default. To enable it for an abnormal HTTP response and an I/O exception * you should call {@link HttpRequest#setUnsuccessfulResponseHandler} with a new * {@link HttpBackOffUnsuccessfulResponseHandler} instance and * {@link HttpRequest#setIOExceptionHandler} with {@link HttpBackOffIOExceptionHandler}. * </p> * * <p> * Upgrade warning: in prior version 1.14 exponential back-off was enabled by default for an * abnormal HTTP response. Starting with version 1.15 it's disabled by default. * </p> * * @since 1.9 * * @author rmistry@google.com (Ravi Mistry) */ @SuppressWarnings("deprecation") public final class MediaHttpDownloader { /** * Download state associated with the Media HTTP downloader. */ public enum DownloadState { /** The download process has not started yet. */ NOT_STARTED, /** Set after a media file chunk is downloaded. */ MEDIA_IN_PROGRESS, /** Set after the complete media file is successfully downloaded. */ MEDIA_COMPLETE } /** * Default maximum number of bytes that will be downloaded from the server in any single HTTP * request. Set to 32MB because that is the maximum App Engine request size. */ public static final int MAXIMUM_CHUNK_SIZE = 32 * MediaHttpUploader.MB; /** The request factory for connections to the server. */ private final HttpRequestFactory requestFactory; /** The transport to use for requests. */ private final HttpTransport transport; /** * Determines whether direct media download is enabled or disabled. If value is set to * {@code true} then a direct download will be done where the whole media content is downloaded in * a single request. If value is set to {@code false} then the download uses the resumable media * download protocol to download in data chunks. Defaults to {@code false}. */ private boolean directDownloadEnabled = false; /** * Progress listener to send progress notifications to or {@code null} for none. */ private MediaHttpDownloaderProgressListener progressListener; /** * Maximum size of individual chunks that will get downloaded by single HTTP requests. The default * value is {@link #MAXIMUM_CHUNK_SIZE}. */ private int chunkSize = MAXIMUM_CHUNK_SIZE; /** * The length of the HTTP media content or {@code 0} before it is initialized in * {@link #setMediaContentLength}. */ private long mediaContentLength; /** The current state of the downloader. */ private DownloadState downloadState = DownloadState.NOT_STARTED; /** The total number of bytes downloaded by this downloader. */ private long bytesDownloaded; /** * The last byte position of the media file we want to download, default value is {@code -1}. * * <p> * If its value is {@code -1} it means there is no upper limit on the byte position. * </p> */ private long lastBytePos = -1; /** * Construct the {@link MediaHttpDownloader}. * * @param transport The transport to use for requests * @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or * {@code null} for none */ public MediaHttpDownloader( HttpTransport transport, HttpRequestInitializer httpRequestInitializer) { this.transport = Preconditions.checkNotNull(transport); this.requestFactory = httpRequestInitializer == null ? transport.createRequestFactory() : transport.createRequestFactory(httpRequestInitializer); } /** * Executes a direct media download or a resumable media download. * * <p> * This method does not close the given output stream. * </p> * * <p> * This method is not reentrant. A new instance of {@link MediaHttpDownloader} must be * instantiated before download called be called again. * </p> * * @param requestUrl The request URL where the download requests will be sent * @param outputStream destination output stream */ public void download(GenericUrl requestUrl, OutputStream outputStream) throws IOException { download(requestUrl, null, outputStream); } /** * Executes a direct media download or a resumable media download. * * <p> * This method does not close the given output stream. * </p> * * <p> * This method is not reentrant. A new instance of {@link MediaHttpDownloader} must be * instantiated before download called be called again. * </p> * * @param requestUrl request URL where the download requests will be sent * @param requestHeaders request headers or {@code null} to ignore * @param outputStream destination output stream * @since 1.12 */ public void download(GenericUrl requestUrl, HttpHeaders requestHeaders, OutputStream outputStream) throws IOException { Preconditions.checkArgument(downloadState == DownloadState.NOT_STARTED); requestUrl.put("alt", "media"); if (directDownloadEnabled) { updateStateAndNotifyListener(DownloadState.MEDIA_IN_PROGRESS); HttpResponse response = executeCurrentRequest(lastBytePos, requestUrl, requestHeaders, outputStream); // All required bytes have been downloaded from the server. mediaContentLength = response.getHeaders().getContentLength(); bytesDownloaded = mediaContentLength; updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE); return; } // Download the media content in chunks. while (true) { long currentRequestLastBytePos = bytesDownloaded + chunkSize - 1; if (lastBytePos != -1) { // If last byte position has been specified use it iff it is smaller than the chunksize. currentRequestLastBytePos = Math.min(lastBytePos, currentRequestLastBytePos); } HttpResponse response = executeCurrentRequest( currentRequestLastBytePos, requestUrl, requestHeaders, outputStream); String contentRange = response.getHeaders().getContentRange(); long nextByteIndex = getNextByteIndex(contentRange); setMediaContentLength(contentRange); if (mediaContentLength <= nextByteIndex) { // All required bytes have been downloaded from the server. bytesDownloaded = mediaContentLength; updateStateAndNotifyListener(DownloadState.MEDIA_COMPLETE); return; } bytesDownloaded = nextByteIndex; updateStateAndNotifyListener(DownloadState.MEDIA_IN_PROGRESS); } } /** * Executes the current request. * * @param currentRequestLastBytePos last byte position for current request * @param requestUrl request URL where the download requests will be sent * @param requestHeaders request headers or {@code null} to ignore * @param outputStream destination output stream * @return HTTP response */ private HttpResponse executeCurrentRequest(long currentRequestLastBytePos, GenericUrl requestUrl, HttpHeaders requestHeaders, OutputStream outputStream) throws IOException { // prepare the GET request HttpRequest request = requestFactory.buildGetRequest(requestUrl); // add request headers if (requestHeaders != null) { request.getHeaders().putAll(requestHeaders); } // set Range header (if necessary) if (bytesDownloaded != 0 || currentRequestLastBytePos != -1) { StringBuilder rangeHeader = new StringBuilder(); rangeHeader.append("bytes=").append(bytesDownloaded).append("-"); if (currentRequestLastBytePos != -1) { rangeHeader.append(currentRequestLastBytePos); } request.getHeaders().setRange(rangeHeader.toString()); } // execute the request and copy into the output stream HttpResponse response = request.execute(); try { IOUtils.copy(response.getContent(), outputStream); } finally { response.disconnect(); } return response; } /** * Returns the next byte index identifying data that the server has not yet sent out, obtained * from the HTTP Content-Range header (E.g a header of "Content-Range: 0-55/1000" would cause 56 * to be returned). <code>null</code> headers cause 0 to be returned. * * @param rangeHeader in the HTTP response * @return the byte index beginning where the server has yet to send out data */ private long getNextByteIndex(String rangeHeader) { if (rangeHeader == null) { return 0L; } return Long.parseLong( rangeHeader.substring(rangeHeader.indexOf('-') + 1, rangeHeader.indexOf('/'))) + 1; } /** * Sets the total number of bytes that have been downloaded of the media resource. * * <p> * If a download was aborted mid-way due to a connection failure then users can resume the * download from the point where it left off. * </p> * * <p> * Use {@link #setContentRange} if you need to specify both the bytes downloaded and the last byte * position. * </p> * * @param bytesDownloaded The total number of bytes downloaded */ public MediaHttpDownloader setBytesDownloaded(long bytesDownloaded) { Preconditions.checkArgument(bytesDownloaded >= 0); this.bytesDownloaded = bytesDownloaded; return this; } /** * Sets the content range of the next download request. Eg: bytes=firstBytePos-lastBytePos. * * <p> * If a download was aborted mid-way due to a connection failure then users can resume the * download from the point where it left off. * </p> * * <p> * Use {@link #setBytesDownloaded} if you only need to specify the first byte position. * </p> * * @param firstBytePos The first byte position in the content range string * @param lastBytePos The last byte position in the content range string. * @since 1.13 */ public MediaHttpDownloader setContentRange(long firstBytePos, int lastBytePos) { Preconditions.checkArgument(lastBytePos >= firstBytePos); setBytesDownloaded(firstBytePos); this.lastBytePos = lastBytePos; return this; } /** * Sets the media content length from the HTTP Content-Range header (E.g a header of * "Content-Range: 0-55/1000" would cause 1000 to be set. <code>null</code> headers do not set * anything. * * @param rangeHeader in the HTTP response */ private void setMediaContentLength(String rangeHeader) { if (rangeHeader == null) { return; } if (mediaContentLength == 0) { mediaContentLength = Long.parseLong(rangeHeader.substring(rangeHeader.indexOf('/') + 1)); } } /** * Returns whether direct media download is enabled or disabled. If value is set to {@code true} * then a direct download will be done where the whole media content is downloaded in a single * request. If value is set to {@code false} then the download uses the resumable media download * protocol to download in data chunks. Defaults to {@code false}. */ public boolean isDirectDownloadEnabled() { return directDownloadEnabled; } /** * Returns whether direct media download is enabled or disabled. If value is set to {@code true} * then a direct download will be done where the whole media content is downloaded in a single * request. If value is set to {@code false} then the download uses the resumable media download * protocol to download in data chunks. Defaults to {@code false}. */ public MediaHttpDownloader setDirectDownloadEnabled(boolean directDownloadEnabled) { this.directDownloadEnabled = directDownloadEnabled; return this; } /** * Sets the progress listener to send progress notifications to or {@code null} for none. */ public MediaHttpDownloader setProgressListener( MediaHttpDownloaderProgressListener progressListener) { this.progressListener = progressListener; return this; } /** * Returns the progress listener to send progress notifications to or {@code null} for none. */ public MediaHttpDownloaderProgressListener getProgressListener() { return progressListener; } /** Returns the transport to use for requests. */ public HttpTransport getTransport() { return transport; } /** * Sets the maximum size of individual chunks that will get downloaded by single HTTP requests. * The default value is {@link #MAXIMUM_CHUNK_SIZE}. * * <p> * The maximum allowable value is {@link #MAXIMUM_CHUNK_SIZE}. * </p> */ public MediaHttpDownloader setChunkSize(int chunkSize) { Preconditions.checkArgument(chunkSize > 0 && chunkSize <= MAXIMUM_CHUNK_SIZE); this.chunkSize = chunkSize; return this; } /** * Returns the maximum size of individual chunks that will get downloaded by single HTTP requests. * The default value is {@link #MAXIMUM_CHUNK_SIZE}. */ public int getChunkSize() { return chunkSize; } /** * Gets the total number of bytes downloaded by this downloader. * * @return the number of bytes downloaded */ public long getNumBytesDownloaded() { return bytesDownloaded; } /** * Gets the last byte position of the media file we want to download or {@code -1} if there is no * upper limit on the byte position. * * @return the last byte position * @since 1.13 */ public long getLastBytePosition() { return lastBytePos; } /** * Sets the download state and notifies the progress listener. * * @param downloadState value to set to */ private void updateStateAndNotifyListener(DownloadState downloadState) throws IOException { this.downloadState = downloadState; if (progressListener != null) { progressListener.progressChanged(this); } } /** * Gets the current download state of the downloader. * * @return the download state */ public DownloadState getDownloadState() { return downloadState; } /** * Gets the download progress denoting the percentage of bytes that have been downloaded, * represented between 0.0 (0%) and 1.0 (100%). * * @return the download progress */ public double getProgress() { return mediaContentLength == 0 ? 0 : (double) bytesDownloaded / mediaContentLength; } }
Java