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.util;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.SharedPreferences;
import android.os.HandlerThread;
/**
* A set of methods that may be implemented in a platform specific way.
*
* @author Bartlomiej Niechwiej
*/
public interface ApiPlatformAdapter {
/**
* Puts the specified service into foreground.
*
* @param service the service to be put in foreground.
* @param notificationManager the notification manager used to post the given
* notification.
* @param id the ID of the notification, unique within the application.
* @param notification the notification to post.
*/
void startForeground(Service service, NotificationManager notificationManager,
int id, Notification notification);
/**
* Puts the given service into background.
* @param service the service to put into background.
* @param notificationManager the notification manager to user when removing
* notifications.
* @param id the ID of the notification to be remove, or -1 if the
* notification shouldn't be removed.
*/
void stopForeground(Service service, NotificationManager notificationManager,
int id);
/**
* Terminates the given handler thread.
*
* @param handlerThread the thread to be terminated.
* @return true whether the handler has been stopped or not.
*/
boolean stopHandlerThread(HandlerThread handlerThread);
/**
* Applies all changes done to the given preferences editor.
* Changes may or may not be applied immediately.
*/
void applyPreferenceChanges(SharedPreferences.Editor editor);
/**
* Enables strict mode where supported, only if this is a development build.
*/
void enableStrictMode();
}
| 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.util;
import com.google.android.apps.mytracks.MyTracksSettings;
import com.google.android.apps.mytracks.content.DescriptionGenerator;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Various string manipulation methods.
*
* @author Sandor Dornbush
* @author Rodrigo Damazio
*/
public class StringUtils implements DescriptionGenerator {
private final Context context;
/**
* Formats a number of milliseconds as a string.
*
* @param time - A period of time in milliseconds.
* @return A string of the format M:SS, MM:SS or HH:MM:SS
*/
public static String formatTime(long time) {
return formatTimeInternal(time, false);
}
/**
* Formats a number of milliseconds as a string. To be used when we need the
* hours to be shown even when it is zero, e.g. exporting data to a
* spreadsheet.
*
* @param time - A period of time in milliseconds
* @return A string of the format HH:MM:SS even if time is less than 1 hour
*/
public static String formatTimeAlwaysShowingHours(long time) {
return formatTimeInternal(time, true);
}
/**
* Formats the given text as a CDATA element to be used in a XML file. This
* includes adding the starting and ending CDATA tags. Please notice that this
* may result in multiple consecutive CDATA tags.
*
* @param unescaped the unescaped text to be formatted
* @return the formatted text, inside one or more CDATA tags
*/
public static String stringAsCData(String unescaped) {
// "]]>" needs to be broken into multiple CDATA segments, like:
// "Foo]]>Bar" becomes "<![CDATA[Foo]]]]><![CDATA[>Bar]]>"
// (the end of the first CDATA has the "]]", the other has ">")
String escaped = unescaped.replaceAll("]]>", "]]]]><![CDATA[>");
return "<![CDATA[" + escaped + "]]>";
}
private static final SimpleDateFormat BASE_XML_DATE_FORMAT =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
static {
BASE_XML_DATE_FORMAT.setTimeZone(new SimpleTimeZone(0, "UTC"));
}
private static final Pattern XML_DATE_EXTRAS_PATTERN =
Pattern.compile("^(\\.\\d+)?(?:Z|([+-])(\\d{2}):(\\d{2}))?$");
/**
* Parses an XML dateTime element as defined by the XML standard.
*
* @see <a href="http://www.w3.org/TR/xmlschema-2/#dateTime">dateTime</a>
*/
public static long parseXmlDateTime(String xmlTime) {
// Parse the base date (fixed format)
ParsePosition position = new ParsePosition(0);
Date date = BASE_XML_DATE_FORMAT.parse(xmlTime, position);
if (date == null) {
throw new IllegalArgumentException("Invalid XML dateTime value: '" + xmlTime
+ "' (at position " + position.getErrorIndex() + ")");
}
// Parse the extras
Matcher matcher =
XML_DATE_EXTRAS_PATTERN.matcher(xmlTime.substring(position.getIndex()));
if (!matcher.matches()) {
// This will match even an empty string as all groups are optional,
// so a non-match means some other garbage was there
throw new IllegalArgumentException("Invalid XML dateTime value: " + xmlTime);
}
long time = date.getTime();
// Account for fractional seconds
String fractional = matcher.group(1);
if (fractional != null) {
// Regex ensures fractional part is in (0,1(
float fractionalSeconds = Float.parseFloat(fractional);
long fractionalMillis = (long) (fractionalSeconds * 1000.0f);
time += fractionalMillis;
}
// Account for timezones
String sign = matcher.group(2);
String offsetHoursStr = matcher.group(3);
String offsetMinsStr = matcher.group(4);
if (sign != null && offsetHoursStr != null && offsetMinsStr != null) {
// Regex ensures sign is + or -
boolean plusSign = sign.equals("+");
int offsetHours = Integer.parseInt(offsetHoursStr);
int offsetMins = Integer.parseInt(offsetMinsStr);
// Regex ensures values are >= 0
if (offsetHours > 14 || offsetMins > 59) {
throw new IllegalArgumentException("Bad timezone in " + xmlTime);
}
long totalOffsetMillis = (offsetMins + offsetHours * 60L) * 60000L;
// Make time go back to UTC
if (plusSign) {
time -= totalOffsetMillis;
} else {
time += totalOffsetMillis;
}
}
return time;
}
/**
* Formats a number of milliseconds as a string.
*
* @param time - A period of time in milliseconds
* @param alwaysShowHours - Whether to display 00 hours if time is less than 1
* hour
* @return A string of the format HH:MM:SS
*/
private static String formatTimeInternal(long time, boolean alwaysShowHours) {
int[] parts = getTimeParts(time);
StringBuilder builder = new StringBuilder();
if (parts[2] > 0 || alwaysShowHours) {
builder.append(parts[2]);
builder.append(':');
if (parts[1] <= 9) {
builder.append("0");
}
}
builder.append(parts[1]);
builder.append(':');
if (parts[0] <= 9) {
builder.append("0");
}
builder.append(parts[0]);
return builder.toString();
}
/**
* Gets the time as an array of parts.
*/
public static int[] getTimeParts(long time) {
if (time < 0) {
int[] parts = getTimeParts(time * -1);
parts[0] *= -1;
parts[1] *= -1;
parts[2] *= -1;
return parts;
}
int[] parts = new int[3];
long seconds = time / 1000;
parts[0] = (int) (seconds % 60);
int tmp = (int) (seconds / 60);
parts[1] = tmp % 60;
parts[2] = tmp / 60;
return parts;
}
public StringUtils(Context context) {
this.context = context;
}
public String formatTimeLong(long time) {
int[] parts = getTimeParts(time);
String secLabel =
context.getString(parts[0] == 1 ? R.string.second : R.string.seconds);
String minLabel =
context.getString(parts[1] == 1 ? R.string.minute : R.string.minutes);
String hourLabel =
context.getString(parts[2] == 1 ? R.string.hour : R.string.hours);
StringBuilder sb = new StringBuilder();
if (parts[2] != 0) {
sb.append(parts[2]);
sb.append(" ");
sb.append(hourLabel);
sb.append(" ");
sb.append(parts[1]);
sb.append(minLabel);
} else {
sb.append(parts[1]);
sb.append(" ");
sb.append(minLabel);
sb.append(" ");
sb.append(parts[0]);
sb.append(secLabel);
}
return sb.toString();
}
/**
* Generates a description for a track (with information about the
* statistics).
*
* @param track the track
* @return a track description
*/
public String generateTrackDescription(Track track, Vector<Double> distances,
Vector<Double> elevations) {
boolean displaySpeed = true;
SharedPreferences preferences =
context.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0);
if (preferences != null) {
displaySpeed =
preferences.getBoolean(context.getString(R.string.report_speed_key), true);
}
TripStatistics trackStats = track.getStatistics();
final double distanceInKm = trackStats.getTotalDistance() / 1000;
final double distanceInMiles = distanceInKm * UnitConversions.KM_TO_MI;
final long minElevationInMeters = Math.round(trackStats.getMinElevation());
final long minElevationInFeet =
Math.round(trackStats.getMinElevation() * UnitConversions.M_TO_FT);
final long maxElevationInMeters = Math.round(trackStats.getMaxElevation());
final long maxElevationInFeet =
Math.round(trackStats.getMaxElevation() * UnitConversions.M_TO_FT);
final long elevationGainInMeters =
Math.round(trackStats.getTotalElevationGain());
final long elevationGainInFeet = Math.round(
trackStats.getTotalElevationGain() * UnitConversions.M_TO_FT);
long minGrade = 0;
long maxGrade = 0;
double trackMaxGrade = trackStats.getMaxGrade();
double trackMinGrade = trackStats.getMinGrade();
if (!Double.isNaN(trackMaxGrade)
&& !Double.isInfinite(trackMaxGrade)) {
maxGrade = Math.round(trackMaxGrade * 100);
}
if (!Double.isNaN(trackMinGrade) && !Double.isInfinite(trackMinGrade)) {
minGrade = Math.round(trackMinGrade * 100);
}
String category = context.getString(R.string.unknown);
String trackCategory = track.getCategory();
if (trackCategory != null && trackCategory.length() > 0) {
category = trackCategory;
}
String averageSpeed =
getSpeedString(trackStats.getAverageSpeed(),
R.string.average_speed_label,
R.string.average_pace_label,
displaySpeed);
String averageMovingSpeed =
getSpeedString(trackStats.getAverageMovingSpeed(),
R.string.average_moving_speed_label,
R.string.average_moving_pace_label,
displaySpeed);
String maxSpeed =
getSpeedString(trackStats.getMaxSpeed(),
R.string.max_speed_label,
R.string.min_pace_label,
displaySpeed);
return String.format("%s<p>"
+ "%s: %.2f %s (%.1f %s)<br>"
+ "%s: %s<br>"
+ "%s: %s<br>"
+ "%s %s %s"
+ "%s: %d %s (%d %s)<br>"
+ "%s: %d %s (%d %s)<br>"
+ "%s: %d %s (%d %s)<br>"
+ "%s: %d %%<br>"
+ "%s: %d %%<br>"
+ "%s: %tc<br>"
+ "%s: %s<br>"
+ "<img border=\"0\" src=\"%s\"/>",
// Line 1
context.getString(R.string.fusiontable_link),
// Line 2
context.getString(R.string.total_distance_label),
distanceInKm, context.getString(R.string.kilometer),
distanceInMiles, context.getString(R.string.mile),
// Line 3
context.getString(R.string.total_time_label),
StringUtils.formatTime(trackStats.getTotalTime()),
// Line 4
context.getString(R.string.moving_time_label),
StringUtils.formatTime(trackStats.getMovingTime()),
// Line 5
averageSpeed, averageMovingSpeed, maxSpeed,
// Line 6
context.getString(R.string.min_elevation_label),
minElevationInMeters, context.getString(R.string.meter),
minElevationInFeet, context.getString(R.string.feet),
// Line 7
context.getString(R.string.max_elevation_label),
maxElevationInMeters, context.getString(R.string.meter),
maxElevationInFeet, context.getString(R.string.feet),
// Line 8
context.getString(R.string.elevation_gain_label),
elevationGainInMeters, context.getString(R.string.meter),
elevationGainInFeet, context.getString(R.string.feet),
// Line 9
context.getString(R.string.max_grade_label), maxGrade,
// Line 10
context.getString(R.string.min_grade_label), minGrade,
// Line 11
context.getString(R.string.recorded_date),
new Date(trackStats.getStartTime()),
// Line 12
context.getString(R.string.category), category,
// Line 13
ChartURLGenerator.getChartUrl(distances, elevations, track, context));
}
private String getSpeedString(double speed, int speedLabel, int paceLabel,
boolean displaySpeed) {
double speedInKph = speed * 3.6;
double speedInMph = speedInKph * UnitConversions.KMH_TO_MPH;
if (displaySpeed) {
return String.format("%s: %.2f %s (%.1f %s)<br>",
context.getString(speedLabel),
speedInKph, context.getString(R.string.kilometer_per_hour),
speedInMph, context.getString(R.string.mile_per_hour));
} else {
double paceInKm;
double paceInMi;
if (speed == 0) {
paceInKm = 0.0;
paceInMi = 0.0;
} else {
paceInKm = 60.0 / speedInKph;
paceInMi = 60.0 / speedInMph;
}
return String.format("%s: %.2f %s (%.1f %s)<br>",
context.getString(paceLabel),
paceInKm, context.getString(R.string.min_per_kilometer),
paceInMi, context.getString(R.string.min_per_mile));
}
}
/**
* Generates a description for a waypoint (with information about the
* statistics).
*
* @return a track description
*/
public String generateWaypointDescription(Waypoint waypoint) {
TripStatistics stats = waypoint.getStatistics();
final double distanceInKm = stats.getTotalDistance() / 1000;
final double distanceInMiles = distanceInKm * UnitConversions.KM_TO_MI;
final double averageSpeedInKmh = stats.getAverageSpeed() * 3.6;
final double averageSpeedInMph =
averageSpeedInKmh * UnitConversions.KMH_TO_MPH;
final double movingSpeedInKmh = stats.getAverageMovingSpeed() * 3.6;
final double movingSpeedInMph =
movingSpeedInKmh * UnitConversions.KMH_TO_MPH;
final double maxSpeedInKmh = stats.getMaxSpeed() * 3.6;
final double maxSpeedInMph = maxSpeedInKmh * UnitConversions.KMH_TO_MPH;
final long minElevationInMeters = Math.round(stats.getMinElevation());
final long minElevationInFeet =
Math.round(stats.getMinElevation() * UnitConversions.M_TO_FT);
final long maxElevationInMeters = Math.round(stats.getMaxElevation());
final long maxElevationInFeet =
Math.round(stats.getMaxElevation() * UnitConversions.M_TO_FT);
final long elevationGainInMeters =
Math.round(stats.getTotalElevationGain());
final long elevationGainInFeet = Math.round(
stats.getTotalElevationGain() * UnitConversions.M_TO_FT);
long theMinGrade = 0;
long theMaxGrade = 0;
double maxGrade = stats.getMaxGrade();
double minGrade = stats.getMinGrade();
if (!Double.isNaN(maxGrade) &&
!Double.isInfinite(maxGrade)) {
theMaxGrade = Math.round(maxGrade * 100);
}
if (!Double.isNaN(minGrade) &&
!Double.isInfinite(minGrade)) {
theMinGrade = Math.round(minGrade * 100);
}
final String percent = "%";
return String.format(
"%s: %.2f %s (%.1f %s)\n"
+ "%s: %s\n"
+ "%s: %s\n"
+ "%s: %.2f %s (%.1f %s)\n"
+ "%s: %.2f %s (%.1f %s)\n"
+ "%s: %.2f %s (%.1f %s)\n"
+ "%s: %d %s (%d %s)\n"
+ "%s: %d %s (%d %s)\n"
+ "%s: %d %s (%d %s)\n"
+ "%s: %d %s\n"
+ "%s: %d %s\n",
context.getString(R.string.distance_label),
distanceInKm, context.getString(R.string.kilometer),
distanceInMiles, context.getString(R.string.mile),
context.getString(R.string.time_label),
StringUtils.formatTime(stats.getTotalTime()),
context.getString(R.string.moving_time_label),
StringUtils.formatTime(stats.getMovingTime()),
context.getString(R.string.average_speed_label),
averageSpeedInKmh, context.getString(R.string.kilometer_per_hour),
averageSpeedInMph, context.getString(R.string.mile_per_hour),
context.getString(R.string.average_moving_speed_label),
movingSpeedInKmh, context.getString(R.string.kilometer_per_hour),
movingSpeedInMph, context.getString(R.string.mile_per_hour),
context.getString(R.string.max_speed_label),
maxSpeedInKmh, context.getString(R.string.kilometer_per_hour),
maxSpeedInMph, context.getString(R.string.mile_per_hour),
context.getString(R.string.min_elevation_label),
minElevationInMeters, context.getString(R.string.meter),
minElevationInFeet, context.getString(R.string.feet),
context.getString(R.string.max_elevation_label),
maxElevationInMeters, context.getString(R.string.meter),
maxElevationInFeet, context.getString(R.string.feet),
context.getString(R.string.elevation_gain_label),
elevationGainInMeters, context.getString(R.string.meter),
elevationGainInFeet, context.getString(R.string.feet),
context.getString(R.string.max_grade_label),
theMaxGrade, percent,
context.getString(R.string.min_grade_label),
theMinGrade, percent);
}
}
| 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.util;
/**
* Unit conversion constants.
*
* @author Sandor Dornbush
*/
public abstract class UnitConversions {
public static final double KM_TO_MI = 0.621371192;
public static final double M_TO_FT = 3.2808399;
public static final double MI_TO_M = 1609.344;
public static final double MI_TO_FEET = 5280.0;
public static final double KMH_TO_MPH = 1000 * M_TO_FT / MI_TO_FEET;
public static final double TO_RADIANS = Math.PI / 180.0;
protected UnitConversions() {
}
}
| 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.util;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.SharedPreferences.Editor;
import android.os.HandlerThread;
/**
* The Eclair (API level 5) specific implementation of the
* {@link ApiPlatformAdapter}.
*
* @author Bartlomiej Niechwiej
*/
public class EclairPlatformAdapter implements ApiPlatformAdapter {
@Override
public void startForeground(Service service,
NotificationManager notificationManager, int id,
Notification notification) {
service.startForeground(id, notification);
}
@Override
public void stopForeground(Service service,
NotificationManager notificationManager, int id) {
service.stopForeground(id != -1);
}
@Override
public boolean stopHandlerThread(HandlerThread handlerThread) {
return handlerThread.quit();
}
@Override
public void applyPreferenceChanges(Editor editor) {
editor.commit();
}
@Override
public void enableStrictMode() {
// Not supported
}
}
| 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.util;
import com.google.android.apps.mytracks.MyTracksSettings;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.Vector;
/**
* This class will generate google chart server url's.
*
* @author Sandor Dornbush
*/
public class ChartURLGenerator {
private static final String CHARTS_BASE_URL =
"http://chart.apis.google.com/chart?";
private ChartURLGenerator() {
}
/**
* Gets a chart of a track.
*
* @param distances An array of distance measurements
* @param elevations A matching array of elevation measurements
* @param track The track for this chart
* @param context The current appplication context
*/
public static String getChartUrl(Vector<Double> distances,
Vector<Double> elevations, Track track, Context context) {
SharedPreferences preferences =
context.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0);
boolean metricUnits = true;
if (preferences != null) {
metricUnits = preferences.getBoolean(
context.getString(R.string.metric_units_key), true);
}
return getChartUrl(distances, elevations, track,
context.getString(R.string.elevation_label), metricUnits);
}
/**
* Gets a chart of a track.
* This form is for testing without contexts.
*
* @param distances An array of distance measurements
* @param elevations A matching array of elevation measurements
* @param track The track for this chart
* @param title The title for the chart
* @param metricUnits Should the data be displayed in metric units
*/
public static String getChartUrl(
Vector<Double> distances, Vector<Double> elevations,
Track track, String title, boolean metricUnits) {
if (distances == null || elevations == null || track == null) {
return null;
}
if (distances.size() != elevations.size()) {
return null;
}
// Round it up.
TripStatistics stats = track.getStatistics();
double effectiveMaxY = metricUnits
? stats.getMaxElevation()
: stats.getMaxElevation() * UnitConversions.M_TO_FT;
effectiveMaxY = ((int) (effectiveMaxY / 100)) * 100 + 100;
// Round it down.
double effectiveMinY = 0;
double minElevation = metricUnits
? stats.getMinElevation()
: stats.getMinElevation() * UnitConversions.M_TO_FT;
effectiveMinY = ((int) (minElevation / 100)) * 100;
if (stats.getMinElevation() < 0) {
effectiveMinY -= 100;
}
double ySpread = effectiveMaxY - effectiveMinY;
StringBuilder sb = new StringBuilder(CHARTS_BASE_URL);
sb.append("&chs=600x350");
sb.append("&cht=lxy");
// Title
sb.append("&chtt=");
sb.append(title);
// Labels
sb.append("&chxt=x,y");
double distKM = stats.getTotalDistance() / 1000.0;
double distDisplay =
metricUnits ? distKM : (distKM * UnitConversions.KM_TO_MI);
int xInterval = ((int) (distDisplay / 6));
int yInterval = ((int) (ySpread / 600)) * 100;
if (yInterval < 100) {
yInterval = 25;
}
// Range
sb.append("&chxr=0,0,");
sb.append((int) distDisplay);
sb.append(',');
sb.append(xInterval);
sb.append("|1,");
sb.append(effectiveMinY);
sb.append(',');
sb.append(effectiveMaxY);
sb.append(',');
sb.append(yInterval);
// Line color
sb.append("&chco=009A00");
// Fill
sb.append("&chm=B,00AA00,0,0,0");
// Grid lines
double desiredGrids = ySpread / yInterval;
sb.append("&chg=100000,");
sb.append(100.0 / desiredGrids);
sb.append(",1,0");
// Data
sb.append("&chd=e:");
for (int i = 0; i < distances.size(); i++) {
int normalized =
(int) (getNormalizedDistance(distances.elementAt(i), track) * 4095);
sb.append(ChartsExtendedEncoder.getEncodedValue(normalized));
}
sb.append(ChartsExtendedEncoder.getSeparator());
for (int i = 0; i < elevations.size(); i++) {
int normalized =
(int) (getNormalizedElevation(
elevations.elementAt(i), effectiveMinY, ySpread) * 4095);
sb.append(ChartsExtendedEncoder.getEncodedValue(normalized));
}
return sb.toString();
}
private static double getNormalizedDistance(double d, Track track) {
return d / track.getStatistics().getTotalDistance();
}
private static double getNormalizedElevation(
double d, double effectiveMinY, double ySpread) {
return (d - effectiveMinY) / ySpread;
}
}
| 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.util;
import com.google.android.maps.GeoPoint;
/**
* A rectangle in geographical space.
*/
public class GeoRect {
public int top;
public int left;
public int bottom;
public int right;
public GeoRect() {
top = 0;
left = 0;
bottom = 0;
right = 0;
}
public GeoRect(GeoPoint center, int latSpan, int longSpan) {
top = center.getLatitudeE6() - latSpan / 2;
left = center.getLongitudeE6() - longSpan / 2;
bottom = center.getLatitudeE6() + latSpan / 2;
right = center.getLongitudeE6() + longSpan / 2;
}
public GeoPoint getCenter() {
return new GeoPoint(top / 2 + bottom / 2, left / 2 + right / 2);
}
public int getLatSpan() {
return bottom - top;
}
public int getLongSpan() {
return right - left;
}
public boolean contains(GeoPoint geoPoint) {
if (geoPoint.getLatitudeE6() >= top
&& geoPoint.getLatitudeE6() <= bottom
&& geoPoint.getLongitudeE6() >= left
&& geoPoint.getLongitudeE6() <= right) {
return true;
}
return false;
}
} | 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.util;
import static com.google.android.apps.mytracks.MyTracksConstants.TAG;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.SharedPreferences.Editor;
import android.os.HandlerThread;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* The Cupcake (API level 3) specific implementation of the
* {@link ApiPlatformAdapter}.
*
* @author Bartlomiej Niechwiej
*/
public class CupcakePlatformAdapter implements ApiPlatformAdapter {
@Override
public void startForeground(Service service,
NotificationManager notificationManager, int id,
Notification notification) {
setServiceForeground(service, true);
notificationManager.notify(id, notification);
}
@Override
public void stopForeground(Service service,
NotificationManager notificationManager, int id) {
setServiceForeground(service, false);
if (id != -1) {
notificationManager.cancel(id);
}
}
private void setServiceForeground(Service service, boolean foreground) {
// setForeground has been completely removed in API level 11, so we use reflection.
try {
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
setForegroundMethod.invoke(service, foreground);
} catch (SecurityException e) {
Log.e(TAG, "Unable to set service foreground state", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Unable to set service foreground state", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to set service foreground state", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to set service foreground state", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Unable to set service foreground state", e);
}
}
@Override
public boolean stopHandlerThread(HandlerThread handlerThread) {
// Do nothing, as Cupcake doesn't provide quit().
return false;
}
@Override
public void applyPreferenceChanges(Editor editor) {
editor.commit();
}
@Override
public void enableStrictMode() {
// Not supported
}
}
| 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.util;
import com.google.android.apps.mytracks.MyTracksConstants;
import android.os.Environment;
import java.io.File;
import java.util.regex.Pattern;
/**
* Utilities for dealing with files.
*
* @author Rodrigo Damazio
*/
public class FileUtils {
/**
* The maximum length of a filename, as per the FAT32 specification.
*/
private static final int MAX_FILENAME_LENGTH = 260;
/**
* A set of characters that are prohibited from being in file names.
*/
private static final Pattern PROHIBITED_CHAR_PATTERN =
Pattern.compile("[^ A-Za-z0-9_.()-]+");
/**
* Builds a path inside the My Tracks directory in the SD card.
*
* @param components the path components inside the mytracks directory
* @return the full path to the destination
*/
public String buildExternalDirectoryPath(String... components) {
StringBuilder dirNameBuilder = new StringBuilder();
dirNameBuilder.append(Environment.getExternalStorageDirectory());
dirNameBuilder.append(File.separatorChar);
dirNameBuilder.append(MyTracksConstants.SDCARD_TOP_DIR);
for (String component : components) {
dirNameBuilder.append(File.separatorChar);
dirNameBuilder.append(component);
}
return dirNameBuilder.toString();
}
/**
* Returns whether the SD card is available.
*/
public boolean isSdCardAvailable() {
return Environment.MEDIA_MOUNTED.equals(
Environment.getExternalStorageState());
}
/**
* Normalizes the input string and make sure it is a valid fat32 file name.
*
* @param name the name to normalize
* @return the sanitized name
*/
String sanitizeName(String name) {
String cleaned = PROHIBITED_CHAR_PATTERN.matcher(name).replaceAll("");
return (cleaned.length() > MAX_FILENAME_LENGTH)
? cleaned.substring(0, MAX_FILENAME_LENGTH)
: cleaned.toString();
}
/**
* Ensures the given directory exists by creating it and its parents if
* necessary.
*
* @return whether the directory exists (either already existed or was
* successfully created)
*/
public boolean ensureDirectoryExists(File dir) {
if (dir.exists() && dir.isDirectory()) {
return true;
}
if (dir.mkdirs()) {
return true;
}
return false;
}
/**
* Builds a filename with the given base name (prefix) and the given
* extension, possibly adding a suffix to ensure the file doesn't exist.
*
* @param directory the directory the file will live in
* @param fileBaseName the prefix for the file name
* @param extension the file's extension
* @return the complete file name, without the directory
*/
public synchronized String buildUniqueFileName(File directory,
String fileBaseName, String extension) {
return buildUniqueFileName(directory, fileBaseName, extension, 0);
}
/**
* Builds a filename with the given base name (prefix) and the given
* extension, possibly adding a suffix to ensure the file doesn't exist.
*
* @param directory the directory the file will live in
* @param fileBaseName the prefix for the file name
* @param extension the file's extension
* @param suffix the first numeric suffix to try to use, or 0 for none
* @return the complete file name, without the directory
*/
private String buildUniqueFileName(File directory, String fileBaseName,
String extension, int suffix) {
String suffixedBaseName = fileBaseName;
if (suffix > 0) {
suffixedBaseName += " (" + Integer.toString(suffix) + ")";
}
String fullName = suffixedBaseName + "." + extension;
String sanitizedName = sanitizeName(fullName);
if (!fileExists(directory, sanitizedName)) {
return sanitizedName;
}
return buildUniqueFileName(directory, fileBaseName, extension, suffix + 1);
}
/**
* Checks whether a file with the given name exists in the given directory.
* This is isolated so it can be overridden in tests.
*/
protected boolean fileExists(File directory, String fullName) {
File file = new File(directory, fullName);
return file.exists();
}
}
| 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.util;
import com.google.android.apps.mytracks.MyTracksConstants;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.os.Build;
import android.util.Log;
import java.util.List;
import java.util.Set;
/**
* Utilities for dealing with bluetooth devices.
* This can be used safely even in systems that don't support bluetooth,
* in which case a dummy implementation will be used.
*
* @author Rodrigo Damazio
*/
public abstract class BluetoothDeviceUtils {
public static final String ANY_DEVICE = "any";
private static BluetoothDeviceUtils instance;
/**
* Dummy implementation, for systems that don't support bluetooth.
*/
private static class DummyImpl extends BluetoothDeviceUtils {
@Override
public void populateDeviceLists(List<String> deviceNames, List<String> deviceAddresses) {
// Do nothing - no devices to add
}
@Override
public BluetoothDevice findDeviceMatching(String targetDeviceAddress) {
return null;
}
}
/**
* Real implementation, for systems that DO support bluetooth.
*/
private static class RealImpl extends BluetoothDeviceUtils {
private final BluetoothAdapter bluetoothAdapter;
public RealImpl() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
throw new IllegalStateException("Unable to get bluetooth adapter");
}
}
@Override
public void populateDeviceLists(List<String> deviceNames, List<String> deviceAddresses) {
ensureNotDiscovering();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
BluetoothClass bluetoothClass = device.getBluetoothClass();
if (bluetoothClass != null) {
// Not really sure what we want, but I know what we don't want.
switch(bluetoothClass.getMajorDeviceClass()) {
case BluetoothClass.Device.Major.COMPUTER:
case BluetoothClass.Device.Major.PHONE:
break;
default:
deviceAddresses.add(device.getAddress());
deviceNames.add(device.getName());
}
}
}
}
@Override
public BluetoothDevice findDeviceMatching(String targetDeviceAddress) {
if (targetDeviceAddress.equals(ANY_DEVICE)) {
return findAnyDevice();
} else {
return findDeviceByAddress(targetDeviceAddress);
}
}
/**
* Finds and returns the first suitable bluetooth sensor.
*/
private BluetoothDevice findAnyDevice() {
ensureNotDiscovering();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
// Look for the first paired computer device
if (isSuitableDevice(device)) {
return device;
}
}
return null;
}
/**
* Finds and returns a device with the given address, or null if it's not
* a suitable sensor.
*/
private BluetoothDevice findDeviceByAddress(String targetDeviceAddress) {
ensureNotDiscovering();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(targetDeviceAddress);
if (isSuitableDevice(device)) {
return device;
}
return null;
}
/**
* Ensures the bluetooth adapter is not in discovery mode.
*/
private void ensureNotDiscovering() {
// If it's in discovery mode, cancel that for now.
bluetoothAdapter.cancelDiscovery();
}
/**
* Checks whether the given device is a suitable sensor.
*
* @param device the device to check
* @return true if it's suitable, false otherwise
*/
private boolean isSuitableDevice(BluetoothDevice device) {
// Check that the device is bonded
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
return false;
}
return true;
}
}
/**
* Returns the proper (singleton) instance of this class.
*/
public static BluetoothDeviceUtils getInstance() {
if (instance == null) {
if (!isBluetoothMethodSupported()) {
Log.d(MyTracksConstants.TAG, "Using dummy bluetooth utils");
instance = new DummyImpl();
} else {
Log.d(MyTracksConstants.TAG, "Using real bluetooth utils");
try {
instance = new RealImpl();
} catch (IllegalStateException ise) {
Log.w(MyTracksConstants.TAG, "Oops, I mean, using dummy bluetooth utils", ise);
instance = new DummyImpl();
}
}
}
return instance;
}
/**
* Populates the given lists with the names and addresses of all suitable
* bluetooth devices.
*
* @param deviceNames the list to populate with user-visible names
* @param deviceAddresses the list to populate with device addresses
*/
public abstract void populateDeviceLists(List<String> deviceNames, List<String> deviceAddresses);
/**
* Finds the bluetooth device with the given address.
*
* @param targetDeviceAddress the address of the device, or
* {@link #ANY_DEVICE} for using the first suitable device
* @return the device's descriptor, or null if not found
*/
public abstract BluetoothDevice findDeviceMatching(String targetDeviceAddress);
/**
* @return whether the bluetooth method is supported on this device
*/
public static boolean isBluetoothMethodSupported() {
return Integer.parseInt(Build.VERSION.SDK) >= 5;
}
}
| 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.util;
import com.google.android.apps.mytracks.MyTracksConstants;
import android.os.Build;
import android.util.Log;
/**
* Utility class for determining if newer-API features are available on the
* current device.
*
* @author Rodrigo Damazio
*/
public class ApiFeatures {
/**
* The API level of the Android version we're being run under.
*/
public static final int ANDROID_API_LEVEL = Integer.parseInt(
Build.VERSION.SDK);
private static ApiFeatures instance;
/**
* The API platform adapter supported by this system.
*/
private ApiPlatformAdapter apiPlatformAdapter;
/**
* Returns the singleton instance of this class.
*/
public static ApiFeatures getInstance() {
if (instance == null) {
instance = new ApiFeatures();
}
return instance;
}
/**
* Injects a specific singleton instance, to be used for unit tests.
*/
public static void injectInstance(ApiFeatures instance) {
ApiFeatures.instance = instance;
}
/**
* Allow subclasses for mocking, but no direct instantiation.
*/
protected ApiFeatures() {
// It is safe to import unsupported classes as long as we only actually
// load the class when supported.
if (getApiLevel() >= 9) {
apiPlatformAdapter = new GingerbreadPlatformAdapter();
} else if (getApiLevel() >= 5) {
apiPlatformAdapter = new EclairPlatformAdapter();
} else {
apiPlatformAdapter = new CupcakePlatformAdapter();
}
Log.i(MyTracksConstants.TAG, "Using platform adapter " + apiPlatformAdapter.getClass());
}
public ApiPlatformAdapter getApiPlatformAdapter() {
return apiPlatformAdapter;
}
/**
* Returns whether cloud backup (a.k.a. Froyo backup) is available.
*/
public boolean hasBackup() {
return getApiLevel() >= 8;
}
/**
* Returns whether text-to-speech is available.
*/
public boolean hasTextToSpeech() {
if (getApiLevel() < 4) return false;
try {
Class.forName("android.speech.tts.TextToSpeech");
} catch (ClassNotFoundException ex) {
return false;
} catch (LinkageError er) {
return false;
}
return true;
}
public boolean hasStrictMode() {
return getApiLevel() >= 9;
}
public boolean isAudioFocusSupported() {
return getApiLevel() >= 8;
}
/**
* There's a bug (#1587) in Cupcake and Donut which prevents you from
* using a SQLiteQueryBuilder twice. That is, if you call buildQuery
* on a given instance (to log the statement for debugging), and then
* call query on the same instance to make it actually do the query,
* it'll regenerate the query for the second call, and will screw it
* up. Specifically, it'll add extra parens which don't belong.
*/
public boolean canReuseSQLiteQueryBuilder() {
return getApiLevel() > 4;
}
// Visible for testing.
protected int getApiLevel() {
return ANDROID_API_LEVEL;
}
}
| 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.util;
import android.content.Context;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
/**
* Utility functions for android resources.
*
* @author Sandor Dornbush
*/
public class ResourceUtils {
public static CharSequence readFile(Context activity, int id) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
activity.getResources().openRawResource(id)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null) {
buffer.append(line).append('\n');
}
return buffer;
} catch (IOException e) {
return "";
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
}
public static void readBinaryFileToOutputStream(
Context activity, int id, OutputStream os) {
BufferedInputStream in = null;
try {
in = new BufferedInputStream(
activity.getResources().openRawResource(id));
BufferedOutputStream out = new BufferedOutputStream(os);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
out.flush();
} catch (IOException e) {
return;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
}
private ResourceUtils() {
}
}
| 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.util;
/**
* The singleton class representing the extended encoding of chart data.
*/
public class ChartsExtendedEncoder {
// ChartServer data encoding in extended mode
private static final String CHARTSERVER_EXTENDED_ENCODING_SEPARATOR = ",";
private static final String CHARTSERVER_EXTENDED_ENCODING =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";
private static final int CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES =
CHARTSERVER_EXTENDED_ENCODING.length();
private static final String MISSING_POINT_EXTENDED_ENCODING = "__";
private ChartsExtendedEncoder() { }
public static String getEncodedValue(int scaled) {
int index1 = scaled / CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES;
if (index1 < 0 || index1 >= CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES) {
return MISSING_POINT_EXTENDED_ENCODING;
}
int index2 = scaled % CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES;
if (index2 < 0 || index2 >= CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES) {
return MISSING_POINT_EXTENDED_ENCODING;
}
return String.valueOf(CHARTSERVER_EXTENDED_ENCODING.charAt(index1))
+ String.valueOf(CHARTSERVER_EXTENDED_ENCODING.charAt(index2));
}
public static String getSeparator() {
return CHARTSERVER_EXTENDED_ENCODING_SEPARATOR;
}
}
| Java |
package com.google.android.apps.mytracks.util;
import com.google.android.apps.mytracks.MyTracksConstants;
import android.content.SharedPreferences.Editor;
import android.os.StrictMode;
import android.util.Log;
/**
* The Gingerbread (API level 9) specific implememntation of the
* {@link ApiPlatformAdapter}.
*
* @author Rodrigo Damazio
*/
public class GingerbreadPlatformAdapter extends EclairPlatformAdapter {
@Override
public void applyPreferenceChanges(Editor editor) {
// Apply asynchronously
editor.apply();
}
@Override
public void enableStrictMode() {
Log.d(MyTracksConstants.TAG, "Enabling strict mode");
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
}
}
| 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.util;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.maps.GeoPoint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.location.Location;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* Utility class for decimating tracks at a given level of precision.
*
* @author Leif Hendrik Wilden
*/
public class MyTracksUtils {
private static final int RELEASE_SIGNATURE_HASHCODE = -1855564782;
/**
* Computes the distance on the two sphere between the point c0 and the line
* segment c1 to c2.
*
* @param c0 the first coordinate
* @param c1 the beginning of the line segment
* @param c2 the end of the lone segment
* @return the distance in m (assuming spherical earth)
*/
public static double distance(
final Location c0, final Location c1, final Location c2) {
if (c1.equals(c2)) {
return c2.distanceTo(c0);
}
final double s0lat = c0.getLatitude() * UnitConversions.TO_RADIANS;
final double s0lng = c0.getLongitude() * UnitConversions.TO_RADIANS;
final double s1lat = c1.getLatitude() * UnitConversions.TO_RADIANS;
final double s1lng = c1.getLongitude() * UnitConversions.TO_RADIANS;
final double s2lat = c2.getLatitude() * UnitConversions.TO_RADIANS;
final double s2lng = c2.getLongitude() * UnitConversions.TO_RADIANS;
double s2s1lat = s2lat - s1lat;
double s2s1lng = s2lng - s1lng;
final double u =
((s0lat - s1lat) * s2s1lat + (s0lng - s1lng) * s2s1lng)
/ (s2s1lat * s2s1lat + s2s1lng * s2s1lng);
if (u <= 0) {
return c0.distanceTo(c1);
}
if (u >= 1) {
return c0.distanceTo(c2);
}
Location sa = new Location("");
sa.setLatitude(c0.getLatitude() - c1.getLatitude());
sa.setLongitude(c0.getLongitude() - c1.getLongitude());
Location sb = new Location("");
sb.setLatitude(u * (c2.getLatitude() - c1.getLatitude()));
sb.setLongitude(u * (c2.getLongitude() - c1.getLongitude()));
return sa.distanceTo(sb);
}
/**
* Decimates the given locations for a given zoom level. This uses a
* Douglas-Peucker decimation algorithm.
*
* @param tolerance in meters
* @param locations input
* @param decimated output
*/
public static void decimate(double tolerance, ArrayList<Location> locations,
ArrayList<Location> decimated) {
final int n = locations.size();
if (n < 1) {
return;
}
int idx;
int maxIdx = 0;
Stack<int[]> stack = new Stack<int[]>();
double[] dists = new double[n];
dists[0] = 1;
dists[n - 1] = 1;
double maxDist;
double dist = 0.0;
int[] current;
if (n > 2) {
int[] stackVal = new int[] {0, (n - 1)};
stack.push(stackVal);
while (stack.size() > 0) {
current = stack.pop();
maxDist = 0;
for (idx = current[0] + 1; idx < current[1]; ++idx) {
dist = MyTracksUtils.distance(
locations.get(idx),
locations.get(current[0]),
locations.get(current[1]));
if (dist > maxDist) {
maxDist = dist;
maxIdx = idx;
}
}
if (maxDist > tolerance) {
dists[maxIdx] = maxDist;
int[] stackValCurMax = {current[0], maxIdx};
stack.push(stackValCurMax);
int[] stackValMaxCur = {maxIdx, current[1]};
stack.push(stackValMaxCur);
}
}
}
int i = 0;
idx = 0;
decimated.clear();
for (Location l : locations) {
if (dists[idx] != 0) {
decimated.add(l);
i++;
}
idx++;
}
Log.d(MyTracksConstants.TAG, "Decimating " + n + " points to " + i
+ " w/ tolerance = " + tolerance);
}
/**
* Decimates the given track for the given precision.
*
* @param track a track
* @param precision desired precision in meters
*/
public static void decimate(Track track, double precision) {
ArrayList<Location> decimated = new ArrayList<Location>();
decimate(precision, track.getLocations(), decimated);
track.setLocations(decimated);
}
/**
* Limits number of points by dropping any points beyond the given number of
* points. Note: That'll actually discard points.
*
* @param track a track
* @param numberOfPoints maximum number of points
*/
public static void cut(Track track, int numberOfPoints) {
ArrayList<Location> locations = track.getLocations();
while (locations.size() > numberOfPoints) {
locations.remove(locations.size() - 1);
}
}
/**
* Splits a track in multiple tracks where each piece has less or equal than
* maxPoints.
*
* @param track the track to split
* @param maxPoints maximum number of points for each piece
* @return a list of one or more track pieces
*/
public static ArrayList<Track> split(Track track, int maxPoints) {
ArrayList<Track> result = new ArrayList<Track>();
final int nTotal = track.getLocations().size();
int n = 0;
Track piece = null;
do {
piece = new Track();
TripStatistics pieceStats = piece.getStatistics();
piece.setId(track.getId());
piece.setName(track.getName());
piece.setDescription(track.getDescription());
piece.setCategory(track.getCategory());
List<Location> pieceLocations = piece.getLocations();
for (int i = n; i < nTotal && pieceLocations.size() < maxPoints; i++) {
piece.addLocation(track.getLocations().get(i));
}
int nPointsPiece = pieceLocations.size();
if (nPointsPiece >= 2) {
pieceStats.setStartTime(pieceLocations.get(0).getTime());
pieceStats.setStopTime(pieceLocations.get(nPointsPiece - 1).getTime());
result.add(piece);
}
n += (pieceLocations.size() - 1);
} while (n < nTotal && piece != null && piece.getLocations().size() > 1);
return result;
}
/**
* Test if a given GeoPoint is valid, i.e. within physical bounds.
*
* @param geoPoint the point to be tested
* @return true, if it is a physical location on earth.
*/
public static boolean isValidGeoPoint(GeoPoint geoPoint) {
return Math.abs(geoPoint.getLatitudeE6()) < 90E6
&& Math.abs(geoPoint.getLongitudeE6()) <= 180E6;
}
/**
* Checks if a given location is a valid (i.e. physically possible) location
* on Earth. Note: The special separator locations (which have latitude =
* 100) will not qualify as valid. Neither will locations with lat=0 and lng=0
* as these are most likely "bad" measurements which often cause trouble.
*
* @param location the location to test
* @return true if the location is a valid location.
*/
public static boolean isValidLocation(Location location) {
return location != null && Math.abs(location.getLatitude()) <= 90
&& Math.abs(location.getLongitude()) <= 180;
}
/**
* Gets a location from a GeoPoint.
*
* @param p a GeoPoint
* @return the corresponding location
*/
public static Location getLocation(GeoPoint p) {
Location result = new Location("");
result.setLatitude(p.getLatitudeE6() / 1.0E6);
result.setLongitude(p.getLongitudeE6() / 1.0E6);
return result;
}
public static GeoPoint getGeoPoint(Location location) {
return new GeoPoint((int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
}
/**
* Returns whether or not this is a release build.
*/
public static boolean isRelease(Context context) {
try {
Signature [] sigs = context.getPackageManager().getPackageInfo(
context.getPackageName(), PackageManager.GET_SIGNATURES).signatures;
for (Signature sig : sigs) {
if (sig.hashCode() == RELEASE_SIGNATURE_HASHCODE) {
return true;
}
}
} catch (NameNotFoundException e) {
Log.e(MyTracksConstants.TAG, "Unable to get signatures", e);
}
return false;
}
/**
* Get the My Tracks version from the manifest.
*
* @return the version, or an empty string in case of failure.
*/
public static String getMyTracksVersion(Context context) {
try {
PackageInfo pi = context.getPackageManager().getPackageInfo(
"com.google.android.maps.mytracks",
PackageManager.GET_META_DATA);
return pi.versionName;
} catch (NameNotFoundException e) {
Log.w(MyTracksConstants.TAG, "Failed to get version info.", e);
return "";
}
}
/**
* Tries to acquire a partial wake lock if not already acquired. Logs errors
* and gives up trying in case the wake lock cannot be acquired.
*/
public static WakeLock acquireWakeLock(Activity activity, WakeLock wakeLock) {
Log.i(MyTracksConstants.TAG, "MyTracksUtils: Acquiring wake lock.");
try {
PowerManager pm = (PowerManager) activity
.getSystemService(Context.POWER_SERVICE);
if (pm == null) {
Log.e(MyTracksConstants.TAG, "MyTracksUtils: Power manager not found!");
return wakeLock;
}
if (wakeLock == null) {
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
MyTracksConstants.TAG);
if (wakeLock == null) {
Log.e(MyTracksConstants.TAG,
"MyTracksUtils: Could not create wake lock (null).");
}
return wakeLock;
}
if (!wakeLock.isHeld()) {
wakeLock.acquire();
if (!wakeLock.isHeld()) {
Log.e(MyTracksConstants.TAG,
"MyTracksUtils: Could not acquire wake lock.");
}
}
} catch (RuntimeException e) {
Log.e(MyTracksConstants.TAG,
"MyTracksUtils: Caught unexpected exception: " + e.getMessage(), e);
}
return wakeLock;
}
/**
* This is a utility class w/ only static members.
*/
protected MyTracksUtils() {
}
}
| 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;
import com.google.android.apps.mytracks.util.MyTracksUtils;
import com.google.android.maps.mytracks.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebView;
import android.widget.TextView;
/**
* An activity that displays a welcome screen.
*
* @author Sandor Dornbush
*/
public class WelcomeActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.welcome);
WebView web = (WebView) findViewById(R.id.welcome_web);
web.loadUrl("file:///android_asset/welcome.html");
findViewById(R.id.welcome_read_later).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
finish();
}
});
findViewById(R.id.welcome_about).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
about();
}
});
}
/**
* Shows the "about" dialog.
*
* TODO: Add a menu option for showing the same thing.
*/
public void about() {
LayoutInflater li = LayoutInflater.from(this);
View view = li.inflate(R.layout.about, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view);
builder.setPositiveButton(R.string.ok, null);
builder.setNeutralButton(R.string.license, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Eula.showEula(WelcomeActivity.this);
}
});
builder.setIcon(R.drawable.arrow_icon);
AlertDialog dialog = builder.create();
dialog.show();
((TextView) dialog.findViewById(R.id.about_version_register)).
setText(MyTracksUtils.getMyTracksVersion(this));
}
}
| 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;
import com.google.android.apps.mytracks.content.MyTracksLocation;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.content.Sensor.SensorDataSet;
import com.google.android.apps.mytracks.io.TrackWriterFactory.TrackFileFormat;
import android.location.Location;
import android.os.Build;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* Write out a a track in the Garmin training center database, tcx format.
* As defined by:
* http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2
*
* @author Sandor Dornbush
*/
public class TcxTrackWriter implements TrackFormatWriter {
private PrintWriter pw = null;
private Track track;
static final SimpleDateFormat TIMESTAMP_FORMAT =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
static {
TIMESTAMP_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
public TcxTrackWriter() {
}
@Override
public void prepare(Track track, OutputStream out) {
this.track = track;
this.pw = new PrintWriter(out);
}
@Override
public void close() {
if (pw != null) {
pw.close();
pw = null;
}
}
@Override
public String getExtension() {
return TrackFileFormat.TCX.getExtension();
}
@Override
public void writeHeader() {
if (pw == null) {
return;
}
pw.format("<?xml version=\"1.0\" encoding=\"%s\" standalone=\"no\" ?>\n",
Charset.defaultCharset().name());
pw.print("<TrainingCenterDatabase ");
pw.print("xmlns=\"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2\" ");
pw.print("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
pw.print("xsi:schemaLocation=\"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 ");
pw.println("http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd\">");
pw.println();
}
@Override
public void writeBeginTrack(Location firstPoint) {
if (pw == null) {
return;
}
pw.println(" <Activities>");
pw.print(" <Activity Sport=\"");
if (track.getCategory() != null) {
pw.print(track.getCategory());
}
pw.println("\">");
pw.print(" <Id>");
pw.print(TIMESTAMP_FORMAT.format(track.getStatistics().getStartTime()));
pw.println("</Id>");
pw.println(" <Lap>");
pw.print(" <TotalTimeSeconds>");
pw.print(track.getStatistics().getTotalTime() / 1000);
pw.println("</TotalTimeSeconds>");
pw.print(" <DistanceMeters>");
pw.print(track.getStatistics().getTotalDistance());
pw.println("</DistanceMeters>");
// TODO max speed etc.
// Calories are a required element just put in 0.
pw.print("<Calories>0</Calories>");
pw.println("<Intensity>Active</Intensity>");
pw.println("<TriggerMethod>Manual</TriggerMethod>)");
}
@Override
public void writeOpenSegment() {
if (pw != null) {
pw.println(" <Track>");
}
}
@Override
public void writeLocation(Location location) {
if (pw == null) {
return;
}
pw.println(" <Trackpoint>");
Date d = new Date(location.getTime());
pw.println(" <Time>" + TIMESTAMP_FORMAT.format(d) + "</Time>");
pw.println(" <Position>");
pw.print(" <LatitudeDegrees>");
pw.print(location.getLatitude());
pw.println("</LatitudeDegrees>");
pw.print(" <LongitudeDegrees>");
pw.print(location.getLongitude());
pw.println("</LongitudeDegrees>");
pw.println(" </Position>");
pw.print(" <AltitudeMeters>");
pw.print(location.getAltitude());
pw.println("</AltitudeMeters>");
if (location instanceof MyTracksLocation) {
SensorDataSet sensorData = ((MyTracksLocation) location).getSensorDataSet();
if (sensorData != null) {
if (sensorData.hasHeartRate()
&& sensorData.getHeartRate().getState() == Sensor.SensorState.SENDING
&& sensorData.getHeartRate().hasValue()) {
pw.print(" <HeartRateBpm>");
pw.print("<Value>");
pw.print(sensorData.getHeartRate().getValue());
pw.print("</Value>");
pw.println("</HeartRateBpm>");
}
if (sensorData.hasPower()
&& sensorData.getPower().getState() == Sensor.SensorState.SENDING
&& sensorData.getPower().hasValue()) {
pw.print(" <Extensions>");
pw.print("<TPX xmlns=\"http://www.garmin.com/xmlschemas/ActivityExtension/v2\">");
pw.print("<Watts>");
pw.print(sensorData.getPower().getValue());
pw.print("</Watts>");
pw.println("</TPX></Extensions>");
}
if (sensorData.hasCadence()
&& sensorData.getCadence().getState() == Sensor.SensorState.SENDING
&& sensorData.getCadence().hasValue()) {
pw.print(" <Cadence>");
pw.print(sensorData.getCadence().getValue());
pw.println("</Cadence>");
}
}
}
pw.println(" </Trackpoint>");
}
@Override
public void writeCloseSegment() {
if (pw != null) {
pw.println(" </Track>");
}
}
@Override
public void writeEndTrack(Location lastPoint) {
if (pw == null) {
return;
}
pw.println(" </Lap>");
pw.print(" <Creator xsi:type=\"Device_t\">");
pw.print("<Name>");
pw.print(Build.MODEL);
pw.print("</Name>");
pw.println("</Creator>)");
pw.println(" </Activity>");
pw.println(" </Activities>");
}
@Override
public void writeFooter() {
if (pw == null) {
return;
}
pw.print(" <Author xsi:type=\"Application_t\">");
pw.print("<Name>My Tracks by Google</Name>");
pw.println("</Author>");
pw.println("</TrainingCenterDatabase>");
}
@Override
public void writeWaypoint(Waypoint waypoint) {
// TODO Write out the waypoints somewhere.
}
}
| 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;
import com.google.android.apps.mytracks.MyTracksConstants;
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.MyTracksUtils;
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(MyTracksConstants.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 (MyTracksUtils.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(MyTracksConstants.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.docs;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.apps.mytracks.util.UnitConversions;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* <p>This class builds a string of XML tags used to talk to Docs using GData.
*
* <p>Sample Usage:
*
* <code>
* String tags = new DocsTagBuilder(false)
* .append("tagName", "tagValue")
* .appendLargeUnits("bigTagName", 1.0)
* .build();
* </code>
*
* <p>results in:
*
* <code>
* <gsx:tagName><![CDATA[tagValue]]></gsx:tagName>
* <gsx:bigTagName><![CDATA[1.00]]></gsx:bigTagName>
* </code>
*
* @author Matthew Simmons
*/
class DocsTagBuilder {
// TODO(simmonmt): These formats aren't I18N-compatible. Not everyone uses
// commas for thousands and dots for the decimal point.
private static final NumberFormat LARGE_UNIT_FORMAT =
new DecimalFormat("#,###,###.00");
private static final NumberFormat SMALL_UNIT_FORMAT =
new DecimalFormat("###,###");
protected final boolean metricUnits;
protected final StringBuilder stringBuilder;
/**
* @param metricUnits True if metric units are to be used. If false,
* imperial units will be used.
*/
DocsTagBuilder(boolean metricUnits) {
this.metricUnits = metricUnits;
stringBuilder = new StringBuilder();
}
/** Appends a tag containing a string value */
DocsTagBuilder append(String name, String value) {
appendTag(name, value);
return this;
}
/**
* Appends a tag containing a numeric value. The value will be formatted
* according to the large distance of the specified measurement system (i.e.
* kilometers or miles).
*
* @param name The tag name.
* @param d The value to be formatted, in kilometers.
*/
DocsTagBuilder appendLargeUnits(String name, double d) {
double value = metricUnits ? d : (d * UnitConversions.KM_TO_MI);
appendTag(name, LARGE_UNIT_FORMAT.format(value));
return this;
}
/**
* Appends a tag containing a numeric value. The value will be formatted
* according to the small distance of the specified measurement system (i.e.
* meters or feet).
*
* @param name The tag name.
* @param d The value to be formatted, in meters.
*/
DocsTagBuilder appendSmallUnits(String name, double d) {
double value = metricUnits ? d : (d * UnitConversions.M_TO_FT);
appendTag(name, SMALL_UNIT_FORMAT.format(value));
return this;
}
/** Returns a string containing all tags which have been added. */
String build() {
return stringBuilder.toString();
}
private void appendTag(String name, String value) {
stringBuilder.append("<gsx:")
.append(name)
.append(">")
.append(StringUtils.stringAsCData(value))
.append("</gsx:")
.append(name)
.append(">");
}
}
| 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.docs;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.io.AuthManager;
import com.google.android.apps.mytracks.io.gdata.GDataWrapper;
import com.google.android.apps.mytracks.io.gdata.GDataWrapper.QueryFunction;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.ResourceUtils;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.maps.mytracks.R;
import com.google.wireless.gdata.client.GDataServiceClient;
import com.google.wireless.gdata.client.HttpException;
import com.google.wireless.gdata.data.Entry;
import com.google.wireless.gdata.docs.SpreadsheetsClient;
import com.google.wireless.gdata.docs.SpreadsheetsClient.WorksheetEntry;
import com.google.wireless.gdata.parser.GDataParser;
import com.google.wireless.gdata.parser.ParseException;
import com.google.wireless.gdata2.client.AuthenticationException;
import android.content.Context;
import android.util.Log;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.atomic.AtomicReference;
/**
* This class contains helper methods for interacting with Google Docs and
* Google Spreadsheets.
*
* @author Sandor Dornbush
* @author Matthew Simmons
*/
public class DocsHelper {
private static final String DOCS_FEED_URL =
"http://docs.google.com/feeds/documents/private/full";
private static final String DOCS_SPREADSHEET_URL =
"http://docs.google.com/feeds/documents/private/full/spreadsheet%3A";
private static final String DOCS_WORKSHEETS_URL_FORMAT =
"http://spreadsheets.google.com/feeds/worksheets/%s/private/full";
private static final String DOCS_MY_SPREADSHEETS_FEED_URL =
"http://docs.google.com/feeds/documents/private/full?category=mine,spreadsheet";
private static final String DOCS_SPREADSHEET_URL_FORMAT =
"http://spreadsheets.google.com/feeds/list/%s/%s/private/full";
private static final String CONTENT_TYPE_PARAM = "Content-Type";
private static final String OPENDOCUMENT_SPREADSHEET_MIME_TYPE =
"application/x-vnd.oasis.opendocument.spreadsheet";
private static final String ATOM_FEED_MIME_TYPE = "application/atom+xml";
/**
* Creates a new MyTracks spreadsheet with the given name.
*
* @param context The context associated with this request.
* @param docListWrapper The GData handle for the Document List service.
* @param name The name for the newly-created spreadsheet.
* @return The spreadsheet ID, if one is created. {@code null} will be
* returned if a GData error didn't occur, but no spreadsheet ID was
* returned.
*/
public String createSpreadsheet(final Context context,
final GDataWrapper<GDataServiceClient> docListWrapper, final String name) throws IOException {
final AtomicReference<String> idSaver = new AtomicReference<String>();
boolean result = docListWrapper.runQuery(new QueryFunction<GDataServiceClient>() {
@Override
public void query(GDataServiceClient client) throws IOException,
GDataWrapper.AuthenticationException {
// Construct and send request
URL url = new URL(DOCS_FEED_URL);
URLConnection conn = url.openConnection();
conn.addRequestProperty(CONTENT_TYPE_PARAM,
OPENDOCUMENT_SPREADSHEET_MIME_TYPE);
conn.addRequestProperty("Slug", name);
conn.addRequestProperty("Authorization",
"GoogleLogin auth=" +
docListWrapper.getAuthManager().getAuthToken());
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
ResourceUtils.readBinaryFileToOutputStream(
context, R.raw.mytracks_empty_spreadsheet, os);
// Get the response
// TODO: The following is a horrible ugly hack.
// Hopefully we can retire it when there is a proper gdata api.
BufferedReader rd = null;
String line;
StringBuilder resultBuilder = new StringBuilder();
try {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null) {
resultBuilder.append(line);
}
os.close();
rd.close();
} catch (FileNotFoundException e) {
// The GData API sometimes throws an error, even though creation of
// the document succeeded. In that case let's just return. The caller
// then needs to check if the doc actually exists.
return;
} finally {
os.close();
if (rd != null) {
rd.close();
}
}
String result = resultBuilder.toString();
// Try to find the id.
int idTagIndex = result.indexOf("<id>");
if (idTagIndex == -1) {
return;
}
int idTagCloseIndex = result.indexOf("</id>", idTagIndex);
if (idTagCloseIndex == -1) {
return;
}
int idStringStart = result.indexOf(DOCS_SPREADSHEET_URL, idTagIndex);
if (idStringStart == -1) {
return;
}
String id = result.substring(
idStringStart + DOCS_SPREADSHEET_URL.length(), idTagCloseIndex);
Log.i(MyTracksConstants.TAG, "Created new spreadsheet: " + id);
idSaver.set(id);
}});
if (!result) {
throw newIOException(docListWrapper,
"Failed to create new spreadsheet.");
}
return idSaver.get();
}
/**
* Retrieve the ID of a spreadsheet with the given name.
*
* @param docListWrapper The GData handle for the Document List service.
* @param title The name of the spreadsheet whose ID is to be retrieved.
* @return The spreadsheet ID, if it can be retrieved. {@code null} will
* be returned if no spreadsheet exists by the given name.
* @throws IOException If an error occurs during the GData request.
*/
public String requestSpreadsheetId(final GDataWrapper<GDataServiceClient> docListWrapper,
final String title) throws IOException {
final AtomicReference<String> idSaver = new AtomicReference<String>();
boolean result = docListWrapper.runQuery(new QueryFunction<GDataServiceClient>() {
@Override
public void query(GDataServiceClient client)
throws IOException, GDataWrapper.ParseException, GDataWrapper.HttpException,
GDataWrapper.AuthenticationException {
GDataParser listParser;
try {
listParser = client.getParserForFeed(Entry.class,
DOCS_MY_SPREADSHEETS_FEED_URL,
docListWrapper.getAuthManager().getAuthToken());
listParser.init();
while (listParser.hasMoreData()) {
Entry entry = listParser.readNextEntry(null);
String entryTitle = entry.getTitle();
Log.i(MyTracksConstants.TAG, "Found docs entry: " + entryTitle);
if (entryTitle.equals(title)) {
String entryId = entry.getId();
int lastSlash = entryId.lastIndexOf('/');
idSaver.set(entryId.substring(lastSlash + 15));
break;
}
}
} catch (ParseException e) {
throw new GDataWrapper.ParseException(e);
} catch (HttpException e) {
throw new GDataWrapper.HttpException(e.getStatusCode(), e.getMessage());
}
}
});
if (!result) {
throw newIOException(docListWrapper,
"Failed to retrieve spreadsheet list.");
}
return idSaver.get();
}
/**
* Retrieve the ID of the first worksheet in the named spreadsheet.
*
* @param trixWrapper The GData handle for the spreadsheet service.
* @param spreadsheetId The GData ID for the given spreadsheet.
* @return The worksheet ID, if it can be retrieved. {@code null} will be
* returned if the GData request returns without error, but without an
* ID.
* @throws IOException If an error occurs during the GData request.
*/
public String getWorksheetId(final GDataWrapper<GDataServiceClient> trixWrapper,
final String spreadsheetId) throws IOException {
final AtomicReference<String> idSaver = new AtomicReference<String>();
boolean result = trixWrapper.runQuery(new QueryFunction<GDataServiceClient>() {
@Override
public void query(GDataServiceClient client)
throws GDataWrapper.AuthenticationException, IOException, GDataWrapper.ParseException, GDataWrapper.HttpException {
String uri = String.format(DOCS_WORKSHEETS_URL_FORMAT, spreadsheetId);
GDataParser sheetParser;
try {
sheetParser = ((SpreadsheetsClient) client).getParserForWorksheetsFeed(uri,
trixWrapper.getAuthManager().getAuthToken());
sheetParser.init();
if (!sheetParser.hasMoreData()) {
Log.i(MyTracksConstants.TAG, "Found no worksheets");
return;
}
// Grab the first worksheet.
WorksheetEntry worksheetEntry =
(WorksheetEntry) sheetParser.readNextEntry(new WorksheetEntry());
int lastSlash = worksheetEntry.getId().lastIndexOf('/');
idSaver.set(worksheetEntry.getId().substring(lastSlash + 1));
} catch (ParseException e) {
throw new GDataWrapper.ParseException(e);
} catch (AuthenticationException e) {
throw new GDataWrapper.AuthenticationException(e);
}
}
});
if (!result) {
throw newIOException(trixWrapper, "Failed to retrieve worksheet ID.");
}
return idSaver.get();
}
/**
* Add a row to a worksheet containing the stats for a given track.
*
* @param context The context associated with this request.
* @param trixAuth The GData authorization for the spreadsheet service.
* @param spreadsheetId The spreadsheet to be modified.
* @param worksheetId The worksheet to be modified.
* @param track The track whose stats are to be written.
* @param metricUnits True if metric units are to be used. If false,
* imperial units will be used.
* @throws IOException If an error occurs while updating the worksheet.
*/
public void addTrackRow(Context context, AuthManager trixAuth,
String spreadsheetId, String worksheetId, Track track,
boolean metricUnits) throws IOException {
String worksheetUri = String.format(DOCS_SPREADSHEET_URL_FORMAT,
spreadsheetId, worksheetId);
TripStatistics stats = track.getStatistics();
String distanceUnit = context.getString(metricUnits ?
R.string.kilometer : R.string.mile);
String speedUnit = context.getString(metricUnits ?
R.string.kilometer_per_hour : R.string.mile_per_hour);
String elevationUnit = context.getString(metricUnits ?
R.string.meter : R.string.feet);
// Prepare the Post-Text we are going to send.
DocsTagBuilder tagBuilder = new DocsTagBuilder(metricUnits)
.append("name", track.getName())
.append("description", track.getDescription())
.append("date", String.format("%tc", stats.getStartTime()))
.append("totaltime", StringUtils.formatTimeAlwaysShowingHours(
stats.getTotalTime()))
.append("movingtime", StringUtils.formatTimeAlwaysShowingHours(
stats.getMovingTime()))
.appendLargeUnits("distance", stats.getTotalDistance() / 1000)
.append("distanceunit", distanceUnit)
.appendLargeUnits("averagespeed", stats.getAverageSpeed() * 3.6)
.appendLargeUnits("averagemovingspeed",
stats.getAverageMovingSpeed() * 3.6)
.appendLargeUnits("maxspeed", stats.getMaxSpeed() * 3.6)
.append("speedunit", speedUnit)
.appendSmallUnits("elevationgain", stats.getTotalElevationGain())
.appendSmallUnits("minelevation", stats.getMinElevation())
.appendSmallUnits("maxelevation", stats.getMaxElevation())
.append("elevationunit", elevationUnit);
if (track.getMapId().length() > 0) {
tagBuilder.append("map", String.format("%s?msa=0&msid=%s",
MyTracksConstants.MAPSHOP_BASE_URL, track.getMapId()));
}
String postText = new StringBuilder()
.append("<entry xmlns='http://www.w3.org/2005/Atom' "
+ "xmlns:gsx='http://schemas.google.com/spreadsheets/"
+ "2006/extended'>")
.append(tagBuilder.build())
.append("</entry>")
.toString();
Log.i(MyTracksConstants.TAG,
"Inserting at: " + spreadsheetId + " => " + worksheetUri);
Log.i(MyTracksConstants.TAG, postText);
writeRowData(trixAuth, worksheetUri, postText);
Log.i(MyTracksConstants.TAG, "Post finished.");
}
/**
* Writes spreadsheet row data to the indicated worksheet.
*
* @param trixAuth The GData authorization for the spreadsheet service.
* @param worksheetUri The URI of the worksheet to be altered.
* @param postText The XML tags describing the change to be made.
* @throws IOException Thrown if an error occurs during the write.
*/
protected void writeRowData(AuthManager trixAuth, String worksheetUri,
String postText) throws IOException {
// No need for a wrapper because we know that the authorization was good
// enough to get this far.
URL url = new URL(worksheetUri);
URLConnection conn = url.openConnection();
conn.addRequestProperty(CONTENT_TYPE_PARAM, ATOM_FEED_MIME_TYPE);
conn.addRequestProperty("Authorization",
"GoogleLogin auth=" + trixAuth.getAuthToken());
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(postText);
wr.flush();
// Get the response.
// TODO: Should we parse the response, rather than simply throwing it away?
BufferedReader rd =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line.
Log.i(MyTracksConstants.TAG, "r: " + line);
}
wr.close();
rd.close();
}
private static IOException newIOException(GDataWrapper wrapper,
String message) {
return new IOException(String.format("%s: %d: %s", message,
wrapper.getErrorType(), wrapper.getErrorMessage()));
}
}
| 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.gdata;
import com.google.wireless.gdata.client.GDataClient;
import com.google.wireless.gdata.client.HttpException;
import com.google.wireless.gdata.client.QueryParams;
import com.google.wireless.gdata.data.StringUtils;
import com.google.wireless.gdata.parser.ParseException;
import com.google.wireless.gdata.serializer.GDataSerializer;
import android.text.TextUtils;
import android.util.Config;
import android.util.Log;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.zip.GZIPInputStream;
/**
* Implementation of a GDataClient using GoogleHttpClient to make HTTP requests.
* Always issues GETs and POSTs, using the X-HTTP-Method-Override header when a
* PUT or DELETE is desired, to avoid issues with firewalls, etc., that do not
* allow methods other than GET or POST.
*/
public class AndroidGDataClient implements GDataClient {
private static final String TAG = "GDataClient";
private static final boolean DEBUG = false;
private static final boolean LOCAL_LOGV = DEBUG ? Config.LOGD : Config.LOGV;
private static final String X_HTTP_METHOD_OVERRIDE = "X-HTTP-Method-Override";
private static final int MAX_REDIRECTS = 10;
private final HttpClient httpClient;
/**
* Interface for creating HTTP requests. Used by
* {@link AndroidGDataClient#createAndExecuteMethod}, since HttpUriRequest
* does not allow for changing the URI after creation, e.g., when you want to
* follow a redirect.
*/
private interface HttpRequestCreator {
HttpUriRequest createRequest(URI uri);
}
private static class GetRequestCreator implements HttpRequestCreator {
public HttpUriRequest createRequest(URI uri) {
return new HttpGet(uri);
}
}
private static class PostRequestCreator implements HttpRequestCreator {
private final String mMethodOverride;
private final HttpEntity mEntity;
public PostRequestCreator(String methodOverride, HttpEntity entity) {
mMethodOverride = methodOverride;
mEntity = entity;
}
public HttpUriRequest createRequest(URI uri) {
HttpPost post = new HttpPost(uri);
if (mMethodOverride != null) {
post.addHeader(X_HTTP_METHOD_OVERRIDE, mMethodOverride);
}
post.setEntity(mEntity);
return post;
}
}
// MAJOR TODO: make this work across redirects (if we can reset the
// InputStream).
// OR, read the bits into a local buffer (yuck, the media could be large).
private static class MediaPutRequestCreator implements HttpRequestCreator {
private final InputStream mMediaInputStream;
private final String mContentType;
public MediaPutRequestCreator(InputStream mediaInputStream,
String contentType) {
mMediaInputStream = mediaInputStream;
mContentType = contentType;
}
public HttpUriRequest createRequest(URI uri) {
HttpPost post = new HttpPost(uri);
post.addHeader(X_HTTP_METHOD_OVERRIDE, "PUT");
InputStreamEntity entity =
new InputStreamEntity(mMediaInputStream, -1 /* read until EOF */);
entity.setContentType(mContentType);
post.setEntity(entity);
return post;
}
}
/**
* Creates a new AndroidGDataClient.
*/
public AndroidGDataClient() {
httpClient = new DefaultHttpClient();
}
public void close() {
}
/*
* (non-Javadoc)
*
* @see GDataClient#encodeUri(java.lang.String)
*/
public String encodeUri(String uri) {
String encodedUri;
try {
encodedUri = URLEncoder.encode(uri, "UTF-8");
} catch (UnsupportedEncodingException uee) {
// should not happen.
Log.e("JakartaGDataClient", "UTF-8 not supported -- should not happen. "
+ "Using default encoding.", uee);
encodedUri = URLEncoder.encode(uri);
}
return encodedUri;
}
/*
* (non-Javadoc)
*
* @see com.google.wireless.gdata.client.GDataClient#createQueryParams()
*/
public QueryParams createQueryParams() {
return new QueryParamsImpl();
}
// follows redirects
private InputStream createAndExecuteMethod(HttpRequestCreator creator,
String uriString, String authToken) throws HttpException, IOException {
HttpResponse response = null;
int status = 500;
int redirectsLeft = MAX_REDIRECTS;
URI uri;
try {
uri = new URI(uriString);
} catch (URISyntaxException use) {
Log.w(TAG, "Unable to parse " + uriString + " as URI.", use);
throw new IOException("Unable to parse " + uriString + " as URI: "
+ use.getMessage());
}
// we follow redirects ourselves, since we want to follow redirects even on
// POSTs, which
// the HTTP library does not do. following redirects ourselves also allows
// us to log
// the redirects using our own logging.
while (redirectsLeft > 0) {
HttpUriRequest request = creator.createRequest(uri);
request.addHeader("User-Agent", "Android-GData");
request.addHeader("Accept-Encoding", "gzip");
// only add the auth token if not null (to allow for GData feeds that do
// not require
// authentication.)
if (!TextUtils.isEmpty(authToken)) {
request.addHeader("Authorization", "GoogleLogin auth=" + authToken);
}
if (LOCAL_LOGV) {
for (Header h : request.getAllHeaders()) {
Log.v(TAG, h.getName() + ": " + h.getValue());
}
Log.d(TAG, "Executing " + request.getRequestLine().toString());
}
response = null;
try {
response = httpClient.execute(request);
} catch (IOException ioe) {
Log.w(TAG, "Unable to execute HTTP request." + ioe);
throw ioe;
}
StatusLine statusLine = response.getStatusLine();
if (statusLine == null) {
Log.w(TAG, "StatusLine is null.");
throw new NullPointerException(
"StatusLine is null -- should not happen.");
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, response.getStatusLine().toString());
for (Header h : response.getAllHeaders()) {
Log.d(TAG, h.getName() + ": " + h.getValue());
}
}
status = statusLine.getStatusCode();
HttpEntity entity = response.getEntity();
if ((status >= 200) && (status < 300) && entity != null) {
return getUngzippedContent(entity);
}
// TODO: handle 301, 307?
// TODO: let the http client handle the redirects, if we can be sure we'll
// never get a
// redirect on POST.
if (status == 302) {
// consume the content, so the connection can be closed.
entity.consumeContent();
Header location = response.getFirstHeader("Location");
if (location == null) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Redirect requested but no Location " + "specified.");
}
break;
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Following redirect to " + location.getValue());
}
try {
uri = new URI(location.getValue());
} catch (URISyntaxException use) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.",
use);
throw new IOException("Unable to parse " + location.getValue()
+ " as URI.");
}
break;
}
--redirectsLeft;
} else {
break;
}
}
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Received " + status + " status code.");
}
String errorMessage = null;
HttpEntity entity = response.getEntity();
try {
if (response != null && entity != null) {
InputStream in = entity.getContent();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int bytesRead = -1;
while ((bytesRead = in.read(buf)) != -1) {
baos.write(buf, 0, bytesRead);
}
// TODO: use appropriate encoding, picked up from Content-Type.
errorMessage = new String(baos.toByteArray());
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, errorMessage);
}
}
} finally {
if (entity != null) {
entity.consumeContent();
}
}
String exceptionMessage = "Received " + status + " status code";
if (errorMessage != null) {
exceptionMessage += (": " + errorMessage);
}
throw new HttpException(exceptionMessage, status, null /* InputStream */);
}
/**
* Gets the input stream from a response entity. If the entity is gzipped
* then this will get a stream over the uncompressed data.
*
* @param entity the entity whose content should be read
* @return the input stream to read from
* @throws IOException
*/
private static InputStream getUngzippedContent(HttpEntity entity)
throws IOException {
InputStream responseStream = entity.getContent();
if (responseStream == null) {
return responseStream;
}
Header header = entity.getContentEncoding();
if (header == null) {
return responseStream;
}
String contentEncoding = header.getValue();
if (contentEncoding == null) {
return responseStream;
}
if (contentEncoding.contains("gzip")){
responseStream = new GZIPInputStream(responseStream);
}
return responseStream;
}
/*
* (non-Javadoc)
*
* @see GDataClient#getFeedAsStream(java.lang.String, java.lang.String)
*/
public InputStream getFeedAsStream(String feedUrl, String authToken)
throws HttpException, IOException {
InputStream in =
createAndExecuteMethod(new GetRequestCreator(), feedUrl, authToken);
if (in != null) {
return in;
}
throw new IOException("Unable to access feed.");
}
public InputStream getMediaEntryAsStream(String mediaEntryUrl,
String authToken) throws HttpException, IOException {
InputStream in =
createAndExecuteMethod(new GetRequestCreator(), mediaEntryUrl,
authToken);
if (in != null) {
return in;
}
throw new IOException("Unable to access media entry.");
}
/*
* (non-Javadoc)
*
* @see GDataClient#createEntry
*/
public InputStream createEntry(String feedUrl, String authToken,
GDataSerializer entry) throws HttpException, IOException {
HttpEntity entity =
createEntityForEntry(entry, GDataSerializer.FORMAT_CREATE);
InputStream in =
createAndExecuteMethod(new PostRequestCreator(null /* override */,
entity), feedUrl, authToken);
if (in != null) {
return in;
}
throw new IOException("Unable to create entry.");
}
/*
* (non-Javadoc)
*
* @see GDataClient#updateEntry
*/
public InputStream updateEntry(String editUri, String authToken,
GDataSerializer entry) throws HttpException, IOException {
HttpEntity entity =
createEntityForEntry(entry, GDataSerializer.FORMAT_UPDATE);
InputStream in =
createAndExecuteMethod(new PostRequestCreator("PUT", entity), editUri,
authToken);
if (in != null) {
return in;
}
throw new IOException("Unable to update entry.");
}
/*
* (non-Javadoc)
*
* @see GDataClient#deleteEntry
*/
public void deleteEntry(String editUri, String authToken)
throws HttpException, IOException {
if (StringUtils.isEmpty(editUri)) {
throw new IllegalArgumentException(
"you must specify an non-empty edit url");
}
InputStream in =
createAndExecuteMethod(
new PostRequestCreator("DELETE", null /* entity */), editUri,
authToken);
if (in == null) {
throw new IOException("Unable to delete entry.");
}
try {
in.close();
} catch (IOException ioe) {
// ignore
}
}
public InputStream updateMediaEntry(String editUri, String authToken,
InputStream mediaEntryInputStream, String contentType)
throws HttpException, IOException {
InputStream in =
createAndExecuteMethod(new MediaPutRequestCreator(
mediaEntryInputStream, contentType), editUri, authToken);
if (in != null) {
return in;
}
throw new IOException("Unable to write media entry.");
}
private HttpEntity createEntityForEntry(GDataSerializer entry, int format)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
entry.serialize(baos, format);
} catch (IOException ioe) {
Log.e(TAG, "Unable to serialize entry.", ioe);
throw ioe;
} catch (ParseException pe) {
Log.e(TAG, "Unable to serialize entry.", pe);
throw new IOException("Unable to serialize entry: " + pe.getMessage());
}
byte[] entryBytes = baos.toByteArray();
if (entryBytes != null && Log.isLoggable(TAG, Log.DEBUG)) {
try {
Log.d(TAG, "Serialized entry: " + new String(entryBytes, "UTF-8"));
} catch (UnsupportedEncodingException uee) {
// should not happen
throw new IllegalStateException("UTF-8 should be supported!", uee);
}
}
AbstractHttpEntity entity = new ByteArrayEntity(entryBytes);
entity.setContentType(entry.getContentType());
return entity;
}
}
| 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.gdata;
import com.google.wireless.gdata.client.QueryParams;
import android.text.TextUtils;
import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Simple implementation of the QueryParams interface.
*/
// TODO: deal with categories
public class QueryParamsImpl extends QueryParams {
private final Map<String, String> mParams = new HashMap<String, String>();
@Override
public void clear() {
setEntryId(null);
mParams.clear();
}
@Override
public String generateQueryUrl(String feedUrl) {
if (TextUtils.isEmpty(getEntryId()) && mParams.isEmpty()) {
// nothing to do
return feedUrl;
}
// handle entry IDs
if (!TextUtils.isEmpty(getEntryId())) {
if (!mParams.isEmpty()) {
throw new IllegalStateException("Cannot set both an entry ID "
+ "and other query paramters.");
}
return feedUrl + '/' + getEntryId();
}
// otherwise, append the querystring params.
StringBuilder sb = new StringBuilder();
sb.append(feedUrl);
Set<String> params = mParams.keySet();
boolean first = true;
if (feedUrl.contains("?")) {
first = false;
} else {
sb.append('?');
}
for (String param : params) {
if (first) {
first = false;
} else {
sb.append('&');
}
sb.append(param);
sb.append('=');
String value = mParams.get(param);
String encodedValue = null;
try {
encodedValue = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException uee) {
// should not happen.
Log.w("QueryParamsImpl", "UTF-8 not supported -- should not happen. "
+ "Using default encoding.", uee);
encodedValue = URLEncoder.encode(value);
}
sb.append(encodedValue);
}
return sb.toString();
}
@Override
public String getParamValue(String param) {
if (!(mParams.containsKey(param))) {
return null;
}
return mParams.get(param);
}
@Override
public void setParamValue(String param, String value) {
mParams.put(param, value);
}
}
| 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.gdata;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.wireless.gdata.client.GDataClient;
import android.content.Context;
import android.util.Log;
/**
* This factory will fetch the right class for the platform.
*
* @author Sandor Dornbush
*/
public class GDataClientFactory {
private GDataClientFactory() { }
/**
* Creates a new GData client.
* This factory will fetch the right class for the platform.
* @return A GDataClient appropriate for this platform
*/
public static GDataClient getGDataClient(Context context) {
try {
// Try to use the official unbundled gdata client implementation.
// This should work on Froyo and beyond.
return new com.google.android.common.gdata.AndroidGDataClient(context);
} catch (LinkageError e) {
// On all other platforms use the client implementation packaged in the
// apk.
Log.i(MyTracksConstants.TAG, "Using mytracks AndroidGDataClient.", e);
return new com.google.android.apps.mytracks.io.gdata.AndroidGDataClient();
}
}
}
| 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.gdata;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.io.AuthManager;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* GDataWrapper provides a wrapper around GData operations that maintains the
* GData client, and provides a method to run GData queries with proper error
* handling. After a query is run, the wrapper can be queried about the error
* that occurred.
*
* @param C the GData service client
* @author Sandor Dornbush
*/
public class GDataWrapper<C> {
public static class AuthenticationException extends Exception {
private Exception exception;
private static final long serialVersionUID = 1L;
public AuthenticationException(Exception caught) {
this.exception = caught;
}
public Exception getException() {
return exception;
}
};
public static class ParseException extends Exception {
private Exception exception;
private static final long serialVersionUID = 1L;
public ParseException(Exception caught) {
this.exception = caught;
}
public Exception getException() {
return exception;
}
};
public static class ConflictDetectedException extends Exception {
private Exception exception;
private static final long serialVersionUID = 1L;
public ConflictDetectedException(Exception caught) {
this.exception = caught;
}
public Exception getException() {
return exception;
}
};
public static class HttpException extends Exception {
private static final long serialVersionUID = 1L;
private int statusCode;
private String statusMessage;
public HttpException(int statusCode, String statusMessage) {
super();
this.statusCode = statusCode;
this.statusMessage = statusMessage;
}
public int getStatusCode() {
return statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
};
/**
* A QueryFunction is passed in when executing a query. The query function of
* the class is called with the GData client as a parameter. The function
* should execute whatever operations it desires on the client without concern
* for whether the client will throw an error.
*/
public interface QueryFunction<C> {
public abstract void query(C client)
throws AuthenticationException, IOException, ParseException,
ConflictDetectedException, HttpException;
}
/**
* A AuthenticatedFunction is passed in when executing the google
* authenticated service. The authenticated function of the class is called
* with the current authentication token for the service. The function should
* execute whatever operations with the google service without concern for
* whether the client will throw an error.
*/
public interface AuthenticatedFunction {
public abstract void run(String authenticationToken)
throws AuthenticationException, IOException;
}
// The types of error that may be encountered
// No error occurred.
public static final int ERROR_NO_ERROR = 0;
// There was an authentication error, the auth token may be invalid.
public static final int ERROR_AUTH = 1;
// There was an internal error on the server side.
public static final int ERROR_INTERNAL = 2;
// There was an error connecting to the server.
public static final int ERROR_CONNECTION = 3;
// The item queried did not exit.
public static final int ERROR_NOT_FOUND = 4;
// There was an error parsing or serializing locally.
public static final int ERROR_LOCAL = 5;
// There was a conflict, update the entry and try again.
public static final int ERROR_CONFLICT = 6;
// A query was run after cleaning up the wrapper, so the client was invalid.
public static final int ERROR_CLEANED_UP = 7;
// An unknown error occurred.
public static final int ERROR_UNKNOWN = 100;
private static final int AUTH_TOKEN_INVALIDATE_REFRESH_NUM_RETRIES = 1;
private static final int AUTH_TOKEN_INVALIDATE_REFRESH_TIMEOUT = 5000;
private String errorMessage;
private int errorType;
private C gdataServiceClient;
private AuthManager auth;
private boolean retryOnAuthFailure;
public GDataWrapper() {
errorType = ERROR_NO_ERROR;
errorMessage = null;
auth = null;
retryOnAuthFailure = false;
}
public void setClient(C gdataServiceClient) {
this.gdataServiceClient = gdataServiceClient;
}
public boolean runAuthenticatedFunction(
final AuthenticatedFunction function) {
return runCommon(function, null);
}
public boolean runQuery(final QueryFunction<C> query) {
return runCommon(null, query);
}
/**
* Runs an arbitrary piece of code.
*/
private boolean runCommon(final AuthenticatedFunction function,
final QueryFunction<C> query) {
for (int i = 0; i <= AUTH_TOKEN_INVALIDATE_REFRESH_NUM_RETRIES; i++) {
runOne(function, query);
if (errorType == ERROR_NO_ERROR) {
return true;
}
Log.d(MyTracksConstants.TAG, "GData error encountered: " + errorMessage);
if (errorType == ERROR_AUTH && auth != null) {
if (!retryOnAuthFailure || !invalidateAndRefreshAuthToken()) {
return false;
}
}
Log.d(MyTracksConstants.TAG, "retrying function/query");
}
return false;
}
/**
* Execute a given function or query. If one is executed, errorType and
* errorMessage will contain the result/status of the function/query.
*/
private void runOne(final AuthenticatedFunction function,
final QueryFunction<C> query) {
try {
if (function != null) {
function.run(this.auth.getAuthToken());
} else if (query != null) {
query.query(gdataServiceClient);
} else {
throw new IllegalArgumentException(
"invalid invocation of runOne; one of function/query " +
"must be non-null");
}
errorType = ERROR_NO_ERROR;
errorMessage = null;
} catch (AuthenticationException e) {
Log.e(MyTracksConstants.TAG, "AuthenticationException", e);
errorType = ERROR_AUTH;
errorMessage = e.getMessage();
} catch (HttpException e) {
Log.e(MyTracksConstants.TAG,
"HttpException, code " + e.getStatusCode() + " message " + e.getMessage(), e);
errorMessage = e.getMessage();
if (e.getStatusCode() == 401) {
errorType = ERROR_AUTH;
} else {
errorType = ERROR_CONNECTION;
}
} catch (FileNotFoundException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_AUTH;
errorMessage = e.getMessage();
} catch (IOException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorMessage = e.getMessage();
if (errorMessage != null && errorMessage.contains("503")) {
errorType = ERROR_INTERNAL;
} else {
errorType = ERROR_CONNECTION;
}
} catch (ParseException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_LOCAL;
errorMessage = e.getMessage();
} catch (ConflictDetectedException e) {
Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_CONFLICT;
errorMessage = e.getMessage();
}
}
/**
* Invalidates and refreshes the auth token. Blocks until the refresh has
* completed or until we deem the refresh as having timed out.
*
* @return true If the invalidate/refresh succeeds, false if it fails or
* times out.
*/
private boolean invalidateAndRefreshAuthToken() {
Log.d(MyTracksConstants.TAG, "Retrying due to auth failure");
// This FutureTask doesn't do anything -- it exists simply to be
// blocked upon using get().
FutureTask<?> whenFinishedFuture = new FutureTask<Object>(new Runnable() {
public void run() {}
}, null);
auth.invalidateAndRefresh(whenFinishedFuture);
try {
Log.d(MyTracksConstants.TAG, "waiting for invalidate");
whenFinishedFuture.get(AUTH_TOKEN_INVALIDATE_REFRESH_TIMEOUT,
TimeUnit.MILLISECONDS);
Log.d(MyTracksConstants.TAG, "invalidate finished");
return true;
} catch (InterruptedException e) {
Log.e(MyTracksConstants.TAG, "Failed to invalidate", e);
} catch (ExecutionException e) {
Log.e(MyTracksConstants.TAG, "Failed to invalidate", e);
} catch (TimeoutException e) {
Log.e(MyTracksConstants.TAG, "Invalidate didn't complete in time", e);
} finally {
whenFinishedFuture.cancel(false);
}
return false;
}
public int getErrorType() {
return errorType;
}
public String getErrorMessage() {
return errorMessage;
}
public void setAuthManager(AuthManager auth) {
this.auth = auth;
}
public AuthManager getAuthManager() {
return auth;
}
public void setRetryOnAuthFailure(boolean retry) {
retryOnAuthFailure = retry;
}
}
| 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.io;
import com.google.android.googlelogindist.GoogleLoginServiceConstants;
import com.google.android.googlelogindist.GoogleLoginServiceHelper;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import java.util.Iterator;
import java.util.Vector;
/**
* AuthManager keeps track of the current auth token for a user. The advantage
* over just passing around a String is that this class can renew the auth
* token if necessary, and it will change for all classes using this
* AuthManager.
*/
public class AuthManagerOld implements AuthManager {
/** The activity that will handle auth result callbacks. */
private final Activity activity;
/** The code used to tell the activity that it is an auth result. */
private final int code;
/** Extras to pass into the getCredentials function. */
private final Bundle extras;
/** True if the account must be a Google account (not a domain account). */
private final boolean requireGoogle;
/** The name of the service to authorize for. */
private final String service;
/** A list of handlers to call when a new auth token is fetched. */
private final Vector<Runnable> newTokenListeners = new Vector<Runnable>();
/** The most recently fetched auth token or null if none is available. */
private String authToken;
/**
* The number of handlers at the beginning of the above list that shouldn't
* be removed after they are called.
*/
private int stickyNewTokenListenerCount;
/**
* AuthManager requires many of the same parameters as
* {@link GoogleLoginServiceHelper#getCredentials(Activity, int, Bundle,
* boolean, String, boolean)}. The activity must have
* a handler in {@link Activity#onActivityResult} that calls
* {@link #authResult(int, Intent)} if the request code is the code given
* here.
*
* @param activity An activity with a handler in
* {@link Activity#onActivityResult} that calls
* {@link #authResult(int, Intent)} when {@literal code} is the request
* code
* @param code The request code to pass to
* {@link Activity#onActivityResult} when
* {@link #authResult(int, Intent)} should be called
* @param extras A {@link Bundle} of extras for
* {@link GoogleLoginServiceHelper}
* @param requireGoogle True if the account must be a Google account
* @param service The name of the service to authenticate as
*/
public AuthManagerOld(Activity activity, int code, Bundle extras,
boolean requireGoogle, String service) {
this.activity = activity;
this.code = code;
this.extras = extras;
this.requireGoogle = requireGoogle;
this.service = service;
}
/* (non-Javadoc)
* @see com.google.android.apps.mytracks.io.AuthManager#doLogin(java.lang.Runnable)
*/
public void doLogin(Runnable whenFinished, Object o) {
synchronized (newTokenListeners) {
if (whenFinished != null) {
newTokenListeners.add(whenFinished);
}
}
activity.runOnUiThread(new LoginRunnable());
}
/**
* Runnable which actually gets login credentials.
*/
private class LoginRunnable implements Runnable {
@Override
public void run() {
GoogleLoginServiceHelper.getCredentials(
activity, code, extras, requireGoogle, service, true);
}
}
/* (non-Javadoc)
* @see com.google.android.apps.mytracks.io.AuthManager#authResult(int, android.content.Intent)
*/
public boolean authResult(int resultCode, Intent results) {
if (resultCode == Activity.RESULT_OK) {
authToken = results.getStringExtra(
GoogleLoginServiceConstants.AUTHTOKEN_KEY);
if (authToken == null) {
GoogleLoginServiceHelper.getCredentials(
activity, code, extras, requireGoogle, service, false);
return true;
} else {
// Notify all active listeners that we have a new auth token.
synchronized (newTokenListeners) {
Iterator<Runnable> iter = newTokenListeners.iterator();
while (iter.hasNext()) {
iter.next().run();
}
iter = null;
// Remove anything not in the sticky part of the list.
newTokenListeners.setSize(stickyNewTokenListenerCount);
}
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see com.google.android.apps.mytracks.io.AuthManager#getAuthToken()
*/
public String getAuthToken() {
return authToken;
}
/* (non-Javadoc)
* @see com.google.android.apps.mytracks.io.AuthManager#invalidateAndRefresh(java.lang.Runnable)
*/
public void invalidateAndRefresh(Runnable whenFinished) {
synchronized (newTokenListeners) {
if (whenFinished != null) {
newTokenListeners.add(whenFinished);
}
}
activity.runOnUiThread(new Runnable() {
public void run() {
GoogleLoginServiceHelper.invalidateAuthToken(activity, code, authToken);
}
});
}
/**
* Adds a {@link Runnable} to be executed every time the auth token is
* updated. The {@link Runnable} will not be removed until manually removed
* with {@link #removeStickyNewTokenListener(Runnable)}.
*
* @param listener The {@link Runnable} to execute every time a new auth
* token is fetched
*/
public void addStickyNewTokenListener(Runnable listener) {
synchronized (newTokenListeners) {
newTokenListeners.add(0, listener);
stickyNewTokenListenerCount++;
}
}
/**
* Stops executing the given {@link Runnable} every time the auth token is
* updated. This {@link Runnable} must have been added with
* {@link #addStickyNewTokenListener(Runnable)} above. If the
* {@link Runnable} was added more than once, only the first occurrence
* will be removed.
*
* @param listener The {@link Runnable} to stop executing every time a new
* auth token is fetched
*/
public void removeStickyNewTokenListener(Runnable listener) {
synchronized (newTokenListeners) {
if (stickyNewTokenListenerCount > 0
&& newTokenListeners.remove(listener)) {
stickyNewTokenListenerCount--;
}
}
}
}
| 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;
import android.content.Intent;
/**
* This interface describes a class that will fetch and maintain a Google
* authentication token.
*
* @author Sandor Dornbush
*/
public interface AuthManager {
/**
* Initializes the login process. The user should be asked to login if they
* haven't already. The {@link Runnable} provided will be executed when the
* auth token is successfully fetched.
*
* @param whenFinished A {@link Runnable} to execute when the auth token
* has been successfully fetched and is available via
* {@link #getAuthToken()}
*/
public abstract void doLogin(Runnable whenFinished, Object o);
/**
* The {@link android.app.Activity} owner of this class should call this
* function when it gets {@link android.app.Activity#onActivityResult} with
* the request code passed into the constructor. The resultCode and results
* should come directly from the {@link android.app.Activity#onActivityResult}
* function. This function will return true if an auth token was successfully
* fetched or the process is not finished.
*
* @param resultCode The result code passed in to the
* {@link android.app.Activity}'s
* {@link android.app.Activity#onActivityResult} function
* @param results The data passed in to the {@link android.app.Activity}'s
* {@link android.app.Activity#onActivityResult} function
* @return True if the auth token was fetched or we aren't done fetching
* the auth token, or False if there was an error or the request was
* canceled
*/
public abstract boolean authResult(int resultCode, Intent results);
/**
* Returns the current auth token. Response may be null if no valid auth
* token has been fetched.
*
* @return The current auth token or null if no auth token has been
* fetched
*/
public abstract String getAuthToken();
/**
* Invalidates the existing auth token and request a new one. The
* {@link Runnable} provided will be executed when the new auth token is
* successfully fetched.
*
* @param whenFinished A {@link Runnable} to execute when a new auth token
* is successfully fetched
*/
public abstract void invalidateAndRefresh(Runnable whenFinished);
}
| 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.backup;
import static com.google.android.apps.mytracks.content.ContentTypeIds.*;
import com.google.android.apps.mytracks.content.TrackPointsColumns;
import com.google.android.apps.mytracks.content.TracksColumns;
import com.google.android.apps.mytracks.content.WaypointsColumns;
public class BackupColumns {
/** Columns that go into the backup. */
public static final String[] POINTS_BACKUP_COLUMNS =
{ TrackPointsColumns._ID, TrackPointsColumns.TRACKID, TrackPointsColumns.LATITUDE,
TrackPointsColumns.LONGITUDE, TrackPointsColumns.ALTITUDE, TrackPointsColumns.BEARING,
TrackPointsColumns.TIME, TrackPointsColumns.ACCURACY, TrackPointsColumns.SPEED,
TrackPointsColumns.SENSOR };
public static final byte[] POINTS_BACKUP_COLUMN_TYPES =
{ LONG_TYPE_ID, LONG_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, FLOAT_TYPE_ID,
FLOAT_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, BLOB_TYPE_ID };
public static final String[] TRACKS_BACKUP_COLUMNS = {
TracksColumns._ID, TracksColumns.NAME, TracksColumns.DESCRIPTION, TracksColumns.CATEGORY,
TracksColumns.STARTID, TracksColumns.STOPID, TracksColumns.STARTTIME, TracksColumns.STOPTIME,
TracksColumns.NUMPOINTS, TracksColumns.TOTALDISTANCE, TracksColumns.TOTALTIME,
TracksColumns.MOVINGTIME, TracksColumns.AVGSPEED, TracksColumns.AVGMOVINGSPEED,
TracksColumns.MAXSPEED, TracksColumns.MINELEVATION, TracksColumns.MAXELEVATION,
TracksColumns.ELEVATIONGAIN, TracksColumns.MINGRADE, TracksColumns.MAXGRADE,
TracksColumns.MINLAT, TracksColumns.MAXLAT, TracksColumns.MINLON, TracksColumns.MAXLON,
TracksColumns.MAPID, TracksColumns.TABLEID};
public static final byte[] TRACKS_BACKUP_COLUMN_TYPES = {
LONG_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID,
LONG_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, INT_TYPE_ID,
FLOAT_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID,
FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID,
FLOAT_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, STRING_TYPE_ID,
STRING_TYPE_ID};
public static final String[] WAYPOINTS_BACKUP_COLUMNS = {
WaypointsColumns._ID, WaypointsColumns.TRACKID, WaypointsColumns.NAME,
WaypointsColumns.DESCRIPTION, WaypointsColumns.CATEGORY, WaypointsColumns.ICON,
WaypointsColumns.TYPE, WaypointsColumns.LENGTH, WaypointsColumns.DURATION,
WaypointsColumns.STARTTIME, WaypointsColumns.STARTID, WaypointsColumns.STOPID,
WaypointsColumns.LATITUDE, WaypointsColumns.LONGITUDE, WaypointsColumns.ALTITUDE,
WaypointsColumns.BEARING, WaypointsColumns.TIME, WaypointsColumns.ACCURACY,
WaypointsColumns.SPEED, WaypointsColumns.TOTALDISTANCE, WaypointsColumns.TOTALTIME,
WaypointsColumns.MOVINGTIME, WaypointsColumns.AVGSPEED, WaypointsColumns.AVGMOVINGSPEED,
WaypointsColumns.MAXSPEED, WaypointsColumns.MINELEVATION, WaypointsColumns.MAXELEVATION,
WaypointsColumns.ELEVATIONGAIN, WaypointsColumns.MINGRADE, WaypointsColumns.MAXGRADE };
public static final byte[] WAYPOINTS_BACKUP_COLUMN_TYPES = {
LONG_TYPE_ID, LONG_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID,
STRING_TYPE_ID, STRING_TYPE_ID, INT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID,
LONG_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID,
FLOAT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID,
FLOAT_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID,
FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID,
FLOAT_TYPE_ID };
}
| 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.backup;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.MyTracksSettings;
import com.google.android.apps.mytracks.content.TrackPointsColumns;
import com.google.android.apps.mytracks.content.TracksColumns;
import com.google.android.apps.mytracks.content.WaypointsColumns;
import com.google.android.apps.mytracks.util.FileUtils;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* Handler for writing or reading single-file backups.
*
* @author Rodrigo Damazio
*/
class ExternalFileBackup {
// Filename format - in UTC
private static final SimpleDateFormat BACKUP_FILENAME_FORMAT =
new SimpleDateFormat("'backup-'yyyy-MM-dd_HH-mm-ss'.zip'");
static {
BACKUP_FILENAME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
private static final String BACKUPS_SUBDIR = "backups";
private static final int BACKUP_FORMAT_VERSION = 1;
private static final String ZIP_ENTRY_NAME =
"backup.mytracks.v" + BACKUP_FORMAT_VERSION;
private static final int COMPRESSION_LEVEL = 8;
private final Context context;
private final FileUtils fileUtils;
public ExternalFileBackup(Context context, FileUtils fileUtils) {
this.context = context;
this.fileUtils = fileUtils;
}
/**
* Returns whether the backups directory is (or can be made) available.
*
* @param create whether to try creating the directory if it doesn't exist
*/
public boolean isBackupsDirectoryAvailable(boolean create) {
return getBackupsDirectory(create) != null;
}
/**
* Returns the backup directory, or null if not available.
*
* @param create whether to try creating the directory if it doesn't exist
*/
private File getBackupsDirectory(boolean create) {
String dirName = fileUtils.buildExternalDirectoryPath(BACKUPS_SUBDIR);
final File dir = new File(dirName);
Log.d(MyTracksConstants.TAG, "Dir: " + dir.getAbsolutePath());
if (create) {
// Try to create - if that fails, return null
return fileUtils.ensureDirectoryExists(dir) ? dir : null;
} else {
// Return it if it already exists, otherwise return null
return dir.isDirectory() ? dir : null;
}
}
/**
* Returns a list of available backups to be restored.
*/
public Date[] getAvailableBackups() {
File dir = getBackupsDirectory(false);
if (dir == null) { return null; }
String[] fileNames = dir.list();
List<Date> backupDates = new ArrayList<Date>(fileNames.length);
for (int i = 0; i < fileNames.length; i++) {
String fileName = fileNames[i];
try {
backupDates.add(BACKUP_FILENAME_FORMAT.parse(fileName));
} catch (ParseException e) {
// Not a backup file, ignore
}
}
return backupDates.toArray(new Date[backupDates.size()]);
}
/**
* Writes the backup to the default file.
*/
public void writeToDefaultFile() throws IOException {
writeToFile(getFileForDate(new Date()));
}
/**
* Restores the backup from the given date.
*/
public void restoreFromDate(Date when) throws IOException {
restoreFromFile(getFileForDate(when));
}
/**
* Produces the proper file descriptor for the given backup date.
*/
private File getFileForDate(Date when) {
File dir = getBackupsDirectory(false);
String fileName = BACKUP_FILENAME_FORMAT.format(when);
File file = new File(dir, fileName);
return file;
}
/**
* Synchronously writes a backup to the given file.
*/
private void writeToFile(File outputFile) throws IOException {
Log.d(MyTracksConstants.TAG,
"Writing backup to file " + outputFile.getAbsolutePath());
// Create all the auxiliary classes that will do the writing
PreferenceBackupHelper preferencesHelper = new PreferenceBackupHelper();
DatabaseDumper trackDumper = new DatabaseDumper(
BackupColumns.TRACKS_BACKUP_COLUMNS,
BackupColumns.TRACKS_BACKUP_COLUMN_TYPES,
false);
DatabaseDumper waypointDumper = new DatabaseDumper(
BackupColumns.WAYPOINTS_BACKUP_COLUMNS,
BackupColumns.WAYPOINTS_BACKUP_COLUMN_TYPES,
false);
DatabaseDumper pointDumper = new DatabaseDumper(
BackupColumns.POINTS_BACKUP_COLUMNS,
BackupColumns.POINTS_BACKUP_COLUMN_TYPES,
false);
// Open the target for writing
FileOutputStream outputStream = new FileOutputStream(outputFile);
ZipOutputStream compressedStream = new ZipOutputStream(outputStream);
compressedStream.setLevel(COMPRESSION_LEVEL);
compressedStream.putNextEntry(new ZipEntry(ZIP_ENTRY_NAME));
DataOutputStream outWriter = new DataOutputStream(compressedStream);
try {
// Dump the entire contents of each table
ContentResolver contentResolver = context.getContentResolver();
Cursor tracksCursor = contentResolver.query(
TracksColumns.CONTENT_URI, null, null, null, null);
try {
trackDumper.writeAllRows(tracksCursor, outWriter);
} finally {
tracksCursor.close();
}
Cursor waypointsCursor = contentResolver.query(
WaypointsColumns.CONTENT_URI, null, null, null, null);
try {
waypointDumper.writeAllRows(waypointsCursor, outWriter);
} finally {
waypointsCursor.close();
}
Cursor pointsCursor = contentResolver.query(
TrackPointsColumns.CONTENT_URI, null, null, null, null);
try {
pointDumper.writeAllRows(pointsCursor, outWriter);
} finally {
pointsCursor.close();
}
// Dump preferences
SharedPreferences preferences =
context.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0);
preferencesHelper.exportPreferences(preferences, outWriter);
} catch (IOException e) {
// We tried to delete the partially created file, but do nothing
// if that also fails.
outputFile.delete();
throw e;
} finally {
compressedStream.closeEntry();
compressedStream.close();
}
}
/**
* Synchronously restores the backup from the given file.
*/
private void restoreFromFile(File inputFile) throws IOException {
Log.d(MyTracksConstants.TAG,
"Restoring from file " + inputFile.getAbsolutePath());
PreferenceBackupHelper preferencesHelper = new PreferenceBackupHelper();
ContentResolver resolver = context.getContentResolver();
DatabaseImporter trackImporter =
new DatabaseImporter(TracksColumns.CONTENT_URI, resolver, false);
DatabaseImporter waypointImporter =
new DatabaseImporter(WaypointsColumns.CONTENT_URI, resolver, false);
DatabaseImporter pointImporter =
new DatabaseImporter(TrackPointsColumns.CONTENT_URI, resolver, false);
ZipFile zipFile = new ZipFile(inputFile, ZipFile.OPEN_READ);
ZipEntry zipEntry = zipFile.getEntry(ZIP_ENTRY_NAME);
if (zipEntry == null) {
throw new IOException("Invalid backup ZIP file");
}
InputStream compressedStream = zipFile.getInputStream(zipEntry);
DataInputStream reader = new DataInputStream(compressedStream);
try {
// Delete all previous contents of the tables and preferences.
resolver.delete(TracksColumns.CONTENT_URI, null, null);
resolver.delete(TrackPointsColumns.CONTENT_URI, null, null);
resolver.delete(WaypointsColumns.CONTENT_URI, null, null);
// Import the new contents of each table
trackImporter.importAllRows(reader);
waypointImporter.importAllRows(reader);
pointImporter.importAllRows(reader);
// Restore preferences
SharedPreferences preferences =
context.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0);
preferencesHelper.importPreferences(reader, preferences);
} finally {
compressedStream.close();
zipFile.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.backup;
import com.google.android.apps.mytracks.content.ContentTypeIds;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Map;
/**
* Helper for backing up and restoring shared preferences.
*
* @author Rodrigo Damazio
*/
class PreferenceBackupHelper {
private static final int BUFFER_SIZE = 2048;
/**
* Exports all shared preferences from the given object as a byte array.
*
* @param preferences the preferences to export
* @return the corresponding byte array
* @throws IOException if there are any errors while writing to the byte array
*/
public byte[] exportPreferences(SharedPreferences preferences)
throws IOException {
ByteArrayOutputStream bufStream = new ByteArrayOutputStream(BUFFER_SIZE);
DataOutputStream outWriter = new DataOutputStream(bufStream);
exportPreferences(preferences, outWriter);
return bufStream.toByteArray();
}
/**
* Exports all shared preferences from the given object into the given output
* stream.
*
* @param preferences the preferences to export
* @param outWriter the stream to write them to
* @throws IOException if there are any errors while writing the output
*/
public void exportPreferences(
SharedPreferences preferences,
DataOutputStream outWriter) throws IOException {
Map<String, ?> values = preferences.getAll();
outWriter.writeInt(values.size());
for (Map.Entry<String, ?> entry : values.entrySet()) {
writePreference(entry.getKey(), entry.getValue(), outWriter);
}
outWriter.flush();
}
/**
* Imports all preferences from the given byte array.
*
* @param data the byte array to read preferences from
* @param preferences the shared preferences to edit
* @return whether the preference change was successful
* @throws IOException if there are any errors while reading
*/
public boolean importPreferences(byte[] data, SharedPreferences preferences)
throws IOException {
ByteArrayInputStream bufStream = new ByteArrayInputStream(data);
DataInputStream reader = new DataInputStream(bufStream);
return importPreferences(reader, preferences);
}
/**
* Imports all preferences from the given stream.
*
* @param reader the stream to read from
* @param preferences the shared preferences to edit
* @return whether the preference change was successful
* @throws IOException if there are any errors while reading
*/
public boolean importPreferences(DataInputStream reader,
SharedPreferences preferences) throws IOException {
Editor editor = preferences.edit();
editor.clear();
int numPreferences = reader.readInt();
for (int i = 0; i < numPreferences; i++) {
String name = reader.readUTF();
byte typeId = reader.readByte();
readAndSetPreference(name, typeId, reader, editor);
}
return editor.commit();
}
/**
* Reads a single preference and sets it into the given editor.
*
* @param name the name of the preference to read
* @param typeId the type ID of the preference to read
* @param reader the reader to read from
* @param editor the editor to set the preference in
* @throws IOException if there are errors while reading
*/
private void readAndSetPreference(String name, byte typeId,
DataInputStream reader, Editor editor) throws IOException {
switch (typeId) {
case ContentTypeIds.BOOLEAN_TYPE_ID:
editor.putBoolean(name, reader.readBoolean());
return;
case ContentTypeIds.LONG_TYPE_ID:
editor.putLong(name, reader.readLong());
return;
case ContentTypeIds.FLOAT_TYPE_ID:
editor.putFloat(name, reader.readFloat());
return;
case ContentTypeIds.INT_TYPE_ID:
editor.putInt(name, reader.readInt());
return;
case ContentTypeIds.STRING_TYPE_ID:
editor.putString(name, reader.readUTF());
return;
}
}
/**
* Writes a single preference.
*
* @param name the name of the preference to write
* @param value the correctly-typed value of the preference
* @param writer the writer to write to
* @throws IOException if there are errors while writing
*/
private void writePreference(String name, Object value, DataOutputStream writer)
throws IOException {
writer.writeUTF(name);
if (value instanceof Boolean) {
writer.writeByte(ContentTypeIds.BOOLEAN_TYPE_ID);
writer.writeBoolean((Boolean) value);
} else if (value instanceof Integer) {
writer.writeByte(ContentTypeIds.INT_TYPE_ID);
writer.writeInt((Integer) value);
} else if (value instanceof Long) {
writer.writeByte(ContentTypeIds.LONG_TYPE_ID);
writer.writeLong((Long) value);
} else if (value instanceof Float) {
writer.writeByte(ContentTypeIds.FLOAT_TYPE_ID);
writer.writeFloat((Float) value);
} else if (value instanceof String) {
writer.writeByte(ContentTypeIds.STRING_TYPE_ID);
writer.writeUTF((String) value);
} else {
throw new IllegalArgumentException(
"Type " + value.getClass().getName() + " not supported");
}
}
}
| 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.backup;
import com.google.android.apps.mytracks.MyTracks;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.util.FileUtils;
import com.google.android.maps.mytracks.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
/**
* Helper which shows a UI for writing or restoring a backup,
* and calls the appropriate handler for actually executing those
* operations.
*
* @author Rodrigo Damazio
*/
public class BackupActivityHelper {
// Since the user sees this format, we use the local timezone
private static final SimpleDateFormat DISPLAY_BACKUP_FORMAT =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static final Comparator<Date> REVERSE_DATE_ORDER =
new Comparator<Date>() {
@Override
public int compare(Date s1, Date s2) {
return s2.compareTo(s1);
}
};
private final FileUtils fileUtils;
private final ExternalFileBackup backup;
private final Activity activity;
public BackupActivityHelper(Activity activity) {
this.activity = activity;
this.fileUtils = new FileUtils();
this.backup = new ExternalFileBackup(activity, fileUtils);
}
/**
* Writes a full backup to the default file.
* This shows the results to the user.
*/
public void writeBackup() {
if (!fileUtils.isSdCardAvailable()) {
showToast(R.string.io_no_external_storage_found);
return;
}
if (!backup.isBackupsDirectoryAvailable(true)) {
showToast(R.string.io_create_dir_failed);
return;
}
final ProgressDialog progressDialog = ProgressDialog.show(
activity,
activity.getString(R.string.progress_title),
activity.getString(R.string.backup_write_progress_message),
true);
// Do the writing in another thread
new Thread() {
@Override
public void run() {
try {
backup.writeToDefaultFile();
showToast(R.string.io_write_finished);
} catch (IOException e) {
Log.e(MyTracksConstants.TAG, "Failed to write backup", e);
showToast(R.string.io_write_failed);
} finally {
dismissDialog(progressDialog);
}
}
}.start();
}
/**
* Restores a full backup from the SD card.
* The user will be given a choice of which backup to restore as well as a
* confirmation dialog.
*/
public void restoreBackup() {
// Get the list of existing backups
if (!fileUtils.isSdCardAvailable()) {
showToast(R.string.io_no_external_storage_found);
return;
}
if (!backup.isBackupsDirectoryAvailable(false)) {
showToast(R.string.no_backups);
return;
}
final Date[] backupDates = backup.getAvailableBackups();
if (backupDates == null || backupDates.length == 0) {
showToast(R.string.no_backups);
return;
}
Arrays.sort(backupDates, REVERSE_DATE_ORDER);
// Show a confirmation dialog
Builder confirmationDialogBuilder = new AlertDialog.Builder(activity);
confirmationDialogBuilder.setMessage(R.string.restore_overwrites_warning);
confirmationDialogBuilder.setCancelable(true);
confirmationDialogBuilder.setPositiveButton(android.R.string.yes,
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
pickBackupForRestore(backupDates);
}
});
confirmationDialogBuilder.setNegativeButton(android.R.string.no, null);
confirmationDialogBuilder.create().show();
}
/**
* Shows a backup list for the user to pick, then restores it.
*
* @param backupDir the backup directory
* @param backupDates the list of available backup files
*/
private void pickBackupForRestore(final Date[] backupDates) {
if (backupDates.length == 1) {
// Only one choice, don't bother showing the list
restoreFromDateAsync(backupDates[0]);
return;
}
// Make a user-visible version of the backup filenames
final String backupDateStrs[] = new String[backupDates.length];
for (int i = 0; i < backupDates.length; i++) {
backupDateStrs[i] = DISPLAY_BACKUP_FORMAT.format(backupDates[i]);
}
// Show a dialog for the user to pick which backup to restore
Builder dialogBuilder = new AlertDialog.Builder(activity);
dialogBuilder.setCancelable(true);
dialogBuilder.setTitle(R.string.select_backup_to_restore);
dialogBuilder.setItems(backupDateStrs, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// User picked to restore this one
restoreFromDateAsync(backupDates[which]);
}
});
dialogBuilder.create().show();
}
/**
* Shows a progress dialog, then starts restoring the backup osynchronously.
*
* @param inputFile the file to restore from
*/
private void restoreFromDateAsync(final Date date) {
// Show a progress dialog
final ProgressDialog progressDialog = ProgressDialog.show(
activity,
activity.getString(R.string.progress_title),
activity.getString(R.string.backup_import_progress_message),
true);
// Do the actual importing in another thread (don't block the UI)
new Thread() {
@Override
public void run() {
try {
backup.restoreFromDate(date);
showToast(R.string.io_read_finished);
} catch (IOException e) {
Log.e(MyTracksConstants.TAG, "Failed to restore backup", e);
showToast(R.string.io_read_failed);
} finally {
dismissDialog(progressDialog);
// Data may have been restored, "reboot" the app to catch it
restartApplication();
}
}
}.start();
}
/**
* Restarts My Tracks completely.
* This forces any modified data to be re-read.
*/
private void restartApplication() {
Intent intent = new Intent(activity, MyTracks.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(intent);
}
/**
* Shows a toast with the given contents.
*/
private void showToast(final int resId) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, resId, Toast.LENGTH_LONG).show();
}
});
}
/**
* Safely dismisses the given dialog.
*/
private void dismissDialog(final Dialog dialog) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
});
}
}
| 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.backup;
import com.google.android.apps.mytracks.content.ContentTypeIds;
import android.database.Cursor;
import android.database.MergeCursor;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* Database dumper which is able to write only part of the database
* according to some query.
*
* This dumper is symmetrical to {@link DatabaseImporter}.
*
* @author Rodrigo Damazio
*/
class DatabaseDumper {
/** The names of the columns being dumped. */
private final String[] columnNames;
/** The types of the columns being dumped. */
private final byte[] columnTypes;
/** Whether to output null fields. */
private final boolean outputNullFields;
// Temporary state
private int[] columnIndices;
private boolean[] hasFields;
public DatabaseDumper(String[] columnNames, byte[] columnTypes,
boolean outputNullFields) {
if (columnNames.length != columnTypes.length) {
throw new IllegalArgumentException("Names don't match types");
}
this.columnNames = columnNames;
this.columnTypes = columnTypes;
this.outputNullFields = outputNullFields;
}
/**
* Writes the header plus all rows that can be read from the given cursor.
* This assumes the cursor will have the same column and column indices on
* every row (and thus may not work with a {@link MergeCursor}).
*/
public void writeAllRows(Cursor cursor, DataOutputStream writer)
throws IOException {
writeHeaders(cursor, cursor.getCount(), writer);
if (!cursor.moveToFirst()) {
return;
}
do {
writeOneRow(cursor, writer);
} while (cursor.moveToNext());
}
/**
* Writes just the headers for the data that will come from the given cursor.
* The headers include column information and the number of rows that will be
* written.
*
* @param cursor the cursor to get columns from
* @param numRows the number of rows that will be later written
* @throws IOException if there are errors while writing
*/
public void writeHeaders(Cursor cursor, int numRows, DataOutputStream writer)
throws IOException {
initializeCachedValues(cursor);
writeQueryMetadata(cursor, numRows, writer);
}
/**
* Writes the current row from the cursor. The cursor is not advanced.
* This must be called after {@link #writeHeaders}.
*
* @param cursor the cursor to write data from
* @throws IOException if there are any errors while writing
*/
public void writeOneRow(Cursor cursor, DataOutputStream writer)
throws IOException {
if (columnIndices == null) {
throw new IllegalStateException(
"Cannot write rows before writing the header");
}
if (columnIndices.length > Long.SIZE) {
throw new IllegalArgumentException("Too many fields");
}
// Build a bitmap of which fields are present
long fields = 0;
for (int i = 0; i < columnIndices.length; i++) {
hasFields[i] = !cursor.isNull(columnIndices[i]);
fields |= (hasFields[i] ? 1 : 0) << i;
}
writer.writeLong(fields);
// Actually write the present fields
for (int i = 0; i < columnIndices.length; i++) {
if (hasFields[i]) {
writeCell(columnIndices[i], columnTypes[i], cursor, writer);
} else if (outputNullFields) {
writeDummyCell(columnTypes[i], writer);
}
}
}
/**
* Initializes the column indices and other temporary state for reading from
* the given cursor.
*/
private void initializeCachedValues(Cursor cursor) {
// These indices are constant for every row (unless we're fed a MergeCursor)
if (cursor instanceof MergeCursor) {
throw new IllegalArgumentException("Cannot use a MergeCursor");
}
columnIndices = new int[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
String columnName = columnNames[i];
columnIndices[i] = cursor.getColumnIndexOrThrow(columnName);
}
hasFields = new boolean[columnIndices.length];
}
/**
* Writes metadata about the query to be dumped.
*
* @param cursor the cursor that the data will come from
* @param numRows the number of rows that will be dumped
* @throws IOException if there are any errors while writing
*/
private void writeQueryMetadata(
Cursor cursor, int numRows, DataOutputStream writer) throws IOException {
// Write column data
writer.writeInt(columnNames.length);
for (int i = 0; i < columnNames.length; i++) {
String columnName = columnNames[i];
byte columnType = columnTypes[i];
writer.writeUTF(columnName);
writer.writeByte(columnType);
}
// Write the number of rows
writer.writeInt(numRows);
}
/**
* Writes a single cell of the database to the output.
*
* @param columnIdx the column index to read from
* @param columnTypeId the type of the column to be read
* @param cursor the cursor to read from
* @throws IOException if there are any errors while writing
*/
private void writeCell(
int columnIdx, byte columnTypeId, Cursor cursor, DataOutputStream writer)
throws IOException {
switch (columnTypeId) {
case ContentTypeIds.LONG_TYPE_ID:
writer.writeLong(cursor.getLong(columnIdx));
return;
case ContentTypeIds.DOUBLE_TYPE_ID:
writer.writeDouble(cursor.getDouble(columnIdx));
return;
case ContentTypeIds.FLOAT_TYPE_ID:
writer.writeFloat(cursor.getFloat(columnIdx));
return;
case ContentTypeIds.BOOLEAN_TYPE_ID:
writer.writeBoolean(cursor.getInt(columnIdx) != 0);
return;
case ContentTypeIds.INT_TYPE_ID:
writer.writeInt(cursor.getInt(columnIdx));
return;
case ContentTypeIds.STRING_TYPE_ID:
writer.writeUTF(cursor.getString(columnIdx));
return;
case ContentTypeIds.BLOB_TYPE_ID: {
byte[] blob = cursor.getBlob(columnIdx);
writer.writeInt(blob.length);
writer.write(blob);
return;
}
default:
throw new IllegalArgumentException(
"Type " + columnTypeId + " not supported");
}
}
/**
* Writes a dummy cell value to the output.
*
* @param columnTypeId the type of the value to write
* @throws IOException if there are any errors while writing
*/
private void writeDummyCell(byte columnTypeId, DataOutputStream writer)
throws IOException {
switch (columnTypeId) {
case ContentTypeIds.LONG_TYPE_ID:
writer.writeLong(0L);
return;
case ContentTypeIds.DOUBLE_TYPE_ID:
writer.writeDouble(0.0);
return;
case ContentTypeIds.FLOAT_TYPE_ID:
writer.writeFloat(0.0f);
return;
case ContentTypeIds.BOOLEAN_TYPE_ID:
writer.writeBoolean(false);
return;
case ContentTypeIds.INT_TYPE_ID:
writer.writeInt(0);
return;
case ContentTypeIds.STRING_TYPE_ID:
writer.writeUTF("");
return;
case ContentTypeIds.BLOB_TYPE_ID:
writer.writeInt(0);
return;
default:
throw new IllegalArgumentException(
"Type " + columnTypeId + " not supported");
}
}
}
| 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.backup;
import com.google.android.apps.mytracks.content.ContentTypeIds;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import java.io.DataInputStream;
import java.io.IOException;
/**
* Database importer which reads values written by {@link DatabaseDumper}.
*
* @author Rodrigo Damazio
*/
public class DatabaseImporter {
/** Maximum number of entries in a bulk insertion */
private static final int DEFAULT_BULK_SIZE = 1024;
private final Uri destinationUri;
private final ContentResolver resolver;
private final boolean readNullFields;
private final int bulkSize;
// Metadata read from the reader
private String[] columnNames;
private byte[] columnTypes;
public DatabaseImporter(Uri destinationUri, ContentResolver resolver,
boolean readNullFields) {
this(destinationUri, resolver, readNullFields, DEFAULT_BULK_SIZE);
}
protected DatabaseImporter(Uri destinationUri, ContentResolver resolver,
boolean readNullFields, int bulkSize) {
this.destinationUri = destinationUri;
this.resolver = resolver;
this.readNullFields = readNullFields;
this.bulkSize = bulkSize;
}
/**
* Reads the header which includes metadata about the table being imported.
*
* @throws IOException if there are any problems while reading
*/
private void readHeaders(DataInputStream reader) throws IOException {
int numColumns = reader.readInt();
columnNames = new String[numColumns];
columnTypes = new byte[numColumns];
for (int i = 0; i < numColumns; i++) {
columnNames[i] = reader.readUTF();
columnTypes[i] = reader.readByte();
}
}
/**
* Imports all rows from the reader into the database.
* Insertion is done in bulks for efficiency.
*
* @throws IOException if there are any errors while reading
*/
public void importAllRows(DataInputStream reader) throws IOException {
readHeaders(reader);
ContentValues[] valueBulk = new ContentValues[bulkSize];
int numValues = 0;
int numRows = reader.readInt();
int numColumns = columnNames.length;
// For each row
for (int r = 0; r < numRows; r++) {
if (valueBulk[numValues] == null) {
valueBulk[numValues] = new ContentValues(numColumns);
} else {
// Reuse values objects
valueBulk[numValues].clear();
}
// Read the fields bitmap
long fields = reader.readLong();
for (int c = 0; c < numColumns; c++) {
if ((fields & 1) == 1) {
// Field is present, read into values
readOneCell(columnNames[c], columnTypes[c], valueBulk[numValues],
reader);
} else if (readNullFields) {
// Field not present but still written, read and discard
readOneCell(columnNames[c], columnTypes[c], null, reader);
}
fields >>= 1;
}
numValues++;
// If we have enough values, flush them as a bulk insertion
if (numValues >= bulkSize) {
doBulkInsert(valueBulk);
numValues = 0;
}
}
// Do a final bulk insert with the leftovers
if (numValues > 0) {
ContentValues[] leftovers = new ContentValues[numValues];
System.arraycopy(valueBulk, 0, leftovers, 0, numValues);
doBulkInsert(leftovers);
}
}
protected void doBulkInsert(ContentValues[] values) {
resolver.bulkInsert(destinationUri, values);
}
/**
* Reads a single cell from the reader.
*
* @param name the name of the column to be read
* @param typeId the type ID of the column to be read
* @param values the {@link ContentValues} object to put the read cell value
* in - if null, the value is just discarded
* @throws IOException if there are any problems while reading
*/
private void readOneCell(String name, byte typeId, ContentValues values,
DataInputStream reader) throws IOException {
switch (typeId) {
case ContentTypeIds.BOOLEAN_TYPE_ID: {
boolean value = reader.readBoolean();
if (values != null) { values.put(name, value); }
return;
}
case ContentTypeIds.LONG_TYPE_ID: {
long value = reader.readLong();
if (values != null) { values.put(name, value); }
return;
}
case ContentTypeIds.DOUBLE_TYPE_ID: {
double value = reader.readDouble();
if (values != null) { values.put(name, value); }
return;
}
case ContentTypeIds.FLOAT_TYPE_ID: {
Float value = reader.readFloat();
if (values != null) { values.put(name, value); }
return;
}
case ContentTypeIds.INT_TYPE_ID: {
int value = reader.readInt();
if (values != null) { values.put(name, value); }
return;
}
case ContentTypeIds.STRING_TYPE_ID: {
String value = reader.readUTF();
if (values != null) { values.put(name, value); }
return;
}
case ContentTypeIds.BLOB_TYPE_ID: {
int blobLength = reader.readInt();
if (blobLength != 0) {
byte[] blob = new byte[blobLength];
int readBytes = reader.read(blob, 0, blobLength);
if (readBytes != blobLength) {
throw new IOException(String.format(
"Short read on column %s; expected %d bytes, read %d",
name, blobLength, readBytes));
}
if (values != null) {
values.put(name, blob);
}
}
return;
}
default:
throw new IOException("Read unknown type " + typeId);
}
}
}
| 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.backup;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.MyTracksSettings;
import android.app.backup.BackupAgent;
import android.app.backup.BackupDataInput;
import android.app.backup.BackupDataOutput;
import android.content.SharedPreferences;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.IOException;
/**
* Backup agent used to backup and restore all preferences.
* We use a regular {@link BackupAgent} instead of the convenient helpers in
* order to be future-proof (assuming we'll want to back up tracks later).
*
* @author Rodrigo Damazio
*/
public class MyTracksBackupAgent extends BackupAgent {
private static final String PREFERENCES_ENTITY = "prefs";
@Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
ParcelFileDescriptor newState) throws IOException {
Log.i(MyTracksConstants.TAG, "Performing backup");
SharedPreferences preferences = this.getSharedPreferences(
MyTracksSettings.SETTINGS_NAME, 0);
backupPreferences(data, preferences);
Log.i(MyTracksConstants.TAG, "Backup complete");
}
private void backupPreferences(BackupDataOutput data,
SharedPreferences preferences) throws IOException {
PreferenceBackupHelper preferenceDumper = createPreferenceBackupHelper();
byte[] dumpedContents = preferenceDumper.exportPreferences(preferences);
data.writeEntityHeader(PREFERENCES_ENTITY, dumpedContents.length);
data.writeEntityData(dumpedContents, dumpedContents.length);
}
protected PreferenceBackupHelper createPreferenceBackupHelper() {
return new PreferenceBackupHelper();
}
@Override
public void onRestore(BackupDataInput data, int appVersionCode,
ParcelFileDescriptor newState) throws IOException {
Log.i(MyTracksConstants.TAG, "Restoring from backup");
while (data.readNextHeader()) {
String key = data.getKey();
Log.d(MyTracksConstants.TAG, "Restoring entity " + key);
if (key.equals(PREFERENCES_ENTITY)) {
restorePreferences(data);
} else {
Log.e(MyTracksConstants.TAG, "Found unknown backup entity: " + key);
data.skipEntityData();
}
}
Log.i(MyTracksConstants.TAG, "Done restoring from backup");
}
/**
* Restores all preferences from the backup.
*
* @param data the backup data to read from
* @throws IOException if there are any errors while reading
*/
private void restorePreferences(BackupDataInput data) throws IOException {
int dataSize = data.getDataSize();
byte[] dataBuffer = new byte[dataSize];
int read = data.readEntityData(dataBuffer, 0, dataSize);
if (read != dataSize) {
throw new IOException("Failed to read all the preferences data");
}
SharedPreferences preferences = this.getSharedPreferences(
MyTracksSettings.SETTINGS_NAME, 0);
PreferenceBackupHelper importer = createPreferenceBackupHelper();
importer.importPreferences(dataBuffer, preferences);
}
}
| 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.backup;
import com.google.android.apps.mytracks.util.ApiFeatures;
import android.app.backup.BackupManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
/**
* Shared preferences listener which notifies the backup system about new data
* being available for backup.
* This class is API-version-safe and will provide a dummy implementation if
* the device doesn't support backup services.
*
* @author Rodrigo Damazio
*/
public abstract class BackupPreferencesListener
implements OnSharedPreferenceChangeListener {
/**
* Real implementation of the listener, which calls the {@link BackupManager}.
*/
private static class BackupPreferencesListenerImpl
extends BackupPreferencesListener {
private final BackupManager backupManager;
public BackupPreferencesListenerImpl(Context context) {
this.backupManager = new BackupManager(context);
}
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
backupManager.dataChanged();
}
}
/**
* Dummy implementation of the listener which does nothing.
*/
private static class DummyBackupPreferencesListener
extends BackupPreferencesListener {
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
// Do nothing
}
}
/**
* Creates and returns a proper instance of the listener for this device.
*/
public static BackupPreferencesListener create(
Context context, ApiFeatures apiFeatures) {
if (apiFeatures.hasBackup()) {
return new BackupPreferencesListenerImpl(context);
} else {
return new DummyBackupPreferencesListener();
}
}
} | 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;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import android.content.Context;
/**
* 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();
}
};
/**
* 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);
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 TrackWriter(context, providerUtils, track, writer);
}
private TrackWriterFactory() { }
}
| 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;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.content.MyTracksLocation;
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.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.util.FileUtils;
import com.google.android.apps.mytracks.util.MyTracksUtils;
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;
/**
* The class which exports tracks to the SD card.
* This writer is 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 class TrackWriter {
private final Context context;
private final MyTracksProviderUtils providerUtils;
private final Track track;
private final TrackFormatWriter writer;
private final FileUtils fileUtils;
private Runnable onCompletion = null;
private boolean success = false;
private int errorMessage = -1;
private File directory = null;
private File file = null;
public TrackWriter(Context context, MyTracksProviderUtils providerUtils,
Track track, TrackFormatWriter writer) {
this.context = context;
this.providerUtils = providerUtils;
this.track = track;
this.writer = writer;
this.fileUtils = new FileUtils();
}
/**
* Sets a completion callback.
*
* @param onCompletion Runnable that will be executed when finished
*/
public void setOnCompletion(Runnable onCompletion) {
this.onCompletion = onCompletion;
}
/**
* Sets a custom directory where the file will be written.
*/
public void setDirectory(File directory) {
this.directory = directory;
}
public String getAbsolutePath() {
return file.getAbsolutePath();
}
/**
* Writes the given track id to the SD card.
* This is non-blocking.
*/
public void writeTrackAsync() {
Thread t = new Thread() {
@Override
public void run() {
writeTrack();
}
};
t.start();
}
/**
* Writes the given track id to the SD card.
* This is blocking.
*/
public void writeTrack() {
// Open the input and output
success = false;
errorMessage = R.string.error_track_does_not_exist;
if (track != null) {
if (openFile()) {
writeDocument();
}
}
finished();
}
public int getErrorMessage() {
return errorMessage;
}
public boolean wasSuccess() {
return success;
}
/*
* Helper methods:
* ===============
*/
private void finished() {
if (onCompletion != null) {
runOnUiThread(onCompletion);
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(MyTracksConstants.TAG,
"Unable to get a unique filename for " + fileName);
return false;
}
Log.i(MyTracksConstants.TAG, "Writing track to: " + fileName);
try {
writer.prepare(track, newOutputStream(fileName));
} catch (FileNotFoundException e) {
Log.e(MyTracksConstants.TAG, "Failed to open output file.", e);
errorMessage = R.string.io_write_failed;
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(MyTracksConstants.TAG, "Could not find SD card.");
errorMessage = R.string.io_no_external_storage_found;
return false;
}
if (!fileUtils.ensureDirectoryExists(directory)) {
Log.i(MyTracksConstants.TAG, "Could not create export directory.");
errorMessage = R.string.io_create_dir_failed;
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,
MyTracksConstants.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 {
if (cursor != null) {
cursor.close();
}
}
}
}
/**
* Does the actual work of writing the track to the now open file.
*/
void writeDocument() {
Log.d(MyTracksConstants.TAG, "Started writing track.");
writer.writeHeader();
writeWaypoints(track.getId());
writeLocations();
writer.writeFooter();
writer.close();
success = true;
Log.d(MyTracksConstants.TAG, "Done writing track.");
errorMessage = R.string.io_write_finished;
}
private void writeLocations() {
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(MyTracksConstants.TAG, "Unable to get any points to write");
return;
}
while (it.hasNext()) {
Location loc = it.next();
boolean isValid = MyTracksUtils.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);
} 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;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.io.TrackWriterFactory.TrackFileFormat;
import android.location.Location;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* 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 {
static final NumberFormat SHORT_FORMAT = NumberFormat.getInstance();
static final SimpleDateFormat TIMESTAMP_FORMAT =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
static {
SHORT_FORMAT.setMaximumFractionDigits(4);
TIMESTAMP_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
private int segmentIdx = 0;
private int numFields = -1;
private PrintWriter pw;
private Track track;
@Override
public String getExtension() {
return TrackFileFormat.CSV.getExtension();
}
@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 = 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 = 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 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;
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 extentsion (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);
/**
* 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 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;
import com.google.android.apps.mytracks.MyTracksConstants;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
/**
* A factory for getting the platform specific AuthManager.
*
* @author Sandor Dornbush
*/
public class AuthManagerFactory {
private AuthManagerFactory() {
}
/**
* Returns whether the modern AuthManager should be used
*/
public static boolean useModernAuthManager() {
return Integer.parseInt(Build.VERSION.SDK) >= 7;
}
/**
* Get a right {@link AuthManager} for the platform.
* @return A new AuthManager
*/
public static AuthManager getAuthManager(Activity activity, int code,
Bundle extras, boolean requireGoogle, String service) {
if (useModernAuthManager()) {
Log.i(MyTracksConstants.TAG,
"Creating modern auth manager: " + service);
return new ModernAuthManager(activity, code, extras, requireGoogle, service);
} else {
Log.i(MyTracksConstants.TAG,
"Creating legacy auth manager: " + service);
return new AuthManagerOld(activity, code, extras, requireGoogle, service);
}
}
}
| 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;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.MyTracksSettings;
import com.google.android.apps.mytracks.ProgressIndicator;
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.gdata.GDataWrapper;
import com.google.android.apps.mytracks.io.gdata.GDataWrapper.QueryFunction;
import com.google.android.apps.mytracks.stats.DoubleBuffer;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.MyTracksUtils;
import com.google.android.apps.mytracks.util.StringUtils;
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.MethodOverrideIntercepter;
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.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.javanet.NetHttpTransport;
import com.google.api.client.util.Strings;
import android.app.Activity;
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.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
/**
* A helper class used to transmit tracks to Google Fusion Tables.
* A new instance should be used for each upload.
*
* @author Leif Hendrik Wilden
*/
public class SendToFusionTables implements Runnable {
/**
* Listener invoked when sending to fusion tables completes.
*/
public interface OnSendCompletedListener {
void onSendCompleted(String tableId, boolean success, int statusMessage);
}
/** The GData service id for Fusion Tables. */
public static final String SERVICE_ID = "fusiontables";
/** The path for viewing a map visualization of a table. */
private static final String FUSIONTABLES_MAP =
"http://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";
/** Standard base feed url for Fusion Tables. */
private static final String FUSIONTABLES_BASE_FEED_URL =
"http://www.google.com/fusiontables/api/query";
private static final int MAX_POINTS_PER_UPLOAD = 2048;
private static final String GDATA_VERSION = "2";
// This class reports upload status to the user as a completion percentage
// using a progress bar. Progress is defined as follows:
//
// 0% Getting track metadata
// 5% Creating Fusion Table (GData to FT server)
// 10%-90% Uploading the track data to Fusion Tables
// 95% Uploading waypoints
// 100% Done
private static final int PROGRESS_INITIALIZATION = 0;
private static final int PROGRESS_FUSION_TABLE_CREATE = 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;
private final Activity context;
private final AuthManager auth;
private final long trackId;
private final ProgressIndicator progressIndicator;
private final OnSendCompletedListener onCompletion;
private final StringUtils stringUtils;
private final MyTracksProviderUtils providerUtils;
// Progress status
private int totalLocationsRead;
private int totalLocationsPrepared;
private int totalLocationsUploaded;
private int totalLocations;
private int totalSegmentsUploaded;
private HttpTransport transport;
private String tableId;
private static String MARKER_TYPE_START = "large_green";
private static String MARKER_TYPE_END = "large_red";
private static String MARKER_TYPE_WAYPOINT = "large_yellow";
static {
// We manually assign the transport to avoid having HttpTransport try to
// load it via reflection (which breaks due to ProGuard).
HttpTransport.setLowLevelHttpTransport(new NetHttpTransport());
}
public SendToFusionTables(Activity context, AuthManager auth,
long trackId, ProgressIndicator progressIndicator,
OnSendCompletedListener onCompletion) {
this.context = context;
this.auth = auth;
this.trackId = trackId;
this.progressIndicator = progressIndicator;
this.onCompletion = onCompletion;
this.stringUtils = new StringUtils(context);
this.providerUtils = MyTracksProviderUtils.Factory.get(context);
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-MyTracks-" + MyTracksUtils.getMyTracksVersion(context));
headers.gdataVersion = GDATA_VERSION;
transport = new HttpTransport();
MethodOverrideIntercepter.setAsFirstFor(transport);
transport.defaultHeaders = headers;
}
@Override
public void run() {
Log.d(MyTracksConstants.TAG, "Sending to Fusion tables: trackId = " + trackId);
doUpload();
}
public static String getMapVisualizationUrl(Track track) {
// TODO(leifhendrik): Determine 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, FUSIONTABLES_MAP, track.getTableId(),
latE6 / 1.E6, lonE6 / 1.E6, z);
}
private void doUpload() {
((GoogleHeaders) transport.defaultHeaders).setGoogleLogin(auth.getAuthToken());
int statusMessageId = R.string.error_sending_to_fusiontables;
boolean success = true;
try {
progressIndicator.setProgressValue(PROGRESS_INITIALIZATION);
progressIndicator.setProgressMessage(R.string.progress_message_reading_track);
// Get the track meta-data
Track track = providerUtils.getTrack(trackId);
String originalDescription = track.getDescription();
// Create a new table:
progressIndicator.setProgressValue(PROGRESS_FUSION_TABLE_CREATE);
progressIndicator.setProgressMessage(R.string.progress_message_creating_fusiontable);
if (!createNewTable(track) || !makeTableUnlisted(tableId)) {
return;
}
progressIndicator.setProgressValue(PROGRESS_UPLOAD_DATA_MIN);
progressIndicator.setProgressMessage(R.string.progress_message_sending_fusiontables);
// Upload all of the segments of the track plus start/end markers
if (!uploadAllTrackPoints(track, originalDescription)) {
return;
}
progressIndicator.setProgressValue(PROGRESS_UPLOAD_WAYPOINTS);
// Upload all the waypoints.
if (!uploadWaypoints(track)) {
return;
}
statusMessageId = R.string.status_new_fusiontable_has_been_created;
Log.d(MyTracksConstants.TAG, "SendToFusionTables: Done: " + success);
progressIndicator.setProgressValue(PROGRESS_COMPLETE);
} finally {
final boolean finalSuccess = success;
final int finalStatusMessageId = statusMessageId;
context.runOnUiThread(new Runnable() {
public void run() {
if (onCompletion != null) {
onCompletion.onSendCompleted(
tableId, finalSuccess, finalStatusMessageId);
}
}
});
}
}
/**
* Creates a new table.
* If successful sets {@link #tableId}.
*
* @return true in case of success.
*/
private boolean createNewTable(Track track) {
Log.d(MyTracksConstants.TAG, "Creating a new fusion table.");
String query = "CREATE TABLE '" + sqlEscape(track.getName()) +
"' (name:STRING,description:STRING,geometry:LOCATION,marker:STRING)";
return runUpdate(query);
}
private boolean makeTableUnlisted(String tableId) {
Log.d(MyTracksConstants.TAG, "Setting visibility to unlisted.");
String query = "UPDATE TABLE " + tableId + " SET VISIBILITY = UNLISTED";
return runUpdate(query);
}
/**
* Formats given values SQL style. Escapes single quotes with a backslash.
*
* @param values the values to format
* @return the values formatted as: ('value1','value2',...,'value_n').
*/
private static String values(String... values) {
StringBuilder builder = new StringBuilder("(");
for (int i = 0; i < values.length; i++) {
if (i > 0) {
builder.append(',');
}
builder.append('\'');
builder.append(sqlEscape(values[i]));
builder.append('\'');
}
builder.append(')');
return builder.toString();
}
private static String sqlEscape(String value) {
return value.replaceAll("'", "''");
}
/**
* Creates a new row representing a marker.
*
* @param name the marker name
* @param description the marker description
* @param the marker location
* @return true in case of success.
*/
private boolean createNewPoint(String name, String description, Location location,
String marker) {
Log.d(MyTracksConstants.TAG, "Creating a new row with a point.");
String query = "INSERT INTO " + tableId + " (name,description,geometry,marker) VALUES "
+ values(name, description, getKmlPoint(location), marker);
return runUpdate(query);
}
/**
* Creates a new row representing a line segment.
*
* @param track the track/segment to draw
* @return true in case of success.
*/
private boolean createNewLineString(Track track) {
Log.d(MyTracksConstants.TAG, "Creating a new row with a point.");
String query = "INSERT INTO " + tableId
+ " (name,description,geometry) VALUES "
+ values(track.getName(), track.getDescription(), getKmlLineString(track));
return runUpdate(query);
}
private boolean uploadAllTrackPoints(final Track track, String originalDescription) {
SharedPreferences preferences = context.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0);
boolean metricUnits = true;
if (preferences != null) {
metricUnits = preferences.getBoolean(context.getString(R.string.metric_units_key), true);
}
Cursor locationsCursor = providerUtils.getLocationsCursor(track.getId(), 0, -1, false);
try {
if (!locationsCursor.moveToFirst()) {
Log.w(MyTracksConstants.TAG, "Unable to get any points to upload");
return false;
}
totalLocationsRead = 0;
totalLocationsPrepared = 0;
totalLocationsUploaded = 0;
totalLocations = locationsCursor.getCount();
totalSegmentsUploaded = 0;
// Limit the number of elevation readings. Ideally we would want around 250.
int elevationSamplingFrequency =
Math.max(1, (int) (totalLocations / 250.0));
Log.d(MyTracksConstants.TAG,
"Using elevation sampling factor: " + elevationSamplingFrequency
+ " on " + totalLocations);
double totalDistance = 0;
Vector<Double> distances = new Vector<Double>();
Vector<Double> elevations = new Vector<Double>();
DoubleBuffer elevationBuffer = new DoubleBuffer(MyTracksConstants.ELEVATION_SMOOTHING_FACTOR);
List<Location> locations = new ArrayList<Location>(MAX_POINTS_PER_UPLOAD);
Location lastLocation = null;
do {
if (totalLocationsRead % 100 == 0) {
updateTrackDataUploadProgress();
}
Location loc = providerUtils.createLocation(locationsCursor);
locations.add(loc);
if (totalLocationsRead == 0) {
// Put a marker at the first point of the first valid segment:
String name = track.getName() + " " + context.getString(R.string.start);
createNewPoint(name, "", loc, MARKER_TYPE_START);
}
// Add to the elevation profile.
if (loc != null && MyTracksUtils.isValidLocation(loc)) {
// All points go into the smoothing buffer...
elevationBuffer.setNext(metricUnits ? loc.getAltitude()
: loc.getAltitude() * UnitConversions.M_TO_FT);
if (lastLocation != null) {
double dist = lastLocation.distanceTo(loc);
totalDistance += dist;
}
// ...but only a few points are really used to keep the url short.
if (totalLocationsRead % elevationSamplingFrequency == 0) {
distances.add(totalDistance);
elevations.add(elevationBuffer.getAverage());
}
}
// If the location was not valid, it's a segment split, so make sure the
// distance between the previous segment and the new one is not accounted
// for in the next iteration.
lastLocation = loc;
// Every now and then, upload the accumulated points
if (totalLocationsRead % MAX_POINTS_PER_UPLOAD == MAX_POINTS_PER_UPLOAD - 1) {
if (!prepareAndUploadPoints(track, locations)) {
return false;
}
}
totalLocationsRead++;
} while (locationsCursor.moveToNext());
// Do a final upload with what's left
if (!prepareAndUploadPoints(track, locations)) {
return false;
}
// Put an end marker at the last point of the last valid segment:
if (lastLocation != null) {
track.setDescription("<p>" + originalDescription + "</p><p>"
+ stringUtils.generateTrackDescription(track, distances, elevations)
+ "</p>");
String name = track.getName() + " " + context.getString(R.string.end);
return createNewPoint(name, track.getDescription(), lastLocation, MARKER_TYPE_END);
}
return true;
} finally {
locationsCursor.close();
}
}
/**
* Appends the given location to the string in the format:
* longitude,latitude[,altitude]
*
* @param location the location to be added
* @param builder the string builder to use
*/
private void appendCoordinate(Location location, StringBuilder builder) {
builder
.append(location.getLongitude())
.append(",")
.append(location.getLatitude());
if (location.hasAltitude()) {
builder.append(",");
builder.append(location.getAltitude());
}
}
/**
* Gets a KML Point tag for the given location.
*
* @param location The location.
* @return the kml.
*/
private String getKmlPoint(Location location) {
StringBuilder builder = new StringBuilder("<Point><coordinates>");
appendCoordinate(location, builder);
builder.append("</coordinates></Point>");
return builder.toString();
}
/**
* Returns a KML Point tag for the given location.
*
* @param location The location.
* @return the kml.
*/
private String getKmlLineString(Track track) {
StringBuilder builder = new StringBuilder("<LineString><coordinates>");
for (Location location : track.getLocations()) {
appendCoordinate(location, builder);
builder.append(' ');
}
builder.append("</coordinates></LineString>");
return builder.toString();
}
private boolean prepareAndUploadPoints(Track track, List<Location> locations) {
updateTrackDataUploadProgress();
int numLocations = locations.size();
if (numLocations < 2) {
Log.d(MyTracksConstants.TAG, "Not preparing/uploading too few points");
totalLocationsUploaded += numLocations;
return true;
}
// Prepare/pre-process the points
ArrayList<Track> splitTracks = prepareLocations(track, locations);
// Start uploading them
for (Track splitTrack : splitTracks) {
if (totalSegmentsUploaded > 1) {
splitTrack.setName(splitTrack.getName() + " "
+ String.format(
context.getString(R.string.part), totalSegmentsUploaded));
}
totalSegmentsUploaded++;
Log.d(MyTracksConstants.TAG,
"SendToFusionTables: Prepared feature for upload w/ "
+ splitTrack.getLocations().size() + " points.");
// Transmit tracks via GData feed:
// -------------------------------
Log.d(MyTracksConstants.TAG,
"SendToFusionTables: Uploading to table " + tableId + " w/ auth " + auth);
if (!uploadTrackPoints(splitTrack)) {
Log.e(MyTracksConstants.TAG, "Uploading failed");
return false;
}
}
locations.clear();
totalLocationsUploaded += numLocations;
updateTrackDataUploadProgress();
return true;
}
/**
* Prepares a buffer of locations for transmission to google fusion tables.
*
* @param track the original track with meta data
* @param buffer a buffer of locations on the track
* @return an array of tracks each with a sub section of the points in the
* original buffer
*/
private ArrayList<Track> prepareLocations(
Track track, Iterable<Location> locations) {
ArrayList<Track> splitTracks = new ArrayList<Track>();
// Create segments from each full track:
Track segment = new Track();
TripStatistics segmentStats = segment.getStatistics();
TripStatistics trackStats = track.getStatistics();
segment.setId(track.getId());
segment.setName(track.getName());
segment.setDescription(/* track.getDescription() */ "");
segment.setCategory(track.getCategory());
segmentStats.setStartTime(trackStats.getStartTime());
segmentStats.setStopTime(trackStats.getStopTime());
boolean startNewTrackSegment = false;
for (Location loc : locations) {
if (totalLocationsPrepared % 100 == 0) {
updateTrackDataUploadProgress();
}
if (loc.getLatitude() > 90) {
startNewTrackSegment = true;
}
if (startNewTrackSegment) {
// Close up the last segment.
prepareTrackSegment(segment, splitTracks);
Log.d(MyTracksConstants.TAG,
"MyTracksSendToFusionTables: Starting new track segment...");
startNewTrackSegment = false;
segment = new Track();
segment.setId(track.getId());
segment.setName(track.getName());
segment.setDescription(/* track.getDescription() */ "");
segment.setCategory(track.getCategory());
}
if (loc.getLatitude() <= 90) {
segment.addLocation(loc);
if (segmentStats.getStartTime() < 0) {
segmentStats.setStartTime(loc.getTime());
}
}
totalLocationsPrepared++;
}
prepareTrackSegment(segment, splitTracks);
return splitTracks;
}
/**
* Prepares a track segment for sending to google fusion tables.
* The main steps are:
* - correcting end time
* - decimating locations
* - splitting into smaller tracks.
*
* The final track pieces will be put in the array list splitTracks.
*
* @param segment the original segment of the track
* @param splitTracks an array of smaller track segments
*/
private void prepareTrackSegment(
Track segment, ArrayList<Track> splitTracks) {
TripStatistics segmentStats = segment.getStatistics();
if (segmentStats.getStopTime() < 0
&& segment.getLocations().size() > 0) {
segmentStats.setStopTime(segment.getLocations().size() - 1);
}
/*
* Decimate to 2 meter precision. Fusion tables doesn't like too many
* points:
*/
MyTracksUtils.decimate(segment, 2.0);
/* If the track still has > 2500 points, split it in pieces: */
final int maxPoints = 2500;
if (segment.getLocations().size() > maxPoints) {
splitTracks.addAll(MyTracksUtils.split(segment, maxPoints));
} else if (segment.getLocations().size() >= 2) {
splitTracks.add(segment);
}
}
private boolean uploadTrackPoints(Track splitTrack) {
int numLocations = splitTrack.getLocations().size();
if (numLocations < 2) {
// Need at least two points for a polyline:
Log.w(MyTracksConstants.TAG, "Not uploading too few points");
return true;
}
return createNewLineString(splitTrack);
}
/**
* Uploads all of the waypoints associated with this track to a table.
*
* @param track The track to upload waypoints for.
*
* @return True on success.
*/
private boolean uploadWaypoints(final Track track) {
// TODO: Stream through the 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.
boolean success = true;
Cursor c = null;
try {
c = providerUtils.getWaypointsCursor(
track.getId(), 0,
MyTracksConstants.MAX_LOADED_WAYPOINTS_POINTS);
if (c != null) {
if (c.moveToFirst()) {
// This will skip the 1st waypoint (it carries the stats for the
// last segment).
while (c.moveToNext()) {
Waypoint wpt = providerUtils.createWaypoint(c);
Log.d(MyTracksConstants.TAG, "SendToFusionTables: Creating waypoint.");
success = createNewPoint(wpt.getName(), wpt.getDescription(), wpt.getLocation(),
MARKER_TYPE_WAYPOINT);
if (!success) {
break;
}
}
}
}
if (!success) {
Log.w(MyTracksConstants.TAG, "SendToFusionTables: upload waypoints failed.");
}
return success;
} finally {
if (c != null) {
c.close();
}
}
}
private void updateTrackDataUploadProgress() {
// The percent of the total that represents the completed part of this
// segment. We calculate it as an absolute percentage, and then scale it
// to fit the completion percentage range alloted to track data upload.
double totalPercentage =
(totalLocationsRead + totalLocationsPrepared + totalLocationsUploaded)
/ (totalLocations * 3);
double scaledPercentage = totalPercentage
* (PROGRESS_UPLOAD_DATA_MAX - PROGRESS_UPLOAD_DATA_MIN) + PROGRESS_UPLOAD_DATA_MIN;
progressIndicator.setProgressValue((int) scaledPercentage);
}
/**
* Runs an update query. Handles authentication.
*
* @param query The given SQL like query
* @return true in case of success
*/
private boolean runUpdate(final String query) {
GDataWrapper<HttpTransport> wrapper = new GDataWrapper<HttpTransport>();
wrapper.setAuthManager(auth);
wrapper.setRetryOnAuthFailure(true);
wrapper.setClient(transport);
Log.d(MyTracksConstants.TAG, "GData connection prepared: " + this.auth);
wrapper.runQuery(new QueryFunction<HttpTransport>() {
@Override
public void query(HttpTransport client)
throws IOException, GDataWrapper.ParseException, GDataWrapper.HttpException,
GDataWrapper.AuthenticationException {
HttpRequest request = transport.buildPostRequest();
request.headers.contentType = "application/x-www-form-urlencoded";
GenericUrl url = new GenericUrl(FUSIONTABLES_BASE_FEED_URL);
request.url = url;
InputStreamContent isc = new InputStreamContent();
String sql = "sql=" + URLEncoder.encode(query, "UTF-8");
isc.inputStream = new ByteArrayInputStream(Strings.toBytesUtf8(sql));
request.content = isc;
Log.d(MyTracksConstants.TAG, "Running update query " + url.toString() + ": " + sql);
HttpResponse response;
try {
response = request.execute();
} catch (HttpResponseException e) {
throw new GDataWrapper.HttpException(e.response.statusCode, e.response.statusMessage);
}
boolean success = response.isSuccessStatusCode;
if (success) {
byte[] result = new byte[1024];
response.getContent().read(result);
String s = Strings.fromBytesUtf8(result);
String[] lines = s.split(Strings.LINE_SEPARATOR);
if (lines[0].equals("tableid")) {
tableId = lines[1];
Log.d(MyTracksConstants.TAG, "tableId = " + tableId);
} else {
Log.w(MyTracksConstants.TAG, "Unrecognized response: " + lines[0]);
}
} else {
Log.d(MyTracksConstants.TAG, "Query failed: " + response.statusMessage + " (" +
response.statusCode + ")");
throw new GDataWrapper.HttpException(response.statusCode, response.statusMessage);
}
}
});
return wrapper.getErrorType() == GDataWrapper.ERROR_NO_ERROR;
}
}
| 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;
import com.google.android.accounts.Account;
import com.google.android.accounts.AccountManager;
import com.google.android.accounts.AccountManagerCallback;
import com.google.android.accounts.AccountManagerFuture;
import com.google.android.accounts.AuthenticatorException;
import com.google.android.accounts.OperationCanceledException;
import com.google.android.apps.mytracks.AccountChooser;
import com.google.android.apps.mytracks.MyTracks;
import com.google.android.apps.mytracks.MyTracksConstants;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
/**
* AuthManager keeps track of the current auth token for a user. The advantage
* over just passing around a String is that this class can renew the auth
* token if necessary, and it will change for all classes using this
* AuthManager.
*/
public class ModernAuthManager implements AuthManager {
/** The activity that will handle auth result callbacks. */
private final Activity activity;
/** The name of the service to authorize for. */
private final String service;
/** The most recently fetched auth token or null if none is available. */
private String authToken;
private final AccountManager accountManager;
private Runnable whenFinished;
/**
* AuthManager requires many of the same parameters as
* {@link com.google.android.googlelogindist.GoogleLoginServiceHelper
* #getCredentials(Activity, int, Bundle, boolean, String, boolean)}.
* The activity must have a handler in {@link Activity#onActivityResult} that
* calls {@link #authResult(int, Intent)} if the request code is the code
* given here.
*
* @param activity An activity with a handler in
* {@link Activity#onActivityResult} that calls
* {@link #authResult(int, Intent)} when {@literal code} is the request
* code
* @param code The request code to pass to
* {@link Activity#onActivityResult} when
* {@link #authResult(int, Intent)} should be called
* @param extras A {@link Bundle} of extras for
* {@link com.google.android.googlelogindist.GoogleLoginServiceHelper}
* @param requireGoogle True if the account must be a Google account
* @param service The name of the service to authenticate as
*/
public ModernAuthManager(Activity activity, int code, Bundle extras,
boolean requireGoogle, String service) {
this.activity = activity;
this.service = service;
this.accountManager = AccountManager.get(activity);
}
/**
* Call this to do the initial login. The user will be asked to login if
* they haven't already. The {@link Runnable} provided will be executed
* when the auth token is successfully fetched.
*
* @param runnable A {@link Runnable} to execute when the auth token
* has been successfully fetched and is available via
* {@link #getAuthToken()}
*/
public void doLogin(final Runnable runnable, Object o) {
this.whenFinished = runnable;
if (!(o instanceof Account)) {
throw new IllegalArgumentException("FroyoAuthManager requires an account.");
}
Account account = (Account) o;
accountManager.getAuthToken(account, service, true,
new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle result = future.getResult();
// AccountManager needs user to grant permission
if (result.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = (Intent) result.get(AccountManager.KEY_INTENT);
clearNewTaskFlag(intent);
activity.startActivityForResult(intent, MyTracksConstants.GET_LOGIN);
return;
}
authToken = result.getString(
AccountManager.KEY_AUTHTOKEN);
Log.e(MyTracksConstants.TAG, "Got auth token.");
runWhenFinished();
} catch (OperationCanceledException e) {
Log.e(MyTracksConstants.TAG, "Operation Canceled", e);
} catch (IOException e) {
Log.e(MyTracksConstants.TAG, "IOException", e);
} catch (AuthenticatorException e) {
Log.e(MyTracksConstants.TAG, "Authentication Failed", e);
}
}
}, null /* handler */);
}
private static void clearNewTaskFlag(Intent intent) {
int flags = intent.getFlags();
flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
intent.setFlags(flags);
}
/**
* The {@link Activity} passed into the constructor should call this
* function when it gets {@link Activity#onActivityResult} with the request
* code passed into the constructor. The resultCode and results should
* come directly from the {@link Activity#onActivityResult} function. This
* function will return true if an auth token was successfully fetched or
* the process is not finished.
*
* @param resultCode The result code passed in to the {@link Activity}'s
* {@link Activity#onActivityResult} function
* @param results The data passed in to the {@link Activity}'s
* {@link Activity#onActivityResult} function
* @return True if the auth token was fetched or we aren't done fetching
* the auth token, or False if there was an error or the request was
* canceled
*/
public boolean authResult(int resultCode, Intent results) {
if (results != null) {
authToken = results.getStringExtra(
AccountManager.KEY_AUTHTOKEN);
Log.w(MyTracksConstants.TAG, "authResult: " + authToken);
} else {
Log.e(MyTracksConstants.TAG, "No auth result results!!");
}
runWhenFinished();
return authToken != null;
}
/**
* Returns the current auth token. Response may be null if no valid auth
* token has been fetched.
*
* @return The current auth token or null if no auth token has been
* fetched
*/
public String getAuthToken() {
return authToken;
}
/**
* Invalidates the existing auth token and request a new one. The
* {@link Runnable} provided will be executed when the new auth token is
* successfully fetched.
*
* @param runnable A {@link Runnable} to execute when a new auth token
* is successfully fetched
*/
public void invalidateAndRefresh(final Runnable runnable) {
this.whenFinished = runnable;
activity.runOnUiThread(new Runnable() {
public void run() {
accountManager.invalidateAuthToken(MyTracksConstants.ACCOUNT_TYPE,
authToken);
MyTracks.getInstance().getAccountChooser().chooseAccount(activity,
new AccountChooser.AccountHandler() {
@Override
public void handleAccountSelected(Account account) {
if (account != null) {
doLogin(whenFinished, account);
} else {
runWhenFinished();
}
}
});
}
});
}
private void runWhenFinished() {
if (whenFinished != null) {
(new Thread() {
@Override
public void run() {
whenFinished.run();
}
}).start();
}
}
}
| 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;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.io.TrackWriterFactory.TrackFileFormat;
import com.google.android.apps.mytracks.util.StringUtils;
import android.content.Context;
import android.location.Location;
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 StringUtils stringUtils;
private PrintWriter pw = null;
private Track track;
public KmlTrackWriter(Context context) {
stringUtils = new StringUtils(context);
}
/**
* Testing constructor.
*/
KmlTrackWriter(StringUtils stringUtils) {
this.stringUtils = stringUtils;
}
@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.println("<atom:author><atom:name>My Tracks running on Android"
+ "</atom:name></atom:author>");
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 = stringUtils.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 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;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.MyTracksSettings;
import com.google.android.apps.mytracks.ProgressIndicator;
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.mymaps.MapsFacade;
import com.google.android.apps.mytracks.io.mymaps.MapsFacade.WaypointData;
import com.google.android.apps.mytracks.stats.DoubleBuffer;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.MyTracksUtils;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.location.Location;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* A helper class used to transmit tracks to Google MyMaps.
* A new instance should be used for each upload.
*
* IMPORTANT: while this code is Apache-licensed, please notice that usage of
* the Google Maps servers through this API is only allowed for the My Tracks
* application. Other applications looking to upload maps data should look
* into using the Fusion Tables API.
*
* @author Leif Hendrik Wilden
*/
public class SendToMyMaps implements Runnable {
public static final String NEW_MAP_ID = "new";
private static final int MAX_POINTS_PER_UPLOAD = 2048;
private final Activity context;
private final AuthManager auth;
private final long trackId;
private final ProgressIndicator progressIndicator;
private final OnSendCompletedListener onCompletion;
private final StringUtils stringUtils;
private final MyTracksProviderUtils providerUtils;
private String mapId;
private MapsFacade mapsClient;
// Progress status
private int totalLocationsRead;
private int totalLocationsPrepared;
private int totalLocationsUploaded;
private int totalLocations;
private int totalSegmentsUploaded;
public interface OnSendCompletedListener {
void onSendCompleted(String mapId, boolean success, int statusMessage);
}
public SendToMyMaps(Activity context, String mapId, AuthManager auth,
long trackId, ProgressIndicator progressIndicator,
OnSendCompletedListener onCompletion) {
this.context = context;
this.mapId = mapId;
this.auth = auth;
this.trackId = trackId;
this.progressIndicator = progressIndicator;
this.onCompletion = onCompletion;
this.stringUtils = new StringUtils(context);
this.providerUtils = MyTracksProviderUtils.Factory.get(context);
}
@Override
public void run() {
Log.d(MyTracksConstants.TAG, "Sending to MyMaps: trackId = " + trackId);
doUpload();
}
private void doUpload() {
int statusMessageId = R.string.error_sending_to_mymap;
boolean success = true;
try {
progressIndicator.setProgressValue(1);
progressIndicator.setProgressMessage(
R.string.progress_message_reading_track);
// Get the track meta-data
Track track = providerUtils.getTrack(trackId);
String originalDescription = track.getDescription();
track.setDescription("<p>" + track.getDescription() + "</p><p>"
+ stringUtils.generateTrackDescription(track, null, null) + "</p>");
mapsClient = MyMapsFactory.newMapsClient(context, auth);
// Create a new map if necessary:
boolean isNewMap = mapId.equals(NEW_MAP_ID);
if (isNewMap) {
SharedPreferences preferences = context.getSharedPreferences(
MyTracksSettings.SETTINGS_NAME, 0);
boolean mapPublic = true;
if (preferences != null) {
mapPublic = preferences.getBoolean(
context.getString(R.string.default_map_public_key), true);
}
progressIndicator.setProgressMessage(
R.string.progress_message_creating_map);
StringBuilder mapIdBuilder = new StringBuilder();
success = mapsClient.createNewMap(
track.getName(), track.getCategory(), originalDescription, mapPublic, mapIdBuilder);
mapId = mapIdBuilder.toString();
}
// Upload all of the segments of the track plus start/end markers
if (success) {
success = uploadAllTrackPoints(track, originalDescription);
}
// Put waypoints.
if (success) {
Cursor c = providerUtils.getWaypointsCursor(
track.getId(), 0,
MyTracksConstants.MAX_LOADED_WAYPOINTS_POINTS);
if (c != null) {
try {
if (c.getCount() > 1 && c.moveToFirst()) {
// This will skip the 1st waypoint (it carries the stats for the
// last segment).
ArrayList<WaypointData> waypoints = new ArrayList<WaypointData>(c.getCount() - 1);
while (c.moveToNext()) {
Waypoint wpt = providerUtils.createWaypoint(c);
waypoints.add(new WaypointData(
wpt.getName(), wpt.getDescription(), wpt.getIcon(), wpt.getLocation()));
}
success = mapsClient.uploadWaypoints(mapId, waypoints);
}
} finally {
c.close();
}
} else {
success = false;
}
if (!success) {
Log.w(MyTracksConstants.TAG,
"SendToMyMaps: upload waypoints failed.");
}
}
if (success) {
statusMessageId = isNewMap
? R.string.status_new_mymap_has_been_created
: R.string.status_tracks_have_been_uploaded;
}
Log.d(MyTracksConstants.TAG, "SendToMyMaps: Done: " + success);
progressIndicator.setProgressValue(100);
} finally {
if (mapsClient != null) {
mapsClient.cleanUp();
}
final boolean finalSuccess = success;
final int finalStatusMessageId = statusMessageId;
context.runOnUiThread(new Runnable() {
public void run() {
if (onCompletion != null) {
onCompletion.onSendCompleted(
mapId, finalSuccess, finalStatusMessageId);
}
}
});
}
}
private boolean uploadAllTrackPoints(
final Track track, String originalDescription) {
SharedPreferences preferences = context.getSharedPreferences(
MyTracksSettings.SETTINGS_NAME, 0);
boolean metricUnits = true;
if (preferences != null) {
metricUnits =
preferences.getBoolean(context.getString(R.string.metric_units_key),
true);
}
Cursor locationsCursor =
providerUtils.getLocationsCursor(track.getId(), 0, -1, false);
try {
if (!locationsCursor.moveToFirst()) {
Log.w(MyTracksConstants.TAG, "Unable to get any points to upload");
return false;
}
totalLocationsRead = 0;
totalLocationsPrepared = 0;
totalLocationsUploaded = 0;
totalLocations = locationsCursor.getCount();
totalSegmentsUploaded = 0;
// Limit the number of elevation readings. Ideally we would want around 250.
int elevationSamplingFrequency =
Math.max(1, (int) (totalLocations / 250.0));
Log.d(MyTracksConstants.TAG,
"Using elevation sampling factor: " + elevationSamplingFrequency
+ " on " + totalLocations);
double totalDistance = 0;
Vector<Double> distances = new Vector<Double>();
Vector<Double> elevations = new Vector<Double>();
DoubleBuffer elevationBuffer =
new DoubleBuffer(MyTracksConstants.ELEVATION_SMOOTHING_FACTOR);
List<Location> locations = new ArrayList<Location>(MAX_POINTS_PER_UPLOAD);
progressIndicator.setProgressMessage(
R.string.progress_message_reading_track);
Location lastLocation = null;
do {
if (totalLocationsRead % 100 == 0) {
updateProgress();
}
Location loc = providerUtils.createLocation(locationsCursor);
locations.add(loc);
if (totalLocationsRead == 0) {
// Put a marker at the first point of the first valid segment:
mapsClient.uploadMarker(mapId, track.getName(), track.getDescription(), loc, true);
}
// Add to the elevation profile.
if (loc != null && MyTracksUtils.isValidLocation(loc)) {
// All points go into the smoothing buffer...
elevationBuffer.setNext(metricUnits ? loc.getAltitude()
: loc.getAltitude() * UnitConversions.M_TO_FT);
if (lastLocation != null) {
double dist = lastLocation.distanceTo(loc);
totalDistance += dist;
}
// ...but only a few points are really used to keep the url short.
if (totalLocationsRead % elevationSamplingFrequency == 0) {
distances.add(totalDistance);
elevations.add(elevationBuffer.getAverage());
}
}
// If the location was not valid, it's a segment split, so make sure the
// distance between the previous segment and the new one is not accounted
// for in the next iteration.
lastLocation = loc;
// Every now and then, upload the accumulated points
if (totalLocationsRead % MAX_POINTS_PER_UPLOAD
== MAX_POINTS_PER_UPLOAD - 1) {
if (!prepareAndUploadPoints(track, locations)) {
return false;
}
}
totalLocationsRead++;
} while (locationsCursor.moveToNext());
// Do a final upload with what's left
if (!prepareAndUploadPoints(track, locations)) {
return false;
}
// Put an end marker at the last point of the last valid segment:
if (lastLocation != null) {
track.setDescription("<p>" + originalDescription + "</p><p>"
+ stringUtils.generateTrackDescription(
track, distances, elevations)
+ "</p>");
return mapsClient.uploadMarker(mapId, track.getName(), track.getDescription(),
lastLocation, false);
}
return true;
} finally {
locationsCursor.close();
}
}
private boolean prepareAndUploadPoints(Track track, List<Location> locations) {
progressIndicator.setProgressMessage(
R.string.progress_message_preparing_track);
updateProgress();
int numLocations = locations.size();
if (numLocations < 2) {
Log.d(MyTracksConstants.TAG, "Not preparing/uploading too few points");
totalLocationsUploaded += numLocations;
return true;
}
// Prepare/pre-process the points
ArrayList<Track> splitTracks = prepareLocations(track, locations);
// Start uploading them
progressIndicator.setProgressMessage(
R.string.progress_message_sending_mymaps);
for (Track splitTrack : splitTracks) {
if (totalSegmentsUploaded > 1) {
splitTrack.setName(splitTrack.getName() + " "
+ String.format(
context.getString(R.string.part), totalSegmentsUploaded));
}
totalSegmentsUploaded++;
Log.d(MyTracksConstants.TAG,
"SendToMyMaps: Prepared feature for upload w/ "
+ splitTrack.getLocations().size() + " points.");
// Transmit tracks via GData feed:
// -------------------------------
Log.d(MyTracksConstants.TAG,
"SendToMyMaps: Uploading to map " + mapId + " w/ auth " + auth);
if (!mapsClient.uploadTrackPoints(mapId, splitTrack.getName(), splitTrack.getLocations())) {
Log.e(MyTracksConstants.TAG, "Uploading failed");
return false;
}
}
locations.clear();
totalLocationsUploaded += numLocations;
updateProgress();
return true;
}
/**
* Prepares a buffer of locations for transmission to google maps.
*
* @param track the original track with meta data
* @param buffer a buffer of locations on the track
* @return an array of tracks each with a sub section of the points in the
* original buffer
*/
private ArrayList<Track> prepareLocations(
Track track, Iterable<Location> locations) {
ArrayList<Track> splitTracks = new ArrayList<Track>();
// Create segments from each full track:
Track segment = new Track();
TripStatistics segmentStats = segment.getStatistics();
TripStatistics trackStats = track.getStatistics();
segment.setId(track.getId());
segment.setName(track.getName());
segment.setDescription(/* track.getDescription() */ "");
segment.setCategory(track.getCategory());
segmentStats.setStartTime(trackStats.getStartTime());
segmentStats.setStopTime(trackStats.getStopTime());
boolean startNewTrackSegment = false;
for (Location loc : locations) {
if (totalLocationsPrepared % 100 == 0) {
updateProgress();
}
if (loc.getLatitude() > 90) {
startNewTrackSegment = true;
}
if (startNewTrackSegment) {
// Close up the last segment.
prepareTrackSegment(segment, splitTracks);
Log.d(MyTracksConstants.TAG,
"MyTracksSendToMyMaps: Starting new track segment...");
startNewTrackSegment = false;
segment = new Track();
segment.setId(track.getId());
segment.setName(track.getName());
segment.setDescription(/* track.getDescription() */ "");
segment.setCategory(track.getCategory());
}
if (loc.getLatitude() <= 90) {
segment.addLocation(loc);
if (segmentStats.getStartTime() < 0) {
segmentStats.setStartTime(loc.getTime());
}
}
totalLocationsPrepared++;
}
prepareTrackSegment(segment, splitTracks);
return splitTracks;
}
/**
* Prepares a track segment for sending to google maps.
* The main steps are:
* - correcting end time
* - decimating locations
* - splitting into smaller tracks.
*
* The final track pieces will be put in the array list splitTracks.
*
* @param segment the original segment of the track
* @param splitTracks an array of smaller track segments
*/
private void prepareTrackSegment(
Track segment, ArrayList<Track> splitTracks) {
TripStatistics segmentStats = segment.getStatistics();
if (segmentStats.getStopTime() < 0
&& segment.getLocations().size() > 0) {
segmentStats.setStopTime(segment.getLocations().size() - 1);
}
/*
* Decimate to 2 meter precision. Mapshop doesn't like too many
* points:
*/
MyTracksUtils.decimate(segment, 2.0);
/* It the track still has > 500 points, split it in pieces: */
if (segment.getLocations().size() > 500) {
splitTracks.addAll(MyTracksUtils.split(segment, 500));
} else if (segment.getLocations().size() >= 2) {
splitTracks.add(segment);
}
}
/**
* Sets the current upload progress.
*/
private void updateProgress() {
// The percent of the total that represents the completed part of this
// segment.
int totalPercentage =
(totalLocationsRead + totalLocationsPrepared + totalLocationsUploaded)
/ (totalLocations * 3);
totalPercentage = Math.min(99, totalPercentage);
progressIndicator.setProgressValue(totalPercentage);
}
}
| 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;
import com.google.android.apps.mytracks.MyTracks;
import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.MyTracksSettings;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.io.docs.DocsHelper;
import com.google.android.apps.mytracks.io.gdata.GDataClientFactory;
import com.google.android.apps.mytracks.io.gdata.GDataWrapper;
import com.google.android.common.gdata.AndroidXmlParserFactory;
import com.google.android.maps.mytracks.R;
import com.google.wireless.gdata.client.GDataClient;
import com.google.wireless.gdata.docs.DocumentsClient;
import com.google.wireless.gdata.docs.SpreadsheetsClient;
import com.google.wireless.gdata.docs.XmlDocsGDataParserFactory;
import com.google.wireless.gdata.client.GDataServiceClient;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import java.io.IOException;
/**
* A helper class used to transmit tracks statistics to Google Docs/Trix.
*
* @author Sandor Dornbush
*/
public class SendToDocs {
/** The GData service name for Google Spreadsheets (aka Trix) */
public static final String GDATA_SERVICE_NAME_TRIX = "wise";
/** The GData service name for the Google Docs Document List */
public static final String GDATA_SERVICE_NAME_DOCLIST = "writely";
private final Activity activity;
private final AuthManager trixAuth;
private final AuthManager docListAuth;
private final long trackId;
private final boolean metricUnits;
private final HandlerThread handlerThread;
private final Handler handler;
private boolean createdNewSpreadSheet = false;
private boolean success = true;
private String statusMessage = "";
private Runnable onCompletion = null;
public SendToDocs(Activity activity, AuthManager trixAuth,
AuthManager docListAuth, long trackId) {
this.activity = activity;
this.trixAuth = trixAuth;
this.docListAuth = docListAuth;
this.trackId = trackId;
SharedPreferences preferences = activity.getSharedPreferences(
MyTracksSettings.SETTINGS_NAME, 0);
if (preferences != null) {
metricUnits =
preferences.getBoolean(activity.getString(R.string.metric_units_key),
true);
} else {
metricUnits = true;
}
Log.d(MyTracksConstants.TAG,
"Sending to Google Docs: trackId = " + trackId);
handlerThread = new HandlerThread("SendToGoogleDocs");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
doUpload();
}
});
}
private void doUpload() {
// TODO
statusMessage = activity.getString(R.string.error_sending_to_fusiontables);
success = false;
try {
if (trackId == -1) {
Log.w(MyTracksConstants.TAG, "Cannot get track id.");
return;
}
// Get the track from the provider:
Track track =
MyTracksProviderUtils.Factory.get(activity).getTrack(trackId);
if (track == null) {
Log.w(MyTracksConstants.TAG, "Cannot get track.");
return;
}
// Transmit track stats via GData feed:
// -------------------------------
Log.d(MyTracksConstants.TAG, "SendToDocs: Uploading to spreadsheet");
success = uploadToDocs(track);
if (success) {
if (createdNewSpreadSheet) {
statusMessage = activity.getString(
R.string.status_tracks_have_been_uploaded_to_new_doc);
} else {
statusMessage = activity.getString(
R.string.status_tracks_have_been_uploaded_to_docs);
}
} else {
statusMessage = activity.getString(R.string.error_sending_to_docs);
}
Log.d(MyTracksConstants.TAG, "SendToDocs: Done.");
} finally {
if (onCompletion != null) {
activity.runOnUiThread(onCompletion);
}
}
}
public boolean wasSuccess() {
return success;
}
public String getStatusMessage() {
return statusMessage;
}
public void setOnCompletion(Runnable onCompletion) {
this.onCompletion = onCompletion;
}
/**
* Uploads the statistics about a track to Google Docs using the docs GData
* feed.
*
* @param track the track
*/
private boolean uploadToDocs(Track track) {
GDataWrapper<GDataServiceClient> docListWrapper = new GDataWrapper<GDataServiceClient>();
docListWrapper.setAuthManager(docListAuth);
docListWrapper.setRetryOnAuthFailure(true);
GDataWrapper<GDataServiceClient> trixWrapper = new GDataWrapper<GDataServiceClient>();
trixWrapper.setAuthManager(trixAuth);
trixWrapper.setRetryOnAuthFailure(true);
DocsHelper docsHelper = new DocsHelper();
GDataClient androidClient = null;
try {
androidClient = GDataClientFactory.getGDataClient(activity);
SpreadsheetsClient gdataClient = new SpreadsheetsClient(androidClient,
new XmlDocsGDataParserFactory(new AndroidXmlParserFactory()));
trixWrapper.setClient(gdataClient);
Log.d(MyTracksConstants.TAG,
"GData connection prepared: " + this.docListAuth);
String sheetTitle = "My Tracks";
if (track.getCategory() != null && !track.getCategory().equals("")) {
sheetTitle += "-" + track.getCategory();
}
DocumentsClient docsGdataClient = new DocumentsClient(androidClient,
new XmlDocsGDataParserFactory(new AndroidXmlParserFactory()));
docListWrapper.setClient(docsGdataClient);
// First try to find the spreadsheet:
String spreadsheetId = null;
try {
spreadsheetId = docsHelper.requestSpreadsheetId(docListWrapper,
sheetTitle);
} catch (IOException e) {
Log.i(MyTracksConstants.TAG, "Spreadsheet lookup failed.", e);
return false;
}
if (spreadsheetId == null) {
MyTracks.getInstance().setProgressValue(65);
// Waiting a few seconds and trying again. Maybe the server just had a
// hickup (unfortunately that happens quite a lot...).
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Log.e(MyTracksConstants.TAG, "Sleep interrupted", e);
}
try {
spreadsheetId = docsHelper.requestSpreadsheetId(docListWrapper,
sheetTitle);
} catch (IOException e) {
Log.i(MyTracksConstants.TAG, "2nd spreadsheet lookup failed.", e);
return false;
}
}
// We were unable to find an existing spreadsheet, so create a new one.
MyTracks.getInstance().setProgressValue(70);
if (spreadsheetId == null) {
Log.i(MyTracksConstants.TAG, "Creating new spreadsheet: " + sheetTitle);
try {
spreadsheetId = docsHelper.createSpreadsheet(activity, docListWrapper,
sheetTitle);
} catch (IOException e) {
Log.i(MyTracksConstants.TAG, "Failed to create new spreadsheet "
+ sheetTitle, e);
return false;
}
MyTracks.getInstance().setProgressValue(80);
createdNewSpreadSheet = true;
if (spreadsheetId == null) {
MyTracks.getInstance().setProgressValue(85);
// The previous creation might have succeeded even though GData
// reported an error. Seems to be a know bug,
// see http://code.google.com/p/gdata-issues/issues/detail?id=929
// Try to find the created spreadsheet:
Log.w(MyTracksConstants.TAG,
"Create might have failed. Trying to find created document.");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Log.e(MyTracksConstants.TAG, "Sleep interrupted", e);
}
try {
spreadsheetId = docsHelper.requestSpreadsheetId(docListWrapper,
sheetTitle);
} catch (IOException e) {
Log.i(MyTracksConstants.TAG, "Failed create-failed lookup", e);
return false;
}
if (spreadsheetId == null) {
MyTracks.getInstance().setProgressValue(87);
// Re-try
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Log.e(MyTracksConstants.TAG, "Sleep interrupted", e);
}
try {
spreadsheetId = docsHelper.requestSpreadsheetId(docListWrapper,
sheetTitle);
} catch (IOException e) {
Log.i(MyTracksConstants.TAG, "Failed create-failed relookup", e);
return false;
}
}
if (spreadsheetId == null) {
Log.i(MyTracksConstants.TAG,
"Creating new spreadsheet really failed.");
return false;
}
}
}
String worksheetId = null;
try {
worksheetId = docsHelper.getWorksheetId(trixWrapper, spreadsheetId);
if (worksheetId == null) {
throw new IOException("Worksheet ID lookup returned empty");
}
} catch (IOException e) {
Log.i(MyTracksConstants.TAG, "Looking up worksheet id failed.", e);
return false;
}
MyTracks.getInstance().setProgressValue(90);
docsHelper.addTrackRow(activity, trixAuth, spreadsheetId, worksheetId,
track, metricUnits);
Log.i(MyTracksConstants.TAG, "Done uploading to docs.");
} catch (IOException e) {
Log.e(MyTracksConstants.TAG, "Unable to upload docs.", e);
return false;
} finally {
if (androidClient != null) {
androidClient.close();
}
}
return true;
}
}
| 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;
import android.os.Environment;
import java.io.File;
/**
* A class to clean up old temporary files.
* @author Sandor Dornbush
*/
public class TempFileCleaner {
private long currentTimeMillis;
public static void clean() {
(new TempFileCleaner(System.currentTimeMillis())).cleanImpl();
}
// @VisibleForTesting
TempFileCleaner(long time) {
currentTimeMillis = time;
}
private void cleanImpl() {
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
return; // Can't do anything now.
}
cleanTmpDirectory("csv");
cleanTmpDirectory("gpx");
cleanTmpDirectory("kml");
cleanTmpDirectory("tcx");
}
private void cleanTmpDirectory(String name) {
String sep = System.getProperty("file.separator");
cleanTmpDirectory(
new File(
Environment.getExternalStorageDirectory() + sep + name + sep
+ "tmp"));
}
// @VisibleForTesting
int cleanTmpDirectory(File dir) {
if (!dir.exists()) {
return 0;
}
int count = 0;
long oldest = currentTimeMillis - 1000 * 3600;
for (File f : dir.listFiles()) {
if (f.lastModified() < oldest) {
f.delete();
count++;
}
}
return count;
}
}
| 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;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.io.TrackWriterFactory.TrackFileFormat;
import com.google.android.apps.mytracks.util.StringUtils;
import android.location.Location;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Log of one track.
*
* @author Sandor Dornbush
*/
public class GpxTrackWriter implements TrackFormatWriter {
private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
private final NumberFormat elevationFormatter;
private final NumberFormat coordinateFormatter;
private final SimpleDateFormat timestampFormatter;
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);
timestampFormatter = new SimpleDateFormat(TIMESTAMP_FORMAT);
timestampFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
}
private String formatLocation(Location l) {
return "lat=\"" + coordinateFormatter.format(l.getLatitude())
+ "\" lon=\"" + coordinateFormatter.format(l.getLongitude()) + "\"";
}
@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.println(" creator=\"My Tracks for the G1 running Android\"");
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>" + timestampFormatter.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>" + timestampFormatter.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 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.wireless.gdata.docs;
import com.google.wireless.gdata.client.GDataClient;
import com.google.wireless.gdata.client.GDataParserFactory;
import com.google.wireless.gdata.client.GDataServiceClient;
import com.google.wireless.gdata.client.HttpException;
import com.google.wireless.gdata.data.Entry;
import com.google.wireless.gdata.data.StringUtils;
import com.google.wireless.gdata.parser.GDataParser;
import com.google.wireless.gdata.parser.ParseException;
import com.google.wireless.gdata.serializer.GDataSerializer;
import com.google.wireless.gdata2.client.AuthenticationException;
import java.io.IOException;
import java.io.InputStream;
/**
* GDataServiceClient for accessing Google Spreadsheets. This client can access
* and parse all of the Spreadsheets feed types: Spreadsheets feed, Worksheets
* feed, List feed, and Cells feed. Read operations are supported on all feed
* types, but only the List and Cells feeds support write operations. (This is a
* limitation of the protocol, not this API. Such write access may be added to
* the protocol in the future, requiring changes to this implementation.)
*
* Only 'private' visibility and 'full' projections are currently supported.
*/
public class SpreadsheetsClient extends GDataServiceClient {
/** The name of the service, dictated to be 'wise' by the protocol. */
private static final String SERVICE = "wise";
/** Standard base feed url for spreadsheets. */
public static final String SPREADSHEETS_BASE_FEED_URL =
"http://spreadsheets.google.com/feeds/spreadsheets/private/full";
/**
* Represents an entry in a GData Spreadsheets meta-feed.
*/
public static class SpreadsheetEntry extends Entry { }
/**
* Represents an entry in a GData Worksheets meta-feed.
*/
public static class WorksheetEntry extends Entry { }
/**
* Creates a new SpreadsheetsClient. Uses the standard base URL for
* spreadsheets feeds.
*
* @param client The GDataClient that should be used to authenticate requests,
* retrieve feeds, etc
*/
public SpreadsheetsClient(GDataClient client,
GDataParserFactory spreadsheetFactory) {
super(client, spreadsheetFactory);
}
@Override
public String getServiceName() {
return SERVICE;
}
/**
* Returns a parser for the specified feed type.
*
* @param feedEntryClass the Class of entry type that will be parsed, which
* lets this method figure out which parser to create
* @param feedUri the URI of the feed to be fetched and parsed
* @param authToken the current authToken to use for the request
* @return a parser for the indicated feed
* @throws AuthenticationException if the authToken is not valid
* @throws ParseException if the response from the server could not be parsed
*/
private GDataParser getParserForTypedFeed(
Class<? extends Entry> feedEntryClass, String feedUri, String authToken)
throws AuthenticationException, ParseException, IOException {
GDataClient gDataClient = getGDataClient();
GDataParserFactory gDataParserFactory = getGDataParserFactory();
try {
InputStream is = gDataClient.getFeedAsStream(feedUri, authToken);
return gDataParserFactory.createParser(feedEntryClass, is);
} catch (HttpException e) {
convertHttpExceptionForReads("Could not fetch parser feed.", e);
return null; // never reached
}
}
/**
* Converts an HTTP exception that happened while reading into the equivalent
* local exception.
*/
public void convertHttpExceptionForReads(String message, HttpException cause)
throws AuthenticationException, IOException {
switch (cause.getStatusCode()) {
case HttpException.SC_FORBIDDEN:
case HttpException.SC_UNAUTHORIZED:
throw new AuthenticationException(message, cause);
case HttpException.SC_GONE:
default:
throw new IOException(message + ": " + cause.getMessage());
}
}
@Override
public Entry createEntry(String feedUri, String authToken, Entry entry)
throws ParseException, IOException {
GDataParserFactory factory = getGDataParserFactory();
GDataSerializer serializer = factory.createSerializer(entry);
InputStream is;
try {
is = getGDataClient().createEntry(feedUri, authToken, serializer);
} catch (HttpException e) {
convertHttpExceptionForWrites(entry.getClass(),
"Could not update entry.", e);
return null; // never reached.
}
GDataParser parser = factory.createParser(entry.getClass(), is);
try {
return parser.parseStandaloneEntry();
} finally {
parser.close();
}
}
/**
* Fetches a GDataParser for the indicated feed. The parser can be used to
* access the contents of URI. WARNING: because we cannot reliably infer the
* feed type from the URI alone, this method assumes the default feed type!
* This is probably NOT what you want. Please use the getParserFor[Type]Feed
* methods.
*
* @param feedEntryClass
* @param feedUri the URI of the feed to be fetched and parsed
* @param authToken the current authToken to use for the request
* @return a parser for the indicated feed
* @throws ParseException if the response from the server could not be parsed
*/
@SuppressWarnings("unchecked")
@Override
public GDataParser getParserForFeed(
Class feedEntryClass, String feedUri, String authToken)
throws ParseException, IOException {
try {
return getParserForTypedFeed(SpreadsheetEntry.class, feedUri, authToken);
} catch (AuthenticationException e) {
throw new IOException("Authentication Failure: " + e.getMessage());
}
}
/**
* Returns a parser for a Worksheets meta-feed.
*
* @param feedUri the URI of the feed to be fetched and parsed
* @param authToken the current authToken to use for the request
* @return a parser for the indicated feed
* @throws AuthenticationException if the authToken is not valid
* @throws ParseException if the response from the server could not be parsed
*/
public GDataParser getParserForWorksheetsFeed(
String feedUri, String authToken)
throws AuthenticationException, ParseException, IOException {
return getParserForTypedFeed(WorksheetEntry.class, feedUri, authToken);
}
/**
* Updates an entry. The URI to be updated is taken from <code>entry</code>.
* Note that only entries in List and Cells feeds can be updated, so
* <code>entry</code> must be of the corresponding type; other types will
* result in an exception.
*
* @param entry the entry to be updated; must include its URI
* @param authToken the current authToken to be used for the operation
* @return An Entry containing the re-parsed version of the entry returned by
* the server in response to the update
* @throws ParseException if the server returned an error, if the server's
* response was unparseable (unlikely), or if <code>entry</code> is of
* a read-only type
* @throws IOException on network error
*/
@Override
public Entry updateEntry(Entry entry, String authToken)
throws ParseException, IOException {
GDataParserFactory factory = getGDataParserFactory();
GDataSerializer serializer = factory.createSerializer(entry);
String editUri = entry.getEditUri();
if (StringUtils.isEmpty(editUri)) {
throw new ParseException("No edit URI -- cannot update.");
}
InputStream is;
try {
is = getGDataClient().updateEntry(editUri, authToken, serializer);
} catch (HttpException e) {
convertHttpExceptionForWrites(entry.getClass(),
"Could not update entry.", e);
return null; // never reached
}
GDataParser parser = factory.createParser(entry.getClass(), is);
try {
return parser.parseStandaloneEntry();
} finally {
parser.close();
}
}
/**
* Converts an HTTP exception which happened while writing to the equivalent
* local exception.
*/
@SuppressWarnings("unchecked")
private void convertHttpExceptionForWrites(
Class entryClass, String message, HttpException cause)
throws ParseException, IOException {
switch (cause.getStatusCode()) {
case HttpException.SC_CONFLICT:
if (entryClass != null) {
InputStream is = cause.getResponseStream();
if (is != null) {
parseEntry(entryClass, cause.getResponseStream());
}
}
throw new IOException(message);
case HttpException.SC_BAD_REQUEST:
throw new ParseException(message + ": " + cause);
case HttpException.SC_FORBIDDEN:
case HttpException.SC_UNAUTHORIZED:
throw new IOException(message);
default:
throw new IOException(message + ": " + cause.getMessage());
}
}
/**
* Parses one entry from the input stream.
*/
@SuppressWarnings("unchecked")
private Entry parseEntry(Class entryClass, InputStream is)
throws ParseException, IOException {
GDataParser parser = null;
try {
parser = getGDataParserFactory().createParser(entryClass, is);
return parser.parseStandaloneEntry();
} finally {
if (parser != null) {
parser.close();
}
}
}
}
| 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.wireless.gdata.docs;
import com.google.wireless.gdata.client.GDataClient;
import com.google.wireless.gdata.client.GDataParserFactory;
import com.google.wireless.gdata.client.GDataServiceClient;
/**
* GDataServiceClient for accessing Google Documents. This is not a full
* implementation.
*/
public class DocumentsClient extends GDataServiceClient {
/** The name of the service, dictated to be 'wise' by the protocol. */
private static final String SERVICE = "writely";
/**
* Creates a new DocumentsClient.
*
* @param client The GDataClient that should be used to authenticate requests,
* retrieve feeds, etc
* @param parserFactory The GDataParserFactory that should be used to obtain
* GDataParsers used by this client
*/
public DocumentsClient(GDataClient client, GDataParserFactory parserFactory) {
super(client, parserFactory);
}
@Override
public String getServiceName() {
return SERVICE;
}
}
| 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.wireless.gdata.docs;
import com.google.wireless.gdata.client.GDataParserFactory;
import com.google.wireless.gdata.data.Entry;
import com.google.wireless.gdata.parser.GDataParser;
import com.google.wireless.gdata.parser.ParseException;
import com.google.wireless.gdata.parser.xml.XmlGDataParser;
import com.google.wireless.gdata.parser.xml.XmlParserFactory;
import com.google.wireless.gdata.serializer.GDataSerializer;
import com.google.wireless.gdata.serializer.xml.XmlEntryGDataSerializer;
import java.io.InputStream;
import org.xmlpull.v1.XmlPullParserException;
/**
* Factory of Xml parsers for gdata maps data.
*/
public class XmlDocsGDataParserFactory implements GDataParserFactory {
private XmlParserFactory xmlFactory;
public XmlDocsGDataParserFactory(XmlParserFactory xmlFactory) {
this.xmlFactory = xmlFactory;
}
@Override
public GDataParser createParser(InputStream is) throws ParseException {
try {
return new XmlGDataParser(is, xmlFactory.createParser());
} catch (XmlPullParserException e) {
e.printStackTrace();
return null;
}
}
@SuppressWarnings("unchecked")
@Override
public GDataParser createParser(Class cls, InputStream is)
throws ParseException {
try {
return createParserForClass(cls, is);
} catch (XmlPullParserException e) {
e.printStackTrace();
return null;
}
}
private GDataParser createParserForClass(
Class<? extends Entry> cls, InputStream is)
throws ParseException, XmlPullParserException {
return new XmlGDataParser(is, xmlFactory.createParser());
}
@Override
public GDataSerializer createSerializer(Entry en) {
return new XmlEntryGDataSerializer(xmlFactory, en);
}
} | 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 string) {
super(string);
}
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.content.Sensor;
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) {
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) {
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) {
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) {
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) {
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) {
String selection = TrackPointsColumns._ID + "=" + id;
return findLocationBy(selection);
}
@Override
public Cursor getLocationsCursor(long trackId, long minTrackPointId,
int maxLocations, boolean descending) {
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) {
String selection;
if (minWaypointId > 0) {
selection = String.format("%s=%d AND %s>=%d",
WaypointsColumns.TRACKID, trackId,
WaypointsColumns._ID, minWaypointId);
} else {
selection = String.format("%s=%d",
WaypointsColumns.TRACKID, trackId);
}
String sortOrder = "_id ASC";
if (maxWaypoints > 0) {
sortOrder += " LIMIT " + maxWaypoints;
}
return contentResolver.query(
WaypointsColumns.CONTENT_URI, null, selection, null, sortOrder);
}
@Override
public Track getTrack(long id) {
String select = TracksColumns._ID + "=" + id;
return findTrackBy(select);
}
@Override
public List<Track> getAllTracks() {
Cursor cursor = getTracksCursor(null);
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) {
Cursor cursor = contentResolver.query(
TracksColumns.CONTENT_URI, null, selection, null, "_id");
return cursor;
}
@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) {
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 gets to own the returned cursor. Don't forget to close 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 gets to own the returned cursor. Don't forget to close 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);
/**
* 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 gets to own the returned cursor. Don't forget to close it.
*
* @param selection a given selection
* @return a cursor of the selected tracks
*/
Cursor getTracksCursor(String selection);
/**
* 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.
*/
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");
}
};
/**
* 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 waypoints.
*
* @author Sandor Dornbush
*/
public interface DescriptionGenerator {
/**
* Generate a description of the waypoint.
*/
public String generateWaypointDescription(Waypoint waypoint);
/**
* Generates a description for a track (with information about the
* statistics).
*
* @param track the track
* @return a track description
*/
public String generateTrackDescription(Track track, Vector<Double> distances,
Vector<Double> elevations);
}
| 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 {@link 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 = -1;
/**
* The stop time for the trip. This is the system time which might not match
* gps time.
*/
private long stopTime = -1;
/**
* 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() {
return totalDistance / ((double) totalTime / 1000);
}
/**
* Gets the the average speed the user traveled when they were actively
* moving.
*
* @return The average moving speed in m/s
*/
public double getAverageMovingSpeed() {
return totalDistance / ((double) movingTime / 1000);
}
/**
* 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
* decimal degrees.
*/
public int getLeft() {
return (int) (longitudeExtremities.getMin() * 1E6);
}
/**
* Returns the rightmost position (highest longitude) of the track, in signed
* decimal degrees.
*/
public int getRight() {
return (int) (longitudeExtremities.getMax() * 1E6);
}
/**
* Returns the bottommost position (lowest latitude) of the track, in meters.
*/
public int getBottom() {
return (int) (latitudeExtremities.getMin() * 1E6);
}
/**
* Returns the topmost position (highest latitude) of the track, in meters.
*/
public int getTop() {
return (int) (latitudeExtremities.getMax() * 1E6);
}
/**
* 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;
}
@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.*;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.MyTracksProviderUtilsImpl;
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, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent, startId);
return START_STICKY;
}
private void handleCommand(Intent intent, int startId) {
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", icon, description);
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) ||
ctx.getString(R.string.track_resumed_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) ||
ctx.getString(R.string.track_paused_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.*;
import android.content.Context;
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 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;
}
@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() {
StringBuffer sb = new StringBuffer();
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');
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();
}
/**
* 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 |
package com.spatialite.activities;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import jsqlite.Stmt;
import com.spatialite.R;
import com.spatialite.utilities.ActivityHelper;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class TableListActivity extends ListActivity {
private static final String TAG = TableListActivity.class.getName();
TableListAdapter mListAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tablelist);
mListAdapter = new TableListAdapter(this, R.layout.tablelist_row,
new ArrayList<TableInfo>());
setListAdapter(mListAdapter);
fillList();
}
private void fillList() {
try {
String dbFile;
try {
// Find the database
dbFile = ActivityHelper.getDataBase(this,
getString(R.string.test_db));
} catch (FileNotFoundException e) {
ActivityHelper.showAlert(this,
getString(R.string.error_locate_failed));
throw e;
}
// Open the database
jsqlite.Database db = new jsqlite.Database();
db.open(dbFile.toString(), jsqlite.Constants.SQLITE_OPEN_READONLY);
Stmt stmt = db
.prepare("SELECT f_table_name, type, srid FROM geometry_columns;");
// Insert results into list
while (stmt.step()) {
String tableName = stmt.column_string(0);
String type = stmt.column_string(1);
String srid = stmt.column_string(2);
mListAdapter.add(new TableInfo(tableName, type, srid));
}
// Close database
db.close();
} catch (jsqlite.Exception e) {
Log.e(TAG, e.getMessage());
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage());
}
}
private class TableInfo {
private String tableName;
private String type;
private String srid;
TableInfo(String tableName, String type, String srid) {
this.tableName = tableName;
this.type = type;
this.srid = srid;
}
public String getTableName() {
return tableName;
}
public String getType() {
return type;
}
public String getSrid() {
return srid;
}
}
private class TableListAdapter extends ArrayAdapter<TableInfo> {
List<TableInfo> objects;
public TableListAdapter(Context context, int layoutResourceId,
List<TableInfo> objects) {
super(context, layoutResourceId, objects);
this.objects = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = null;
if (null == convertView) {
v = getLayoutInflater().inflate(R.layout.tablelist_row, null);
} else {
v = convertView;
}
TextView name = (TextView) v.findViewById(R.id.table_name);
name.setText(objects.get(position).getTableName());
TextView type = (TextView) v.findViewById(R.id.type);
type.setText(objects.get(position).getType());
return v;
}
}
}
| Java |
package com.spatialite.activities;
import jsqlite.Exception;
import jsqlite.Stmt;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.util.Log;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKBReader;
/**
* Map overlay to highlight various regions when the uses clicks on the MapView.
*/
public class MapSelectionOverlay extends Overlay {
private static final String TAG = MapSelectionOverlay.class.getName();
private final jsqlite.Database mDatabase;
private final TextView mTextVew;
// Allocate once and reuse
private final Paint mPaint = new Paint();
private final Path mPath = new Path();
// Results
private String mRegion;
private Geometry mGeometry;
/**
* @param databaseName Name of database containing the Regions table. Cannot be null.
* @param textVew TextView used to display the region name. Cannot be null.
*/
public MapSelectionOverlay(String databaseName, TextView textVew) throws Exception {
// TODO make sure databaseName and textView are not null
mTextVew = textVew;
// Open readonly database
mDatabase = new jsqlite.Database();
mDatabase.open(databaseName, jsqlite.Constants.SQLITE_OPEN_READONLY);
// Edit paint style
mPaint.setDither(true);
mPaint.setColor(Color.rgb(128, 136, 231));
mPaint.setAlpha(100);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(6);
}
/**
* Handle a "tap" event.
*
* @see com.google.android.maps.Overlay#onTap(GeoPoint, MapView)
*/
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
try {
// Create query
// TODO reuse stmt
Stmt stmt = mDatabase
.prepare("SELECT name, AsBinary(ST_Transform(geometry,4326)) FROM Regions WHERE ST_Within(ST_Transform(MakePoint(?,?,4326),32632),Geometry);");
stmt.bind(1, p.getLongitudeE6() / 1E6);
stmt.bind(2, p.getLatitudeE6() / 1E6);
if (stmt.step()) {
// Set region name
mRegion = stmt.column_string(0);
mTextVew.setText(mRegion);
// Create JTS geometry from binary representation
// returned from database
try {
mGeometry = new WKBReader().read(stmt.column_bytes(1));
} catch (ParseException e) {
mGeometry = null;
Log.e(TAG, e.getMessage());
}
}
stmt.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
// Indicate tap was handled
return true;
}
/**
* Draw the overlay over the map.
*
* @see com.google.android.maps.Overlay#draw(Canvas, MapView, boolean)
*/
@Override
public void draw(Canvas canvas, MapView mapv, boolean shadow) {
super.draw(canvas, mapv, shadow);
if (mGeometry != null) {
// TODO There could be more than one geometries
Geometry g = mGeometry.getGeometryN(0);
final Point p = new Point();
boolean first = true;
mPath.reset();
for (Coordinate c : g.getCoordinates()) {
// Convert lat/lon to pixels on screen
// GeoPoint is immutable so allocation is unavoidable
Projection projection = mapv.getProjection();
projection.toPixels(new GeoPoint((int) (c.y * 1E6), (int) (c.x * 1E6)), p);
// Set path starting point to first coordinate
// otherwise default start is (0,0)
if (first) {
mPath.moveTo(p.x, p.y);
first = false;
}
// Add new point to path
mPath.lineTo(p.x, p.y);
}
}
// Draw the path with give paint
canvas.drawPath(mPath, mPaint);
}
}
| Java |
package com.spatialite.activities;
import java.io.FileNotFoundException;
import java.util.List;
import jsqlite.Exception;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.spatialite.R;
import com.spatialite.utilities.ActivityHelper;
public class MappingActivity extends MapActivity {
private static final String TAG = MappingActivity.class.getName();
List<Overlay> mOverlays;
MapView mMapView;
MapController mMapController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
mMapView = (MapView) findViewById(R.id.mapview);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mOverlays = mMapView.getOverlays();
try {
String dbFile = ActivityHelper.getDataBase(this,
getString(R.string.test_db));
TextView textRegion = (TextView) findViewById(R.id.text_region);
// Add overlay to MapView
mOverlays.add(new MapSelectionOverlay(dbFile, textRegion));
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
// Center map on Italy
mMapController.setCenter(new GeoPoint((int) (42.78 * 1E6), (int) (11.82 * 1E6)));
mMapController.setZoom(7);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
| Java |
package com.spatialite.activities;
import java.io.FileNotFoundException;
import java.util.Arrays;
import com.spatialite.R;
import com.spatialite.utilities.ActivityHelper;
import jsqlite.Callback;
import jsqlite.Stmt;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class TestActivity extends Activity implements OnClickListener {
private static final String TAG = "TestActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
runTest();
}
}
private void runTest() {
try {
// Reset TextView to failed
TextView view = (TextView) findViewById(R.id.txt_result);
view.setText("Result: Failed");
String dbFile;
try {
// Find the database
dbFile = ActivityHelper.getDataBase(this,
getString(R.string.test_db));
} catch (FileNotFoundException e) {
// Database was not found alert the user and stop the test
ActivityHelper.showAlert(this,
getString(R.string.error_locate_failed));
throw e;
}
// Open the database
jsqlite.Database db = new jsqlite.Database();
db.open(dbFile.toString(), jsqlite.Constants.SQLITE_OPEN_READONLY);
// Callback used to display query results in Android LogCat
Callback cb = new Callback() {
@Override
public void columns(String[] coldata) {
Log.v(TAG, "Columns: " + Arrays.toString(coldata));
}
@Override
public void types(String[] types) {
Log.v(TAG, "Types: " + Arrays.toString(types));
}
@Override
public boolean newrow(String[] rowdata) {
Log.v(TAG, "Row: " + Arrays.toString(rowdata));
return false;
}
};
// Test prepare statements
String query = "SELECT name, peoples, AsText(Geometry) from Towns where peoples > 350000";
Stmt st = db.prepare(query);
st.step();
st.close();
// Test various queries
db.exec("select Distance(PointFromText('point(-77.35368 39.04106)', 4326), PointFromText('point(-77.35581 39.01725)', 4326));",
cb);
db.exec("SELECT name, peoples, AsText(Geometry), GeometryType(Geometry), NumPoints(Geometry), SRID(Geometry), IsValid(Geometry) from Towns where peoples > 350000;",
cb);
db.exec("SELECT Distance( Transform(MakePoint(4.430174797, 51.01047063, 4326), 32631), Transform(MakePoint(4.43001276, 51.01041585, 4326),32631));",
cb);
// Close the database
db.close();
// If we got here everything "worked"
view.setText("Result: Passed");
} catch (jsqlite.Exception e) {
Log.e(TAG, e.getMessage());
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage());
}
}
} | Java |
package com.spatialite.activities;
import java.io.IOException;
import com.spatialite.R;
import com.spatialite.utilities.ActivityHelper;
import com.spatialite.utilities.AssetHelper;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener {
@SuppressWarnings("unused")
private static final String TAG = MainActivity.class.getName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_install_to_application) {
try {
AssetHelper.CopyAsset(this,
ActivityHelper.getPath(this, false),
getString(R.string.test_db));
} catch (IOException e) {
ActivityHelper.showAlert(this,
getString(R.string.error_copy_failed));
}
} else if (v.getId() == R.id.btn_install_to_external) {
try {
AssetHelper.CopyAsset(this, ActivityHelper.getPath(this, true),
getString(R.string.test_db));
} catch (IOException e) {
ActivityHelper.showAlert(this,
getString(R.string.error_copy_failed));
}
} else if (v.getId() == R.id.btn_run_tests) {
Intent myIntent = new Intent(this, TestActivity.class);
startActivity(myIntent);
} else if (v.getId() == R.id.btn_browse_data) {
Intent myIntent = new Intent(this, TableListActivity.class);
startActivity(myIntent);
} else if (v.getId() == R.id.btn_map) {
Intent myIntent = new Intent(this, MappingActivity.class);
startActivity(myIntent);
}
}
}
| Java |
package com.spatialite.utilities;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
public class AssetHelper {
private static final String TAG = "AssetHelper";
static public void CopyAsset(Context ctx, File path, String filename)
throws IOException {
AssetManager assetManager = ctx.getAssets();
InputStream in = null;
OutputStream out = null;
// Copy files from asset folder to application folder
try {
in = assetManager.open(filename);
out = new FileOutputStream(path.toString() + "/" + filename);
copyFile(in, out);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
throw e;
} finally {
// Reclaim resources
if (in != null) {
in.close();
in = null;
}
if (out != null) {
out.flush();
out.close();
out = null;
}
}
}
static private void copyFile(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
int read;
// Copy from input stream to output stream
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
}
| Java |
package com.spatialite.utilities;
import java.io.File;
import java.io.FileNotFoundException;
import com.spatialite.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
public class ActivityHelper {
private static final String TAG = "ActivityHelper";
static public void showAlert(Context ctx, final String message) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Application Error");
alertDialog.setMessage(message);
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Dismiss",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
alertDialog.show();
}
static public String getDataBase(Context ctx, String filename) throws FileNotFoundException {
File db = null;
// Check application storage first
db = new File(getPath(ctx, false), filename);
Log.d(TAG, "Checking: " + db.toString());
if (db.exists()) {
return db.toString();
}
// Check external storage second
db = new File(getPath(ctx, true), filename);
Log.d(TAG, "Checking: " + db.toString());
if (db.exists()) {
return db.toString();
}
// Database not found
throw new FileNotFoundException(ctx.getString(R.string.error_locate_failed));
}
static public File getPath(Context ctx, boolean externalStorage) {
if (externalStorage) {
return ctx.getExternalFilesDir(null);
} else {
return ctx.getFilesDir();
}
}
}
| Java |
package jsqlite;
/**
* Callback interface for SQLite's trace function.
*/
public interface Trace {
/**
* Callback to trace (ie log) one SQL statement.
*
* @param stmt SQL statement string
*/
public void trace(String stmt);
}
| Java |
package jsqlite;
/**
* Class for SQLite related exceptions.
*/
public class Exception extends java.lang.Exception {
/**
* Construct a new SQLite exception.
*
* @param string error message
*/
public Exception(String string) {
super(string);
}
}
| Java |
package jsqlite;
/**
* Callback interface for SQLite's user defined functions.
* Each callback method receives a
* <A HREF="FunctionContext.html">FunctionContext</A> object
* which is used to set the function result or error code.
* <BR><BR>
* Example:<BR>
*
* <PRE>
* class SinFunc implements SQLite.Function {
* public void function(SQLite.FunctionContext fc, String args[]) {
* try {
* Double d = new Double(args[0]);
* fc.set_result(Math.sin(d.doubleValue()));
* } catch (Exception e) {
* fc.set_error("sin(" + args[0] + "):" + e);
* }
* }
* ...
* }
* SQLite.Database db = new SQLite.Database();
* db.open("db", 0);
* db.create_function("sin", 1, SinFunc);
* ...
* db.exec("select sin(1.0) from test", null);
* </PRE>
*/
public interface Function {
/**
* Callback for regular function.
*
* @param fc function's context for reporting result
* @param args String array of arguments
*/
public void function(FunctionContext fc, String args[]);
/**
* Callback for one step in aggregate function.
*
* @param fc function's context for reporting result
* @param args String array of arguments
*/
public void step(FunctionContext fc, String args[]);
/**
* Callback for final step in aggregate function.
*
* @param fc function's context for reporting result
*/
public void last_step(FunctionContext fc);
}
| Java |
package jsqlite;
/**
* Class wrapping an SQLite backup object.
*/
public class Backup {
/**
* Internal handle for the native SQLite API.
*/
protected long handle = 0;
/**
* Finish a backup.
*/
protected void finish() throws jsqlite.Exception {
synchronized(this) {
_finalize();
}
}
/**
* Destructor for object.
*/
protected void finalize() {
synchronized(this) {
try {
_finalize();
} catch (jsqlite.Exception e) {
}
}
}
protected native void _finalize() throws jsqlite.Exception;
/**
* Perform a backup step.
*
* @param n number of pages to backup
* @return true when backup completed
*/
public boolean step(int n) throws jsqlite.Exception {
synchronized(this) {
return _step(n);
}
}
private native boolean _step(int n) throws jsqlite.Exception;
/**
* Perform the backup in one step.
*/
public void backup() throws jsqlite.Exception {
synchronized(this) {
_step(-1);
}
}
/**
* Return number of remaining pages to be backed up.
*/
public int remaining() throws jsqlite.Exception {
synchronized(this) {
return _remaining();
}
}
private native int _remaining() throws jsqlite.Exception;
/**
* Return the total number of pages in the backup source database.
*/
public int pagecount() throws jsqlite.Exception {
synchronized(this) {
return _pagecount();
}
}
private native int _pagecount() throws jsqlite.Exception;
/**
* Internal native initializer.
*/
private static native void internal_init();
static {
internal_init();
}
}
| Java |
package jsqlite;
import java.util.Vector;
/**
* Class representing an SQLite result set as
* returned by the
* <A HREF="Database.html#get_table(java.lang.String)">Database.get_table</A>
* convenience method.
* <BR><BR>
* Example:<BR>
*
* <PRE>
* ...
* SQLite.Database db = new SQLite.Database();
* db.open("db", 0);
* System.out.print(db.get_table("select * from TEST"));
* ...
* </PRE>
* Example output:<BR>
*
* <PRE>
* id|firstname|lastname|
* 0|John|Doe|
* 1|Speedy|Gonzales|
* ...
* </PRE>
*/
public class TableResult implements Callback {
/**
* Number of columns in the result set.
*/
public int ncolumns;
/**
* Number of rows in the result set.
*/
public int nrows;
/**
* Column names of the result set.
*/
public String column[];
/**
* Types of columns of the result set or null.
*/
public String types[];
/**
* Rows of the result set. Each row is stored as a String array.
*/
public Vector rows;
/**
* Maximum number of rows to hold in the table.
*/
public int maxrows = 0;
/**
* Flag to indicate Maximum number of rows condition.
*/
public boolean atmaxrows;
/**
* Create an empty result set.
*/
public TableResult() {
clear();
}
/**
* Create an empty result set with maximum number of rows.
*/
public TableResult(int maxrows) {
this.maxrows = maxrows;
clear();
}
/**
* Clear result set.
*/
public void clear() {
column = new String[0];
types = null;
rows = new Vector();
ncolumns = nrows = 0;
atmaxrows = false;
}
/**
* Callback method used while the query is executed.
*/
public void columns(String coldata[]) {
column = coldata;
ncolumns = column.length;
}
/**
* Callback method used while the query is executed.
*/
public void types(String types[]) {
this.types = types;
}
/**
* Callback method used while the query is executed.
*/
public boolean newrow(String rowdata[]) {
if (rowdata != null) {
if (maxrows > 0 && nrows >= maxrows) {
atmaxrows = true;
return true;
}
rows.addElement(rowdata);
nrows++;
}
return false;
}
/**
* Make String representation of result set.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
int i;
for (i = 0; i < ncolumns; i++) {
sb.append(column[i] == null ? "NULL" : column[i]);
sb.append('|');
}
sb.append('\n');
for (i = 0; i < nrows; i++) {
int k;
String row[] = (String[]) rows.elementAt(i);
for (k = 0; k < ncolumns; k++) {
sb.append(row[k] == null ? "NULL" : row[k]);
sb.append('|');
}
sb.append('\n');
}
return sb.toString();
}
}
| Java |
package jsqlite;
/**
* Class to represent compiled SQLite3 statement.
*
* Note, that all native methods of this class are
* not synchronized, i.e. it is up to the caller
* to ensure that only one thread is in these
* methods at any one time.
*/
public class Stmt {
/**
* Internal handle for the SQLite3 statement.
*/
private long handle = 0;
/**
* Internal last error code for prepare()/step() methods.
*/
protected int error_code = 0;
/**
* Prepare the next SQL statement for the Stmt instance.
* @return true when the next piece of the SQL statement sequence
* has been prepared, false on end of statement sequence.
*/
public native boolean prepare() throws jsqlite.Exception;
/**
* Perform one step of compiled SQLite3 statement.
*
* Example:<BR>
* <PRE>
* ...
* try {
* Stmt s = db.prepare("select * from x; select * from y;");
* s.bind(...);
* ...
* s.bind(...);
* while (s.step(cb)) {
* Object o = s.value(...);
* ...
* }
* // s.reset() for re-execution or
* // s.prepare() for the next piece of SQL
* while (s.prepare()) {
* s.bind(...);
* ...
* s.bind(...);
* while (s.step(cb)) {
* Object o = s.value(...);
* ...
* }
* }
* } catch (jsqlite.Exception e) {
* s.close();
* }
* </PRE>
*
* @return true when row data is available, false on end
* of result set.
*/
public native boolean step() throws jsqlite.Exception;
/**
* Close the compiled SQLite3 statement.
*/
public native void close() throws jsqlite.Exception;
/**
* Reset the compiled SQLite3 statement without
* clearing parameter bindings.
*/
public native void reset() throws jsqlite.Exception;
/**
* Clear all bound parameters of the compiled SQLite3 statement.
*/
public native void clear_bindings() throws jsqlite.Exception;
/**
* Bind positional integer value to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param value value of parameter
*/
public native void bind(int pos, int value) throws jsqlite.Exception;
/**
* Bind positional long value to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param value value of parameter
*/
public native void bind(int pos, long value) throws jsqlite.Exception;
/**
* Bind positional double value to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param value value of parameter
*/
public native void bind(int pos, double value) throws jsqlite.Exception;
/**
* Bind positional byte array to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param value value of parameter, may be null
*/
public native void bind(int pos, byte[] value) throws jsqlite.Exception;
/**
* Bind positional String to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param value value of parameter, may be null
*/
public native void bind(int pos, String value) throws jsqlite.Exception;
/**
* Bind positional SQL null to compiled SQLite3 statement.
* @param pos parameter index, 1-based
*/
public native void bind(int pos) throws jsqlite.Exception;
/**
* Bind positional zero'ed blob to compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @param length byte size of zero blob
*/
public native void bind_zeroblob(int pos, int length)
throws jsqlite.Exception;
/**
* Return number of parameters in compiled SQLite3 statement.
* @return int number of parameters
*/
public native int bind_parameter_count() throws jsqlite.Exception;
/**
* Return name of parameter in compiled SQLite3 statement.
* @param pos parameter index, 1-based
* @return String parameter name
*/
public native String bind_parameter_name(int pos) throws jsqlite.Exception;
/**
* Return index of named parameter in compiled SQLite3 statement.
* @param name of parameter
* @return int index of parameter, 1-based
*/
public native int bind_parameter_index(String name)
throws jsqlite.Exception;
/**
* Retrieve integer column from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return int column value
*/
public native int column_int(int col) throws jsqlite.Exception;
/**
* Retrieve long column from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return long column value
*/
public native long column_long(int col) throws jsqlite.Exception;
/**
* Retrieve double column from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return double column value
*/
public native double column_double(int col) throws jsqlite.Exception;
/**
* Retrieve blob column from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return byte[] column value
*/
public native byte[] column_bytes(int col) throws jsqlite.Exception;
/**
* Retrieve string column from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return String column value
*/
public native String column_string(int col) throws jsqlite.Exception;
/**
* Retrieve column type from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return column type code, e.g. jsqlite.Constants.SQLITE_INTEGER
*/
public native int column_type(int col) throws jsqlite.Exception;
/**
* Retrieve number of columns of exec'ed SQLite3 statement.
* @return int number of columns
*/
public native int column_count() throws jsqlite.Exception;
/**
* Retrieve column data as object from exec'ed SQLite3 statement.
* @param col column number, 0-based
* @return Object or null
*/
public Object column(int col) throws jsqlite.Exception {
switch (column_type(col)) {
case Constants.SQLITE_INTEGER:
return new Long(column_long(col));
case Constants.SQLITE_FLOAT:
return new Double(column_double(col));
case Constants.SQLITE_BLOB:
return column_bytes(col);
case Constants.SQLITE3_TEXT:
return column_string(col);
}
return null;
}
/**
* Return table name of column of SQLite3 statement.
* @param col column number, 0-based
* @return String or null
*/
public native String column_table_name(int col) throws jsqlite.Exception;
/**
* Return database name of column of SQLite3 statement.
* @param col column number, 0-based
* @return String or null
*/
public native String column_database_name(int col) throws jsqlite.Exception;
/**
* Return declared column type of SQLite3 statement.
* @param col column number, 0-based
* @return String or null
*/
public native String column_decltype(int col) throws jsqlite.Exception;
/**
* Return column name of column of SQLite3 statement.
* @param col column number, 0-based
* @return String or null
*/
public native String column_name(int col) throws jsqlite.Exception;
/**
* Return origin column name of column of SQLite3 statement.
* @param col column number, 0-based
* @return String or null
*/
public native String column_origin_name(int col) throws jsqlite.Exception;
/**
* Return statement status information.
* @param op which counter to report
* @param flg reset flag
* @return counter
*/
public native int status(int op, boolean flg);
/**
* Destructor for object.
*/
protected native void finalize();
/**
* Internal native initializer.
*/
private static native void internal_init();
static {
internal_init();
}
}
| Java |
package jsqlite;
/**
* Callback interface for SQLite's authorizer function.
*/
public interface Authorizer {
/**
* Callback to authorize access.
*
* @param what integer indicating type of access
* @param arg1 first argument (table, view, index, or trigger name)
* @param arg2 second argument (file, table, or column name)
* @param arg3 third argument (database name)
* @param arg4 third argument (trigger name)
* @return Constants.SQLITE_OK for success, Constants.SQLITE_IGNORE
* for don't allow access but don't raise an error, Constants.SQLITE_DENY
* for abort SQL statement with error.
*/
public int authorize(int what, String arg1, String arg2, String arg3,
String arg4);
}
| Java |
package jsqlite.JDBC2z;
import java.sql.*;
import java.util.*;
public class JDBCStatement implements java.sql.Statement {
protected JDBCConnection conn;
protected JDBCResultSet rs;
protected int updcnt;
protected int maxrows = 0;
private ArrayList<String> batch;
public JDBCStatement(JDBCConnection conn) {
this.conn = conn;
this.updcnt = 0;
this.rs = null;
this.batch = null;
}
public void setFetchSize(int fetchSize) throws SQLException {
if (fetchSize != 1) {
throw new SQLException("fetch size not 1");
}
}
public int getFetchSize() throws SQLException {
return 1;
}
public int getMaxRows() throws SQLException {
return maxrows;
}
public void setMaxRows(int max) throws SQLException {
if (max < 0) {
throw new SQLException("max must be >= 0 (was " + max + ")");
}
maxrows = max;
}
public void setFetchDirection(int fetchDirection) throws SQLException {
throw new SQLException("not supported");
}
public int getFetchDirection() throws SQLException {
return ResultSet.FETCH_UNKNOWN;
}
public int getResultSetConcurrency() throws SQLException {
return ResultSet.CONCUR_READ_ONLY;
}
public int getResultSetType() throws SQLException {
return ResultSet.TYPE_SCROLL_INSENSITIVE;
}
public void setQueryTimeout(int seconds) throws SQLException {
// BEGIN android-changed: more closely follow specification:
// "[throws SQLException if] this method is called on a closed Statement or the condition
// seconds >= 0 is not satisfied"
// (http://java.sun.com/javase/6/docs/api/java/sql/Statement.html#setQueryTimeout(int))
if (isClosed()) {
throw new SQLException("can't set a query timeout on a closed statement");
} else if (seconds < 0) {
throw new SQLException("can't set a query timeout of less than 0 seconds");
} else if (seconds == 0) {
// An argument of 0 seconds should set an unlimited timeout. However, since this was not
// done previously, I assume it isn't implemented and use the same implementation.
conn.timeout = 5000;
} else {
conn.timeout = seconds * 1000;
}
// END android-changed
}
public int getQueryTimeout() throws SQLException {
return conn.timeout / 1000; // android-changed: should return seconds
}
public ResultSet getResultSet() throws SQLException {
return rs;
}
ResultSet executeQuery(String sql, String args[], boolean updonly)
throws SQLException {
jsqlite.TableResult tr = null;
if (rs != null) {
rs.close();
rs = null;
}
updcnt = -1;
if (conn == null || conn.db == null) {
throw new SQLException("stale connection");
}
int busy = 0;
boolean starttrans = !conn.autocommit && !conn.intrans;
while (true) {
try {
if (starttrans) {
conn.db.exec("BEGIN TRANSACTION", null);
conn.intrans = true;
}
if (args == null) {
if (updonly) {
conn.db.exec(sql, null);
} else {
tr = conn.db.get_table(sql, maxrows);
}
} else {
if (updonly) {
conn.db.exec(sql, null, args);
} else {
tr = conn.db.get_table(sql, maxrows, args);
}
}
updcnt = (int) conn.db.changes();
} catch (jsqlite.Exception e) {
if (conn.db.is3() &&
conn.db.last_error() == jsqlite.Constants.SQLITE_BUSY &&
conn.busy3(conn.db, ++busy)) {
try {
if (starttrans && conn.intrans) {
conn.db.exec("ROLLBACK", null);
conn.intrans = false;
}
} catch (jsqlite.Exception ee) {
}
try {
int ms = 20 + busy * 10;
if (ms > 1000) {
ms = 1000;
}
synchronized (this) {
this.wait(ms);
}
} catch (java.lang.Exception eee) {
}
continue;
}
throw new SQLException(e.toString());
}
break;
}
if (!updonly && tr == null) {
throw new SQLException("no result set produced");
}
if (!updonly && tr != null) {
rs = new JDBCResultSet(new TableResultX(tr), this);
}
return rs;
}
public ResultSet executeQuery(String sql) throws SQLException {
return executeQuery(sql, null, false);
}
public boolean execute(String sql) throws SQLException {
return executeQuery(sql) != null;
}
public void cancel() throws SQLException {
if (conn == null || conn.db == null) {
throw new SQLException("stale connection");
}
conn.db.interrupt();
}
public void clearWarnings() throws SQLException {
}
public Connection getConnection() throws SQLException {
return conn;
}
public void addBatch(String sql) throws SQLException {
if (batch == null) {
batch = new ArrayList<String>(1);
}
batch.add(sql);
}
public int[] executeBatch() throws SQLException {
if (batch == null) {
return new int[0];
}
int[] ret = new int[batch.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = EXECUTE_FAILED;
}
int errs = 0;
for (int i = 0; i < ret.length; i++) {
try {
execute((String) batch.get(i));
ret[i] = updcnt;
} catch (SQLException e) {
++errs;
}
}
if (errs > 0) {
throw new BatchUpdateException("batch failed", ret);
}
return ret;
}
public void clearBatch() throws SQLException {
if (batch != null) {
batch.clear();
batch = null;
}
}
public void close() throws SQLException {
clearBatch();
conn = null;
}
public int executeUpdate(String sql) throws SQLException {
executeQuery(sql, null, true);
return updcnt;
}
public int getMaxFieldSize() throws SQLException {
return 0;
}
public boolean getMoreResults() throws SQLException {
if (rs != null) {
rs.close();
rs = null;
}
return false;
}
public int getUpdateCount() throws SQLException {
return updcnt;
}
public SQLWarning getWarnings() throws SQLException {
return null;
}
public void setCursorName(String name) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setEscapeProcessing(boolean enable) throws SQLException {
throw new SQLException("not supported");
}
public void setMaxFieldSize(int max) throws SQLException {
throw new SQLException("not supported");
}
public boolean getMoreResults(int x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public ResultSet getGeneratedKeys() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public int executeUpdate(String sql, int autokeys)
throws SQLException {
if (autokeys != Statement.NO_GENERATED_KEYS) {
throw new SQLFeatureNotSupportedException("generated keys not supported");
}
return executeUpdate(sql);
}
public int executeUpdate(String sql, int colIndexes[])
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public int executeUpdate(String sql, String colIndexes[])
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public boolean execute(String sql, int autokeys)
throws SQLException {
if (autokeys != Statement.NO_GENERATED_KEYS) {
throw new SQLFeatureNotSupportedException("autogenerated keys not supported");
}
return execute(sql);
}
public boolean execute(String sql, int colIndexes[])
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public boolean execute(String sql, String colIndexes[])
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public int getResultSetHoldability() throws SQLException {
return ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
public boolean isClosed() throws SQLException {
return conn == null; // android-changed: pretty sure this is correct, since it matches what's done in close()
}
public void setPoolable(boolean yes) throws SQLException {
if (yes) {
throw new SQLException("poolable statements not supported");
}
}
public boolean isPoolable() throws SQLException {
return false;
}
public <T> T unwrap(java.lang.Class<T> iface) throws SQLException {
throw new SQLException("unsupported");
}
public boolean isWrapperFor(java.lang.Class iface) throws SQLException {
return false;
}
}
| Java |
package jsqlite.JDBC2z;
import java.sql.*;
public class JDBCResultSetMetaData implements java.sql.ResultSetMetaData {
private JDBCResultSet r;
public JDBCResultSetMetaData(JDBCResultSet r) {
this.r = r;
}
public String getCatalogName(int column) throws java.sql.SQLException {
return null;
}
public String getColumnClassName(int column) throws java.sql.SQLException {
column--;
if (r != null && r.tr != null) {
if (column < 0 || column >= r.tr.ncolumns) {
return null;
}
if (r.tr instanceof TableResultX) {
switch (((TableResultX) r.tr).sql_type[column]) {
case Types.SMALLINT: return "java.lang.Short";
case Types.INTEGER: return "java.lang.Integer";
case Types.REAL:
case Types.DOUBLE: return "java.lang.Double";
case Types.FLOAT: return "java.lang.Float";
case Types.BIGINT: return "java.lang.Long";
case Types.DATE: return "java.sql.Date";
case Types.TIME: return "java.sql.Time";
case Types.TIMESTAMP: return "java.sql.Timestamp";
case Types.BINARY:
case Types.VARBINARY: return "[B";
/* defaults to varchar below */
}
}
return "java.lang.String";
}
return null;
}
public int getColumnCount() throws java.sql.SQLException {
if (r != null && r.tr != null) {
return r.tr.ncolumns;
}
return 0;
}
public int getColumnDisplaySize(int column) throws java.sql.SQLException {
return 0;
}
public String getColumnLabel(int column) throws java.sql.SQLException {
column--;
String c = null;
if (r != null && r.tr != null) {
if (column < 0 || column >= r.tr.ncolumns) {
return c;
}
c = r.tr.column[column];
}
return c;
}
public String getColumnName(int column) throws java.sql.SQLException {
column--;
String c = null;
if (r != null && r.tr != null) {
if (column < 0 || column >= r.tr.ncolumns) {
return c;
}
c = r.tr.column[column];
if (c != null) {
int i = c.indexOf('.');
if (i > 0) {
return c.substring(i + 1);
}
}
}
return c;
}
public int getColumnType(int column) throws java.sql.SQLException {
column--;
if (r != null && r.tr != null) {
if (column >= 0 && column < r.tr.ncolumns) {
if (r.tr instanceof TableResultX) {
return ((TableResultX) r.tr).sql_type[column];
}
return Types.VARCHAR;
}
}
throw new SQLException("bad column index");
}
public String getColumnTypeName(int column) throws java.sql.SQLException {
column--;
if (r != null && r.tr != null) {
if (column >= 0 && column < r.tr.ncolumns) {
if (r.tr instanceof TableResultX) {
switch (((TableResultX) r.tr).sql_type[column]) {
case Types.SMALLINT: return "smallint";
case Types.INTEGER: return "integer";
case Types.DOUBLE: return "double";
case Types.FLOAT: return "float";
case Types.BIGINT: return "bigint";
case Types.DATE: return "date";
case Types.TIME: return "time";
case Types.TIMESTAMP: return "timestamp";
case Types.BINARY: return "binary";
case Types.VARBINARY: return "varbinary";
case Types.REAL: return "real";
/* defaults to varchar below */
}
}
return "varchar";
}
}
throw new SQLException("bad column index");
}
public int getPrecision(int column) throws java.sql.SQLException {
return 0;
}
public int getScale(int column) throws java.sql.SQLException {
return 0;
}
public String getSchemaName(int column) throws java.sql.SQLException {
return null;
}
public String getTableName(int column) throws java.sql.SQLException {
column--;
String c = null;
if (r != null && r.tr != null) {
if (column < 0 || column >= r.tr.ncolumns) {
return c;
}
c = r.tr.column[column];
if (c != null) {
int i = c.indexOf('.');
if (i > 0) {
return c.substring(0, i);
}
c = null;
}
}
return c;
}
public boolean isAutoIncrement(int column) throws java.sql.SQLException {
return false;
}
public boolean isCaseSensitive(int column) throws java.sql.SQLException {
return false;
}
public boolean isCurrency(int column) throws java.sql.SQLException {
return false;
}
public boolean isDefinitelyWritable(int column)
throws java.sql.SQLException {
return true;
}
public int isNullable(int column) throws java.sql.SQLException {
return columnNullableUnknown;
}
public boolean isReadOnly(int column) throws java.sql.SQLException {
return false;
}
public boolean isSearchable(int column) throws java.sql.SQLException {
return true;
}
public boolean isSigned(int column) throws java.sql.SQLException {
return false;
}
public boolean isWritable(int column) throws java.sql.SQLException {
return true;
}
int findColByName(String columnName) throws java.sql.SQLException {
String c = null;
if (r != null && r.tr != null) {
for (int i = 0; i < r.tr.ncolumns; i++) {
c = r.tr.column[i];
if (c != null) {
if (c.compareToIgnoreCase(columnName) == 0) {
return i + 1;
}
int k = c.indexOf('.');
if (k > 0) {
c = c.substring(k + 1);
if (c.compareToIgnoreCase(columnName) == 0) {
return i + 1;
}
}
}
c = null;
}
}
throw new SQLException("column " + columnName + " not found");
}
public <T> T unwrap(java.lang.Class<T> iface) throws SQLException {
throw new SQLException("unsupported");
}
public boolean isWrapperFor(java.lang.Class iface) throws SQLException {
return false;
}
}
| Java |
package jsqlite.JDBC2z;
import java.sql.*;
import java.util.*;
public class JDBCConnection
implements java.sql.Connection, jsqlite.BusyHandler {
/**
* Open database.
*/
protected DatabaseX db;
/**
* Database URL.
*/
protected String url;
/**
* Character encoding.
*/
protected String enc;
/**
* SQLite 3 VFS to use.
*/
protected String vfs;
/**
* Autocommit flag, true means autocommit.
*/
protected boolean autocommit = true;
/**
* In-transaction flag.
* Can be true only when autocommit false.
*/
protected boolean intrans = false;
/**
* Timeout for Database.exec()
*/
protected int timeout = 1000000;
/**
* Use double/julian date representation.
*/
protected boolean useJulian = false;
/**
* File name of database.
*/
private String dbfile = null;
/**
* Reference to meta data or null.
*/
private JDBCDatabaseMetaData meta = null;
/**
* Base time value for timeout handling.
*/
private long t0;
/**
* Database in readonly mode.
*/
private boolean readonly = false;
/**
* Transaction isolation mode.
*/
private int trmode = TRANSACTION_SERIALIZABLE;
private boolean busy0(DatabaseX db, int count) {
if (count <= 1) {
t0 = System.currentTimeMillis();
}
if (db != null) {
long t1 = System.currentTimeMillis();
if (t1 - t0 > timeout) {
return false;
}
db.wait(100);
return true;
}
return false;
}
public boolean busy(String table, int count) {
return busy0(db, count);
}
protected boolean busy3(DatabaseX db, int count) {
if (count <= 1) {
t0 = System.currentTimeMillis();
}
if (db != null) {
long t1 = System.currentTimeMillis();
if (t1 - t0 > timeout) {
return false;
}
return true;
}
return false;
}
private DatabaseX open(boolean readonly) throws SQLException {
DatabaseX dbx = null;
try {
dbx = new DatabaseX();
dbx.open(dbfile, readonly ? jsqlite.Constants.SQLITE_OPEN_READONLY :
(jsqlite.Constants.SQLITE_OPEN_READWRITE |
jsqlite.Constants.SQLITE_OPEN_CREATE), vfs);
dbx.set_encoding(enc);
} catch (jsqlite.Exception e) {
throw new SQLException(e.toString());
}
int loop = 0;
while (true) {
try {
dbx.exec("PRAGMA short_column_names = off;", null);
dbx.exec("PRAGMA full_column_names = on;", null);
dbx.exec("PRAGMA empty_result_callbacks = on;", null);
if (jsqlite.Database.version().compareTo("2.6.0") >= 0) {
dbx.exec("PRAGMA show_datatypes = on;", null);
}
} catch (jsqlite.Exception e) {
if (dbx.last_error() != jsqlite.Constants.SQLITE_BUSY ||
!busy0(dbx, ++loop)) {
try {
dbx.close();
} catch (jsqlite.Exception ee) {
}
throw new SQLException(e.toString());
}
continue;
}
break;
}
return dbx;
}
public JDBCConnection(String url, String enc, String pwd, String drep,
String vfs)
throws SQLException {
if (url.startsWith("jsqlite:/")) {
dbfile = url.substring(8);
} else if (url.startsWith("jdbc:jsqlite:/")) {
dbfile = url.substring(13);
} else {
throw new SQLException("unsupported url");
}
this.url = url;
this.enc = enc;
this.vfs = vfs;
try {
db = open(readonly);
try {
if (pwd != null && pwd.length() > 0) {
db.key(pwd);
}
} catch (jsqlite.Exception se) {
throw new SQLException("error while setting key");
}
db.busy_handler(this);
} catch (SQLException e) {
if (db != null) {
try {
db.close();
} catch (jsqlite.Exception ee) {
}
}
throw e;
}
useJulian = drep != null &&
(drep.startsWith("j") || drep.startsWith("J"));
}
/* non-standard */
public jsqlite.Database getSQLiteDatabase() {
return (jsqlite.Database) db;
}
public Statement createStatement() {
JDBCStatement s = new JDBCStatement(this);
return s;
}
public Statement createStatement(int resultSetType,
int resultSetConcurrency)
throws SQLException {
if (resultSetType != ResultSet.TYPE_FORWARD_ONLY &&
resultSetType != ResultSet.TYPE_SCROLL_INSENSITIVE &&
resultSetType != ResultSet.TYPE_SCROLL_SENSITIVE) {
throw new SQLFeatureNotSupportedException("unsupported result set type");
}
if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY &&
resultSetConcurrency != ResultSet.CONCUR_UPDATABLE) {
throw new SQLFeatureNotSupportedException("unsupported result set concurrency");
}
JDBCStatement s = new JDBCStatement(this);
return s;
}
public DatabaseMetaData getMetaData() throws SQLException {
if (meta == null) {
meta = new JDBCDatabaseMetaData(this);
}
return meta;
}
public void close() throws SQLException {
try {
rollback();
} catch (SQLException e) {
/* ignored */
}
intrans = false;
if (db != null) {
try {
db.close();
db = null;
} catch (jsqlite.Exception e) {
throw new SQLException(e.toString());
}
}
}
public boolean isClosed() throws SQLException {
return db == null;
}
public boolean isReadOnly() throws SQLException {
return readonly;
}
public void clearWarnings() throws SQLException {
}
public void commit() throws SQLException {
if (db == null) {
throw new SQLException("stale connection");
}
if (!intrans) {
return;
}
try {
db.exec("COMMIT", null);
intrans = false;
} catch (jsqlite.Exception e) {
throw new SQLException(e.toString());
}
}
public boolean getAutoCommit() throws SQLException {
return autocommit;
}
public String getCatalog() throws SQLException {
return null;
}
public int getTransactionIsolation() throws SQLException {
return trmode;
}
public SQLWarning getWarnings() throws SQLException {
return null;
}
public String nativeSQL(String sql) throws SQLException {
throw new SQLException("not supported");
}
public CallableStatement prepareCall(String sql) throws SQLException {
throw new SQLException("not supported");
}
public CallableStatement prepareCall(String sql, int x, int y)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public PreparedStatement prepareStatement(String sql) throws SQLException {
JDBCPreparedStatement s = new JDBCPreparedStatement(this, sql);
return s;
}
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency)
throws SQLException {
if (resultSetType != ResultSet.TYPE_FORWARD_ONLY &&
resultSetType != ResultSet.TYPE_SCROLL_INSENSITIVE &&
resultSetType != ResultSet.TYPE_SCROLL_SENSITIVE) {
throw new SQLFeatureNotSupportedException("unsupported result set type");
}
if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY &&
resultSetConcurrency != ResultSet.CONCUR_UPDATABLE) {
throw new SQLFeatureNotSupportedException("unsupported result set concurrency");
}
JDBCPreparedStatement s = new JDBCPreparedStatement(this, sql);
return s;
}
public void rollback() throws SQLException {
if (db == null) {
throw new SQLException("stale connection");
}
if (!intrans) {
return;
}
try {
db.exec("ROLLBACK", null);
intrans = false;
} catch (jsqlite.Exception e) {
throw new SQLException(e.toString());
}
}
public void setAutoCommit(boolean ac) throws SQLException {
if (ac && intrans && db != null) {
try {
db.exec("ROLLBACK", null);
} catch (jsqlite.Exception e) {
throw new SQLException(e.toString());
} finally {
intrans = false;
}
}
autocommit = ac;
}
public void setCatalog(String catalog) throws SQLException {
}
public void setReadOnly(boolean ro) throws SQLException {
if (intrans) {
throw new SQLException("incomplete transaction");
}
if (ro != readonly) {
DatabaseX dbx = null;
try {
dbx = open(ro);
db.close();
db = dbx;
dbx = null;
readonly = ro;
} catch (SQLException e) {
throw e;
} catch (jsqlite.Exception ee) {
if (dbx != null) {
try {
dbx.close();
} catch (jsqlite.Exception eee) {
}
}
throw new SQLException(ee.toString());
}
}
}
public void setTransactionIsolation(int level) throws SQLException {
if (db.is3() && jsqlite.JDBCDriver.sharedCache) {
String flag = null;
if (level == TRANSACTION_READ_UNCOMMITTED &&
trmode != TRANSACTION_READ_UNCOMMITTED) {
flag = "on";
} else if (level == TRANSACTION_SERIALIZABLE &&
trmode != TRANSACTION_SERIALIZABLE) {
flag = "off";
}
if (flag != null) {
try {
db.exec("PRAGMA read_uncommitted = " + flag + ";", null);
trmode = level;
} catch (java.lang.Exception e) {
}
}
}
if (level != trmode) {
throw new SQLException("not supported");
}
}
public java.util.Map<String, Class<?>> getTypeMap() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setTypeMap(java.util.Map map) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public int getHoldability() throws SQLException {
return ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
public void setHoldability(int holdability) throws SQLException {
if (holdability == ResultSet.HOLD_CURSORS_OVER_COMMIT) {
return;
}
throw new SQLFeatureNotSupportedException("unsupported holdability");
}
public Savepoint setSavepoint() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public Savepoint setSavepoint(String name) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void rollback(Savepoint x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void releaseSavepoint(Savepoint x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public Statement createStatement(int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
throws SQLException {
if (resultSetHoldability != ResultSet.HOLD_CURSORS_OVER_COMMIT) {
throw new SQLFeatureNotSupportedException("unsupported holdability");
}
return createStatement(resultSetType, resultSetConcurrency);
}
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency,
int resultSetHoldability)
throws SQLException {
if (resultSetHoldability != ResultSet.HOLD_CURSORS_OVER_COMMIT) {
throw new SQLFeatureNotSupportedException("unsupported holdability");
}
return prepareStatement(sql, resultSetType, resultSetConcurrency);
}
public CallableStatement prepareCall(String sql, int x, int y, int z)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public PreparedStatement prepareStatement(String sql, int autokeys)
throws SQLException {
if (autokeys != Statement.NO_GENERATED_KEYS) {
throw new SQLFeatureNotSupportedException("generated keys not supported");
}
return prepareStatement(sql);
}
public PreparedStatement prepareStatement(String sql, int colIndexes[])
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public PreparedStatement prepareStatement(String sql, String columns[])
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public Clob createClob() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public Blob createBlob() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public NClob createNClob() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public SQLXML createSQLXML() throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public boolean isValid(int timeout) throws SQLException {
return true;
}
public void setClientInfo(String name, String value)
throws SQLClientInfoException {
throw new SQLClientInfoException();
}
public void setClientInfo(Properties prop) throws SQLClientInfoException {
throw new SQLClientInfoException();
}
public String getClientInfo(String name) throws SQLException {
throw new SQLException("unsupported");
}
public Properties getClientInfo() throws SQLException {
return new Properties();
}
public Array createArrayOf(String type, Object[] elems)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public Struct createStruct(String type, Object[] attrs)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public <T> T unwrap(java.lang.Class<T> iface) throws SQLException {
throw new SQLException("unsupported");
}
public boolean isWrapperFor(java.lang.Class iface) throws SQLException {
return false;
}
}
class DatabaseX extends jsqlite.Database {
static Object lock = new Object();
public DatabaseX() {
super();
}
void wait(int ms) {
try {
synchronized (lock) {
lock.wait(ms);
}
} catch (java.lang.Exception e) {
}
}
public void exec(String sql, jsqlite.Callback cb)
throws jsqlite.Exception {
super.exec(sql, cb);
synchronized (lock) {
lock.notifyAll();
}
}
public void exec(String sql, jsqlite.Callback cb, String args[])
throws jsqlite.Exception {
super.exec(sql, cb, args);
synchronized (lock) {
lock.notifyAll();
}
}
public jsqlite.TableResult get_table(String sql, String args[])
throws jsqlite.Exception {
jsqlite.TableResult ret = super.get_table(sql, args);
synchronized (lock) {
lock.notifyAll();
}
return ret;
}
public void get_table(String sql, String args[], jsqlite.TableResult tbl)
throws jsqlite.Exception {
super.get_table(sql, args, tbl);
synchronized (lock) {
lock.notifyAll();
}
}
}
| Java |
package jsqlite.JDBC2z;
import java.sql.Types;
import java.util.Vector;
public class TableResultX extends jsqlite.TableResult {
public int sql_type[];
public TableResultX() {
super();
sql_type = new int[this.ncolumns];
for (int i = 0; i < this.ncolumns; i++) {
sql_type[i] = Types.VARCHAR;
}
}
public TableResultX(int maxrows) {
super(maxrows);
sql_type = new int[this.ncolumns];
for (int i = 0; i < this.ncolumns; i++) {
sql_type[i] = Types.VARCHAR;
}
}
public TableResultX(jsqlite.TableResult tr) {
this.column = tr.column;
this.rows = tr.rows;
this.ncolumns = tr.ncolumns;
this.nrows = tr.nrows;
this.types = tr.types;
this.maxrows = tr.maxrows;
sql_type = new int[tr.ncolumns];
for (int i = 0; i < this.ncolumns; i++) {
sql_type[i] = Types.VARCHAR;
}
if (tr.types != null) {
for (int i = 0; i < tr.types.length; i++) {
sql_type[i] = JDBCDatabaseMetaData.mapSqlType(tr.types[i]);
}
}
}
void sql_types(int types[]) {
sql_type = types;
}
}
| Java |
package jsqlite.JDBC2z;
import java.sql.*;
import java.math.BigDecimal;
import java.util.*;
class BatchArg {
String arg;
boolean blob;
BatchArg(String arg, boolean blob) {
if (arg == null) {
this.arg = null;
} else {
this.arg = new String(arg);
}
this.blob = blob;
}
}
public class JDBCPreparedStatement extends JDBCStatement
implements java.sql.PreparedStatement {
private String sql;
private String args[];
private boolean blobs[];
private ArrayList<BatchArg> batch;
private static final boolean nullrepl =
jsqlite.Database.version().compareTo("2.5.0") < 0;
public JDBCPreparedStatement(JDBCConnection conn, String sql) {
super(conn);
this.args = null;
this.blobs = null;
this.batch = null;
this.sql = fixup(sql);
}
private String fixup(String sql) {
StringBuffer sb = new StringBuffer();
boolean inq = false;
int nparm = 0;
for (int i = 0; i < sql.length(); i++) {
char c = sql.charAt(i);
if (c == '\'') {
if (inq) {
char nextChar = 0;
if(i + 1 < sql.length()) {
nextChar = sql.charAt(i + 1);
}
if (nextChar == '\'') {
sb.append(c);
sb.append(nextChar);
i++;
} else {
inq = false;
sb.append(c);
}
} else {
inq = true;
sb.append(c);
}
} else if (c == '?') {
if (inq) {
sb.append(c);
} else {
++nparm;
sb.append(nullrepl ? "'%q'" : "%Q");
}
} else if (c == ';') {
if (!inq) {
break;
}
sb.append(c);
} else if (c == '%') {
sb.append("%%");
} else {
sb.append(c);
}
}
args = new String[nparm];
blobs = new boolean[nparm];
try {
clearParameters();
} catch (SQLException e) {
}
return sb.toString();
}
private String fixup2(String sql) {
if (!conn.db.is3()) {
return sql;
}
StringBuffer sb = new StringBuffer();
int parm = -1;
for (int i = 0; i < sql.length(); i++) {
char c = sql.charAt(i);
if (c == '%') {
sb.append(c);
++i;
c = sql.charAt(i);
if (c == 'Q') {
parm++;
if (blobs[parm]) {
c = 's';
}
}
}
sb.append(c);
}
return sb.toString();
}
public ResultSet executeQuery() throws SQLException {
return executeQuery(fixup2(sql), args, false);
}
public int executeUpdate() throws SQLException {
executeQuery(fixup2(sql), args, true);
return updcnt;
}
public void setNull(int parameterIndex, int sqlType) throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
args[parameterIndex - 1] = nullrepl ? "" : null;
blobs[parameterIndex - 1] = false;
}
public void setBoolean(int parameterIndex, boolean x)
throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
args[parameterIndex - 1] = x ? "1" : "0";
blobs[parameterIndex - 1] = false;
}
public void setByte(int parameterIndex, byte x) throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
args[parameterIndex - 1] = "" + x;
blobs[parameterIndex - 1] = false;
}
public void setShort(int parameterIndex, short x) throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
args[parameterIndex - 1] = "" + x;
blobs[parameterIndex - 1] = false;
}
public void setInt(int parameterIndex, int x) throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
args[parameterIndex - 1] = "" + x;
blobs[parameterIndex - 1] = false;
}
public void setLong(int parameterIndex, long x) throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
args[parameterIndex - 1] = "" + x;
blobs[parameterIndex - 1] = false;
}
public void setFloat(int parameterIndex, float x) throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
args[parameterIndex - 1] = "" + x;
blobs[parameterIndex - 1] = false;
}
public void setDouble(int parameterIndex, double x) throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
args[parameterIndex - 1] = "" + x;
blobs[parameterIndex - 1] = false;
}
public void setBigDecimal(int parameterIndex, BigDecimal x)
throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
if (x == null) {
args[parameterIndex - 1] = nullrepl ? "" : null;
} else {
args[parameterIndex - 1] = "" + x;
}
blobs[parameterIndex - 1] = false;
}
public void setString(int parameterIndex, String x) throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
if (x == null) {
args[parameterIndex - 1] = nullrepl ? "" : null;
} else {
args[parameterIndex - 1] = x;
}
blobs[parameterIndex - 1] = false;
}
public void setBytes(int parameterIndex, byte x[]) throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
blobs[parameterIndex - 1] = false;
if (x == null) {
args[parameterIndex - 1] = nullrepl ? "" : null;
} else {
if (conn.db.is3()) {
args[parameterIndex - 1] = jsqlite.StringEncoder.encodeX(x);
blobs[parameterIndex - 1] = true;
} else {
args[parameterIndex - 1] = jsqlite.StringEncoder.encode(x);
}
}
}
public void setDate(int parameterIndex, java.sql.Date x)
throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
if (x == null) {
args[parameterIndex - 1] = nullrepl ? "" : null;
} else {
if (conn.useJulian) {
args[parameterIndex - 1] = java.lang.Double.toString(jsqlite.Database.julian_from_long(x.getTime()));
} else {
args[parameterIndex - 1] = x.toString();
}
}
blobs[parameterIndex - 1] = false;
}
public void setTime(int parameterIndex, java.sql.Time x)
throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
if (x == null) {
args[parameterIndex - 1] = nullrepl ? "" : null;
} else {
if (conn.useJulian) {
args[parameterIndex - 1] = java.lang.Double.toString(jsqlite.Database.julian_from_long(x.getTime()));
} else {
args[parameterIndex - 1] = x.toString();
}
}
blobs[parameterIndex - 1] = false;
}
public void setTimestamp(int parameterIndex, java.sql.Timestamp x)
throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
if (x == null) {
args[parameterIndex - 1] = nullrepl ? "" : null;
} else {
if (conn.useJulian) {
args[parameterIndex - 1] = java.lang.Double.toString(jsqlite.Database.julian_from_long(x.getTime()));
} else {
args[parameterIndex - 1] = x.toString();
}
}
blobs[parameterIndex - 1] = false;
}
public void setAsciiStream(int parameterIndex, java.io.InputStream x,
int length) throws SQLException {
throw new SQLException("not supported");
}
@Deprecated
public void setUnicodeStream(int parameterIndex, java.io.InputStream x,
int length) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setBinaryStream(int parameterIndex, java.io.InputStream x,
int length) throws SQLException {
try {
byte[] data = new byte[length];
x.read(data, 0, length);
setBytes(parameterIndex, data);
} catch (java.io.IOException e) {
throw new SQLException("I/O failed");
}
}
public void clearParameters() throws SQLException {
for (int i = 0; i < args.length; i++) {
args[i] = nullrepl ? "" : null;
blobs[i] = false;
}
}
public void setObject(int parameterIndex, Object x, int targetSqlType,
int scale) throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
if (x == null) {
args[parameterIndex - 1] = nullrepl ? "" : null;
} else {
if (x instanceof byte[]) {
byte[] bx = (byte[]) x;
if (conn.db.is3()) {
args[parameterIndex - 1] =
jsqlite.StringEncoder.encodeX(bx);
blobs[parameterIndex - 1] = true;
return;
}
args[parameterIndex - 1] = jsqlite.StringEncoder.encode(bx);
} else {
args[parameterIndex - 1] = x.toString();
}
}
blobs[parameterIndex - 1] = false;
}
public void setObject(int parameterIndex, Object x, int targetSqlType)
throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
if (x == null) {
args[parameterIndex - 1] = nullrepl ? "" : null;
} else {
if (x instanceof byte[]) {
byte[] bx = (byte[]) x;
if (conn.db.is3()) {
args[parameterIndex - 1] =
jsqlite.StringEncoder.encodeX(bx);
blobs[parameterIndex - 1] = true;
return;
}
args[parameterIndex - 1] = jsqlite.StringEncoder.encode(bx);
} else {
args[parameterIndex - 1] = x.toString();
}
}
blobs[parameterIndex - 1] = false;
}
public void setObject(int parameterIndex, Object x) throws SQLException {
if (parameterIndex < 1 || parameterIndex > args.length) {
throw new SQLException("bad parameter index");
}
if (x == null) {
args[parameterIndex - 1] = nullrepl ? "" : null;
} else {
if (x instanceof byte[]) {
byte[] bx = (byte[]) x;
if (conn.db.is3()) {
args[parameterIndex - 1] =
jsqlite.StringEncoder.encodeX(bx);
blobs[parameterIndex - 1] = true;
return;
}
args[parameterIndex - 1] = jsqlite.StringEncoder.encode(bx);
} else {
args[parameterIndex - 1] = x.toString();
}
}
blobs[parameterIndex - 1] = false;
}
public boolean execute() throws SQLException {
return executeQuery(fixup2(sql), args, false) != null;
}
public void addBatch() throws SQLException {
if (batch == null) {
batch = new ArrayList<BatchArg>(args.length);
}
for (int i = 0; i < args.length; i++) {
batch.add(new BatchArg(args[i], blobs[i]));
}
}
public int[] executeBatch() throws SQLException {
if (batch == null) {
return new int[0];
}
int[] ret = new int[batch.size() / args.length];
for (int i = 0; i < ret.length; i++) {
ret[i] = EXECUTE_FAILED;
}
int errs = 0;
int index = 0;
for (int i = 0; i < ret.length; i++) {
for (int k = 0; k < args.length; k++) {
BatchArg b = (BatchArg) batch.get(index++);
args[k] = b.arg;
blobs[k] = b.blob;
}
try {
ret[i] = executeUpdate();
} catch (SQLException e) {
++errs;
}
}
if (errs > 0) {
throw new BatchUpdateException("batch failed", ret);
}
return ret;
}
public void clearBatch() throws SQLException {
if (batch != null) {
batch.clear();
batch = null;
}
}
public void close() throws SQLException {
clearBatch();
super.close();
}
public void setCharacterStream(int parameterIndex,
java.io.Reader reader,
int length) throws SQLException {
try {
char[] data = new char[length];
reader.read(data);
setString(parameterIndex, new String(data));
} catch (java.io.IOException e) {
throw new SQLException("I/O failed");
}
}
public void setRef(int i, Ref x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setBlob(int i, Blob x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setClob(int i, Clob x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setArray(int i, Array x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public ResultSetMetaData getMetaData() throws SQLException {
return rs.getMetaData();
}
public void setDate(int parameterIndex, java.sql.Date x, Calendar cal)
throws SQLException {
setDate(parameterIndex, x);
}
public void setTime(int parameterIndex, java.sql.Time x, Calendar cal)
throws SQLException {
setTime(parameterIndex, x);
}
public void setTimestamp(int parameterIndex, java.sql.Timestamp x,
Calendar cal) throws SQLException {
setTimestamp(parameterIndex, x);
}
public void setNull(int parameterIndex, int sqlType, String typeName)
throws SQLException {
setNull(parameterIndex, sqlType);
}
public ParameterMetaData getParameterMetaData() throws SQLException {
throw new SQLException("not supported");
}
public void registerOutputParameter(String parameterName, int sqlType)
throws SQLException {
throw new SQLException("not supported");
}
public void registerOutputParameter(String parameterName, int sqlType,
int scale)
throws SQLException {
throw new SQLException("not supported");
}
public void registerOutputParameter(String parameterName, int sqlType,
String typeName)
throws SQLException {
throw new SQLException("not supported");
}
public java.net.URL getURL(int parameterIndex) throws SQLException {
throw new SQLException("not supported");
}
public void setURL(int parameterIndex, java.net.URL url)
throws SQLException {
throw new SQLException("not supported");
}
public void setNull(String parameterName, int sqlType)
throws SQLException {
throw new SQLException("not supported");
}
public void setBoolean(String parameterName, boolean val)
throws SQLException {
throw new SQLException("not supported");
}
public void setByte(String parameterName, byte val)
throws SQLException {
throw new SQLException("not supported");
}
public void setShort(String parameterName, short val)
throws SQLException {
throw new SQLException("not supported");
}
public void setInt(String parameterName, int val)
throws SQLException {
throw new SQLException("not supported");
}
public void setLong(String parameterName, long val)
throws SQLException {
throw new SQLException("not supported");
}
public void setFloat(String parameterName, float val)
throws SQLException {
throw new SQLException("not supported");
}
public void setDouble(String parameterName, double val)
throws SQLException {
throw new SQLException("not supported");
}
public void setBigDecimal(String parameterName, BigDecimal val)
throws SQLException {
throw new SQLException("not supported");
}
public void setString(String parameterName, String val)
throws SQLException {
throw new SQLException("not supported");
}
public void setBytes(String parameterName, byte val[])
throws SQLException {
throw new SQLException("not supported");
}
public void setDate(String parameterName, java.sql.Date val)
throws SQLException {
throw new SQLException("not supported");
}
public void setTime(String parameterName, java.sql.Time val)
throws SQLException {
throw new SQLException("not supported");
}
public void setTimestamp(String parameterName, java.sql.Timestamp val)
throws SQLException {
throw new SQLException("not supported");
}
public void setAsciiStream(String parameterName,
java.io.InputStream s, int length)
throws SQLException {
throw new SQLException("not supported");
}
public void setBinaryStream(String parameterName,
java.io.InputStream s, int length)
throws SQLException {
throw new SQLException("not supported");
}
public void setObject(String parameterName, Object val, int targetSqlType,
int scale)
throws SQLException {
throw new SQLException("not supported");
}
public void setObject(String parameterName, Object val, int targetSqlType)
throws SQLException {
throw new SQLException("not supported");
}
public void setObject(String parameterName, Object val)
throws SQLException {
throw new SQLException("not supported");
}
public void setCharacterStream(String parameterName,
java.io.Reader r, int length)
throws SQLException {
throw new SQLException("not supported");
}
public void setDate(String parameterName, java.sql.Date val,
Calendar cal)
throws SQLException {
throw new SQLException("not supported");
}
public void setTime(String parameterName, java.sql.Time val,
Calendar cal)
throws SQLException {
throw new SQLException("not supported");
}
public void setTimestamp(String parameterName, java.sql.Timestamp val,
Calendar cal)
throws SQLException {
throw new SQLException("not supported");
}
public void setNull(String parameterName, int sqlType, String typeName)
throws SQLException {
throw new SQLException("not supported");
}
public String getString(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public boolean getBoolean(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public byte getByte(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public short getShort(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public int getInt(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public long getLong(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public float getFloat(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public double getDouble(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public byte[] getBytes(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public java.sql.Date getDate(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public java.sql.Time getTime(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public java.sql.Timestamp getTimestamp(String parameterName)
throws SQLException {
throw new SQLException("not supported");
}
public Object getObject(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public Object getObject(int parameterIndex) throws SQLException {
throw new SQLException("not supported");
}
public BigDecimal getBigDecimal(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public Object getObject(String parameterName, Map map)
throws SQLException {
throw new SQLException("not supported");
}
public Object getObject(int parameterIndex, Map map)
throws SQLException {
throw new SQLException("not supported");
}
public Ref getRef(int parameterIndex) throws SQLException {
throw new SQLException("not supported");
}
public Ref getRef(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public Blob getBlob(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public Blob getBlob(int parameterIndex) throws SQLException {
throw new SQLException("not supported");
}
public Clob getClob(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public Clob getClob(int parameterIndex) throws SQLException {
throw new SQLException("not supported");
}
public Array getArray(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public Array getArray(int parameterIndex) throws SQLException {
throw new SQLException("not supported");
}
public java.sql.Date getDate(String parameterName, Calendar cal)
throws SQLException {
throw new SQLException("not supported");
}
public java.sql.Date getDate(int parameterIndex, Calendar cal)
throws SQLException {
throw new SQLException("not supported");
}
public java.sql.Time getTime(String parameterName, Calendar cal)
throws SQLException {
throw new SQLException("not supported");
}
public java.sql.Time getTime(int parameterIndex, Calendar cal)
throws SQLException {
throw new SQLException("not supported");
}
public java.sql.Timestamp getTimestamp(String parameterName, Calendar cal)
throws SQLException {
throw new SQLException("not supported");
}
public java.sql.Timestamp getTimestamp(int parameterIndex, Calendar cal)
throws SQLException {
throw new SQLException("not supported");
}
public java.net.URL getURL(String parameterName) throws SQLException {
throw new SQLException("not supported");
}
public void setRowId(int parameterIndex, RowId x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setRowId(String parameterName, RowId x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNString(int parameterIndex, String value)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNString(String parameterName, String value)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNCharacterStream(int parameterIndex, java.io.Reader x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNCharacterStream(String parameterName, java.io.Reader x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNClob(int parameterIndex, NClob value)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNClob(String parameterName, NClob value)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setClob(int parameterIndex, java.io.Reader x, long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setClob(String parameterName, java.io.Reader x, long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setBlob(int parameterIndex, java.io.InputStream x, long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setBlob(String parameterName, java.io.InputStream x, long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNClob(int parameterIndex, java.io.Reader x, long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNClob(String parameterName, java.io.Reader x, long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setSQLXML(int parameterIndex, SQLXML xml)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setSQLXML(String parameterName, SQLXML xml)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setAsciiStream(int parameterIndex, java.io.InputStream x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setAsciiStream(String parameterName, java.io.InputStream x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setBinaryStream(int parameterIndex, java.io.InputStream x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setBinaryStream(String parameterName, java.io.InputStream x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setCharacterStream(int parameterIndex, java.io.Reader x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setCharacterStream(String parameterName, java.io.Reader x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setAsciiStream(int parameterIndex, java.io.InputStream x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setAsciiStream(String parameterName, java.io.InputStream x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setBinaryStream(int parameterIndex, java.io.InputStream x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setBinaryStream(String parameterName, java.io.InputStream x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setCharacterStream(int parameterIndex, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setCharacterStream(String parameterName, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNCharacterStream(int parameterIndex, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNCharacterStream(String parameterName, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setClob(int parameterIndex, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setClob(String parameterName, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setBlob(int parameterIndex, java.io.InputStream x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setBlob(String parameterName, java.io.InputStream x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNClob(int parameterIndex, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void setNClob(String parameterName, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
}
| Java |
package jsqlite.JDBC2z;
import java.sql.*;
import java.util.Hashtable;
public class JDBCDatabaseMetaData implements DatabaseMetaData {
private JDBCConnection conn;
public JDBCDatabaseMetaData(JDBCConnection conn) {
this.conn = conn;
}
public boolean allProceduresAreCallable() throws SQLException {
return false;
}
public boolean allTablesAreSelectable() throws SQLException {
return true;
}
public String getURL() throws SQLException {
return conn.url;
}
public String getUserName() throws SQLException {
return "";
}
public boolean isReadOnly() throws SQLException {
return false;
}
public boolean nullsAreSortedHigh() throws SQLException {
return false;
}
public boolean nullsAreSortedLow() throws SQLException {
return false;
}
public boolean nullsAreSortedAtStart() throws SQLException {
return false;
}
public boolean nullsAreSortedAtEnd() throws SQLException {
return false;
}
public String getDatabaseProductName() throws SQLException {
return "SQLite";
}
public String getDatabaseProductVersion() throws SQLException {
return jsqlite.Database.version();
}
public String getDriverName() throws SQLException {
return "SQLite/JDBC";
}
public String getDriverVersion() throws SQLException {
return "" + jsqlite.JDBCDriver.MAJORVERSION + "." +
jsqlite.Constants.drv_minor;
}
public int getDriverMajorVersion() {
return jsqlite.JDBCDriver.MAJORVERSION;
}
public int getDriverMinorVersion() {
return jsqlite.Constants.drv_minor;
}
public boolean usesLocalFiles() throws SQLException {
return true;
}
public boolean usesLocalFilePerTable() throws SQLException {
return false;
}
public boolean supportsMixedCaseIdentifiers() throws SQLException {
return false;
}
public boolean storesUpperCaseIdentifiers() throws SQLException {
return false;
}
public boolean storesLowerCaseIdentifiers() throws SQLException {
return false;
}
public boolean storesMixedCaseIdentifiers() throws SQLException {
return true;
}
public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException {
return false;
}
public boolean storesUpperCaseQuotedIdentifiers() throws SQLException {
return false;
}
public boolean storesLowerCaseQuotedIdentifiers() throws SQLException {
return false;
}
public boolean storesMixedCaseQuotedIdentifiers() throws SQLException {
return true;
}
public String getIdentifierQuoteString() throws SQLException {
return "\"";
}
public String getSQLKeywords() throws SQLException {
return "SELECT,UPDATE,CREATE,TABLE,VIEW,DELETE,FROM,WHERE" +
",COMMIT,ROLLBACK,TRIGGER";
}
public String getNumericFunctions() throws SQLException {
return "";
}
public String getStringFunctions() throws SQLException {
return "";
}
public String getSystemFunctions() throws SQLException {
return "";
}
public String getTimeDateFunctions() throws SQLException {
return "";
}
public String getSearchStringEscape() throws SQLException {
return "\\";
}
public String getExtraNameCharacters() throws SQLException {
return "";
}
public boolean supportsAlterTableWithAddColumn() throws SQLException {
return false;
}
public boolean supportsAlterTableWithDropColumn() throws SQLException {
return false;
}
public boolean supportsColumnAliasing() throws SQLException {
return true;
}
public boolean nullPlusNonNullIsNull() throws SQLException {
return false;
}
public boolean supportsConvert() throws SQLException {
return false;
}
public boolean supportsConvert(int fromType, int toType)
throws SQLException {
return false;
}
public boolean supportsTableCorrelationNames() throws SQLException {
return true;
}
public boolean supportsDifferentTableCorrelationNames()
throws SQLException {
return false;
}
public boolean supportsExpressionsInOrderBy() throws SQLException {
return true;
}
public boolean supportsOrderByUnrelated() throws SQLException {
return true;
}
public boolean supportsGroupBy() throws SQLException {
return true;
}
public boolean supportsGroupByUnrelated() throws SQLException {
return true;
}
public boolean supportsGroupByBeyondSelect() throws SQLException {
return false;
}
public boolean supportsLikeEscapeClause() throws SQLException {
return false;
}
public boolean supportsMultipleResultSets() throws SQLException {
return false;
}
public boolean supportsMultipleTransactions() throws SQLException {
return false;
}
public boolean supportsNonNullableColumns() throws SQLException {
return true;
}
public boolean supportsMinimumSQLGrammar() throws SQLException {
return true;
}
public boolean supportsCoreSQLGrammar() throws SQLException {
return false;
}
public boolean supportsExtendedSQLGrammar() throws SQLException {
return false;
}
public boolean supportsANSI92EntryLevelSQL() throws SQLException {
return true;
}
public boolean supportsANSI92IntermediateSQL() throws SQLException {
return false;
}
public boolean supportsANSI92FullSQL() throws SQLException {
return false;
}
public boolean supportsIntegrityEnhancementFacility()
throws SQLException {
return false;
}
public boolean supportsOuterJoins() throws SQLException {
return false;
}
public boolean supportsFullOuterJoins() throws SQLException {
return false;
}
public boolean supportsLimitedOuterJoins() throws SQLException {
return false;
}
public String getSchemaTerm() throws SQLException {
return "";
}
public String getProcedureTerm() throws SQLException {
return "";
}
public String getCatalogTerm() throws SQLException {
return "";
}
public boolean isCatalogAtStart() throws SQLException {
return false;
}
public String getCatalogSeparator() throws SQLException {
return "";
}
public boolean supportsSchemasInDataManipulation() throws SQLException {
return false;
}
public boolean supportsSchemasInProcedureCalls() throws SQLException {
return false;
}
public boolean supportsSchemasInTableDefinitions() throws SQLException {
return false;
}
public boolean supportsSchemasInIndexDefinitions() throws SQLException {
return false;
}
public boolean supportsSchemasInPrivilegeDefinitions()
throws SQLException {
return false;
}
public boolean supportsCatalogsInDataManipulation() throws SQLException {
return false;
}
public boolean supportsCatalogsInProcedureCalls() throws SQLException {
return false;
}
public boolean supportsCatalogsInTableDefinitions() throws SQLException {
return false;
}
public boolean supportsCatalogsInIndexDefinitions() throws SQLException {
return false;
}
public boolean supportsCatalogsInPrivilegeDefinitions()
throws SQLException {
return false;
}
public boolean supportsPositionedDelete() throws SQLException {
return false;
}
public boolean supportsPositionedUpdate() throws SQLException {
return false;
}
public boolean supportsSelectForUpdate() throws SQLException {
return false;
}
public boolean supportsStoredProcedures() throws SQLException {
return false;
}
public boolean supportsSubqueriesInComparisons() throws SQLException {
return true;
}
public boolean supportsSubqueriesInExists() throws SQLException {
return true;
}
public boolean supportsSubqueriesInIns() throws SQLException {
return true;
}
public boolean supportsSubqueriesInQuantifieds() throws SQLException {
return false;
}
public boolean supportsCorrelatedSubqueries() throws SQLException {
return false;
}
public boolean supportsUnion() throws SQLException {
return true;
}
public boolean supportsUnionAll() throws SQLException {
return true;
}
public boolean supportsOpenCursorsAcrossCommit() throws SQLException {
return false;
}
public boolean supportsOpenCursorsAcrossRollback() throws SQLException {
return false;
}
public boolean supportsOpenStatementsAcrossCommit() throws SQLException {
return false;
}
public boolean supportsOpenStatementsAcrossRollback() throws SQLException {
return false;
}
public int getMaxBinaryLiteralLength() throws SQLException {
return 0;
}
public int getMaxCharLiteralLength() throws SQLException {
return 0;
}
public int getMaxColumnNameLength() throws SQLException {
return 0;
}
public int getMaxColumnsInGroupBy() throws SQLException {
return 0;
}
public int getMaxColumnsInIndex() throws SQLException {
return 0;
}
public int getMaxColumnsInOrderBy() throws SQLException {
return 0;
}
public int getMaxColumnsInSelect() throws SQLException {
return 0;
}
public int getMaxColumnsInTable() throws SQLException {
return 0;
}
public int getMaxConnections() throws SQLException {
return 0;
}
public int getMaxCursorNameLength() throws SQLException {
return 8;
}
public int getMaxIndexLength() throws SQLException {
return 0;
}
public int getMaxSchemaNameLength() throws SQLException {
return 0;
}
public int getMaxProcedureNameLength() throws SQLException {
return 0;
}
public int getMaxCatalogNameLength() throws SQLException {
return 0;
}
public int getMaxRowSize() throws SQLException {
return 0;
}
public boolean doesMaxRowSizeIncludeBlobs() throws SQLException {
return true;
}
public int getMaxStatementLength() throws SQLException {
return 0;
}
public int getMaxStatements() throws SQLException {
return 0;
}
public int getMaxTableNameLength() throws SQLException {
return 0;
}
public int getMaxTablesInSelect() throws SQLException {
return 0;
}
public int getMaxUserNameLength() throws SQLException {
return 0;
}
public int getDefaultTransactionIsolation() throws SQLException {
return Connection.TRANSACTION_SERIALIZABLE;
}
public boolean supportsTransactions() throws SQLException {
return true;
}
public boolean supportsTransactionIsolationLevel(int level)
throws SQLException {
return level == Connection.TRANSACTION_SERIALIZABLE;
}
public boolean supportsDataDefinitionAndDataManipulationTransactions()
throws SQLException {
return true;
}
public boolean supportsDataManipulationTransactionsOnly()
throws SQLException {
return false;
}
public boolean dataDefinitionCausesTransactionCommit()
throws SQLException {
return false;
}
public boolean dataDefinitionIgnoredInTransactions() throws SQLException {
return false;
}
public ResultSet getProcedures(String catalog, String schemaPattern,
String procedureNamePattern)
throws SQLException {
return null;
}
public ResultSet getProcedureColumns(String catalog,
String schemaPattern,
String procedureNamePattern,
String columnNamePattern)
throws SQLException {
return null;
}
public ResultSet getTables(String catalog, String schemaPattern,
String tableNamePattern, String types[])
throws SQLException {
JDBCStatement s = new JDBCStatement(conn);
StringBuffer sb = new StringBuffer();
sb.append("SELECT '' AS 'TABLE_CAT', " +
"'' AS 'TABLE_SCHEM', " +
"tbl_name AS 'TABLE_NAME', " +
"upper(type) AS 'TABLE_TYPE', " +
"'' AS REMARKS FROM sqlite_master " +
"WHERE tbl_name like ");
if (tableNamePattern != null) {
sb.append(jsqlite.Shell.sql_quote(tableNamePattern));
} else {
sb.append("'%'");
}
sb.append(" AND ");
if (types == null || types.length == 0) {
sb.append("(type = 'table' or type = 'view')");
} else {
sb.append("(");
String sep = "";
for (int i = 0; i < types.length; i++) {
sb.append(sep);
sb.append("type = ");
sb.append(jsqlite.Shell.sql_quote(types[i].toLowerCase()));
sep = " or ";
}
sb.append(")");
}
ResultSet rs = null;
try {
rs = s.executeQuery(sb.toString());
s.close();
} catch (SQLException e) {
throw e;
} finally {
s.close();
}
return rs;
}
public ResultSet getSchemas() throws SQLException {
String cols[] = { "TABLE_SCHEM" };
jsqlite.TableResult tr = new jsqlite.TableResult();
tr.columns(cols);
String row[] = { "" };
tr.newrow(row);
JDBCResultSet rs = new JDBCResultSet(tr, null);
return (ResultSet) rs;
}
public ResultSet getCatalogs() throws SQLException {
String cols[] = { "TABLE_CAT" };
jsqlite.TableResult tr = new jsqlite.TableResult();
tr.columns(cols);
String row[] = { "" };
tr.newrow(row);
JDBCResultSet rs = new JDBCResultSet(tr, null);
return (ResultSet) rs;
}
public ResultSet getTableTypes() throws SQLException {
String cols[] = { "TABLE_TYPE" };
jsqlite.TableResult tr = new jsqlite.TableResult();
tr.columns(cols);
String row[] = new String[1];
row[0] = "TABLE";
tr.newrow(row);
row = new String[1];
row[0] = "VIEW";
tr.newrow(row);
JDBCResultSet rs = new JDBCResultSet(tr, null);
return (ResultSet) rs;
}
public ResultSet getColumns(String catalog, String schemaPattern,
String tableNamePattern,
String columnNamePattern)
throws SQLException {
if (conn.db == null) {
throw new SQLException("connection closed.");
}
JDBCStatement s = new JDBCStatement(conn);
JDBCResultSet rs0 = null;
try {
try {
conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null);
} catch (jsqlite.Exception se) {
throw new SQLException("schema reload failed");
}
rs0 = (JDBCResultSet)
(s.executeQuery("PRAGMA table_info(" +
jsqlite.Shell.sql_quote(tableNamePattern) +
")"));
s.close();
} catch (SQLException e) {
throw e;
} finally {
s.close();
}
if (rs0.tr.nrows < 1) {
throw new SQLException("no such table: " + tableNamePattern);
}
String cols[] = {
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
"COLUMN_NAME", "DATA_TYPE", "TYPE_NAME",
"COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS",
"NUM_PREC_RADIX", "NULLABLE", "REMARKS",
"COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB",
"CHAR_OCTET_LENGTH", "ORDINAL_POSITION", "IS_NULLABLE"
};
int types[] = {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.SMALLINT, Types.VARCHAR,
Types.INTEGER, Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.INTEGER, Types.VARCHAR,
Types.VARCHAR, Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.INTEGER, Types.VARCHAR
};
TableResultX tr = new TableResultX();
tr.columns(cols);
tr.sql_types(types);
JDBCResultSet rs = new JDBCResultSet((jsqlite.TableResult) tr, null);
if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) {
Hashtable<String, Integer> h = new Hashtable<String, Integer>();
for (int i = 0; i < rs0.tr.ncolumns; i++) {
h.put(rs0.tr.column[i], Integer.valueOf(i)); // android-changed
}
if (columnNamePattern != null &&
columnNamePattern.charAt(0) == '%') {
columnNamePattern = null;
}
for (int i = 0; i < rs0.tr.nrows; i++) {
String r0[] = (String [])(rs0.tr.rows.elementAt(i));
int col = ((Integer) h.get("name")).intValue();
if (columnNamePattern != null) {
if (r0[col].compareTo(columnNamePattern) != 0) {
continue;
}
}
String row[] = new String[cols.length];
row[0] = "";
row[1] = "";
row[2] = tableNamePattern;
row[3] = r0[col];
col = ((Integer) h.get("type")).intValue();
String typeStr = r0[col];
int type = mapSqlType(typeStr);
row[4] = "" + type;
row[5] = mapTypeName(type);
row[6] = "" + getD(typeStr, type);
row[7] = "" + getM(typeStr, type);
row[8] = "10";
row[9] = "0";
row[11] = null;
col = ((Integer) h.get("dflt_value")).intValue();
row[12] = r0[col];
row[13] = "0";
row[14] = "0";
row[15] = "65536";
col = ((Integer) h.get("cid")).intValue();
row[16] = Integer.toString(Integer.parseInt(r0[col]) + 1); // android-changed
col = ((Integer) h.get("notnull")).intValue();
row[17] = (r0[col].charAt(0) == '0') ? "YES" : "NO";
row[10] = (r0[col].charAt(0) == '0') ? "" + columnNullable :
"" + columnNoNulls;
tr.newrow(row);
}
}
return rs;
}
public ResultSet getColumnPrivileges(String catalog, String schema,
String table,
String columnNamePattern)
throws SQLException {
String cols[] = {
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
"COLUMN_NAME", "GRANTOR", "GRANTEE",
"PRIVILEGE", "IS_GRANTABLE"
};
int types[] = {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR
};
TableResultX tr = new TableResultX();
tr.columns(cols);
tr.sql_types(types);
JDBCResultSet rs = new JDBCResultSet((jsqlite.TableResult) tr, null);
return rs;
}
public ResultSet getTablePrivileges(String catalog, String schemaPattern,
String tableNamePattern)
throws SQLException {
String cols[] = {
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
"COLUMN_NAME", "GRANTOR", "GRANTEE",
"PRIVILEGE", "IS_GRANTABLE"
};
int types[] = {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR
};
TableResultX tr = new TableResultX();
tr.columns(cols);
tr.sql_types(types);
JDBCResultSet rs = new JDBCResultSet((jsqlite.TableResult) tr, null);
return rs;
}
public ResultSet getBestRowIdentifier(String catalog, String schema,
String table, int scope,
boolean nullable)
throws SQLException {
JDBCStatement s0 = new JDBCStatement(conn);
JDBCResultSet rs0 = null;
JDBCStatement s1 = new JDBCStatement(conn);
JDBCResultSet rs1 = null;
try {
try {
conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null);
} catch (jsqlite.Exception se) {
throw new SQLException("schema reload failed");
}
rs0 = (JDBCResultSet)
(s0.executeQuery("PRAGMA index_list(" +
jsqlite.Shell.sql_quote(table) + ")"));
rs1 = (JDBCResultSet)
(s1.executeQuery("PRAGMA table_info(" +
jsqlite.Shell.sql_quote(table) + ")"));
} catch (SQLException e) {
throw e;
} finally {
s0.close();
s1.close();
}
String cols[] = {
"SCOPE", "COLUMN_NAME", "DATA_TYPE",
"TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH",
"DECIMAL_DIGITS", "PSEUDO_COLUMN"
};
int types[] = {
Types.SMALLINT, Types.VARCHAR, Types.SMALLINT,
Types.VARCHAR, Types.INTEGER, Types.INTEGER,
Types.SMALLINT, Types.SMALLINT
};
TableResultX tr = new TableResultX();
tr.columns(cols);
tr.sql_types(types);
JDBCResultSet rs = new JDBCResultSet((jsqlite.TableResult) tr, null);
if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0 &&
rs1 != null && rs1.tr != null && rs1.tr.nrows > 0) {
Hashtable<String, Integer> h0 = new Hashtable<String, Integer>();
for (int i = 0; i < rs0.tr.ncolumns; i++) {
h0.put(rs0.tr.column[i], Integer.valueOf(i)); // android-changed
}
Hashtable<String, Integer> h1 = new Hashtable<String, Integer>();
for (int i = 0; i < rs1.tr.ncolumns; i++) {
h1.put(rs1.tr.column[i], Integer.valueOf(i)); // android-changed
}
for (int i = 0; i < rs0.tr.nrows; i++) {
String r0[] = (String [])(rs0.tr.rows.elementAt(i));
int col = ((Integer) h0.get("unique")).intValue();
String uniq = r0[col];
col = ((Integer) h0.get("name")).intValue();
String iname = r0[col];
if (uniq.charAt(0) == '0') {
continue;
}
JDBCStatement s2 = new JDBCStatement(conn);
JDBCResultSet rs2 = null;
try {
rs2 = (JDBCResultSet)
(s2.executeQuery("PRAGMA index_info(" +
jsqlite.Shell.sql_quote(iname) + ")"));
} catch (SQLException e) {
} finally {
s2.close();
}
if (rs2 == null || rs2.tr == null || rs2.tr.nrows <= 0) {
continue;
}
Hashtable<String, Integer> h2 =
new Hashtable<String, Integer>();
for (int k = 0; k < rs2.tr.ncolumns; k++) {
h2.put(rs2.tr.column[k], Integer.valueOf(k)); // android-changed
}
for (int k = 0; k < rs2.tr.nrows; k++) {
String r2[] = (String [])(rs2.tr.rows.elementAt(k));
col = ((Integer) h2.get("name")).intValue();
String cname = r2[col];
for (int m = 0; m < rs1.tr.nrows; m++) {
String r1[] = (String [])(rs1.tr.rows.elementAt(m));
col = ((Integer) h1.get("name")).intValue();
if (cname.compareTo(r1[col]) == 0) {
String row[] = new String[cols.length];
row[0] = "" + scope;
row[1] = cname;
row[2] = "" + Types.VARCHAR;
row[3] = "VARCHAR";
row[4] = "65536";
row[5] = "0";
row[6] = "0";
row[7] = "" + bestRowNotPseudo;
tr.newrow(row);
}
}
}
}
}
if (tr.nrows <= 0) {
String row[] = new String[cols.length];
row[0] = "" + scope;
row[1] = "_ROWID_";
row[2] = "" + Types.INTEGER;
row[3] = "INTEGER";
row[4] = "10";
row[5] = "0";
row[6] = "0";
row[7] = "" + bestRowPseudo;
tr.newrow(row);
}
return rs;
}
public ResultSet getVersionColumns(String catalog, String schema,
String table) throws SQLException {
String cols[] = {
"SCOPE", "COLUMN_NAME", "DATA_TYPE",
"TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH",
"DECIMAL_DIGITS", "PSEUDO_COLUMN"
};
int types[] = {
Types.SMALLINT, Types.VARCHAR, Types.SMALLINT,
Types.VARCHAR, Types.INTEGER, Types.INTEGER,
Types.SMALLINT, Types.SMALLINT
};
TableResultX tr = new TableResultX();
tr.columns(cols);
tr.sql_types(types);
JDBCResultSet rs = new JDBCResultSet((jsqlite.TableResult) tr, null);
return rs;
}
public ResultSet getPrimaryKeys(String catalog, String schema,
String table) throws SQLException {
JDBCStatement s0 = new JDBCStatement(conn);
JDBCResultSet rs0 = null;
try {
try {
conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null);
} catch (jsqlite.Exception se) {
throw new SQLException("schema reload failed");
}
rs0 = (JDBCResultSet)
(s0.executeQuery("PRAGMA index_list(" +
jsqlite.Shell.sql_quote(table) + ")"));
} catch (SQLException e) {
throw e;
} finally {
s0.close();
}
String cols[] = {
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
"COLUMN_NAME", "KEY_SEQ", "PK_NAME"
};
int types[] = {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.SMALLINT, Types.VARCHAR
};
TableResultX tr = new TableResultX();
tr.columns(cols);
tr.sql_types(types);
JDBCResultSet rs = new JDBCResultSet((jsqlite.TableResult) tr, null);
if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) {
Hashtable<String, Integer> h0 = new Hashtable<String, Integer>();
for (int i = 0; i < rs0.tr.ncolumns; i++) {
h0.put(rs0.tr.column[i], Integer.valueOf(i)); // android-changed
}
for (int i = 0; i < rs0.tr.nrows; i++) {
String r0[] = (String [])(rs0.tr.rows.elementAt(i));
int col = ((Integer) h0.get("unique")).intValue();
String uniq = r0[col];
col = ((Integer) h0.get("name")).intValue();
String iname = r0[col];
if (uniq.charAt(0) == '0') {
continue;
}
JDBCStatement s1 = new JDBCStatement(conn);
JDBCResultSet rs1 = null;
try {
rs1 = (JDBCResultSet)
(s1.executeQuery("PRAGMA index_info(" +
jsqlite.Shell.sql_quote(iname) + ")"));
} catch (SQLException e) {
} finally {
s1.close();
}
if (rs1 == null || rs1.tr == null || rs1.tr.nrows <= 0) {
continue;
}
Hashtable<String, Integer> h1 =
new Hashtable<String, Integer>();
for (int k = 0; k < rs1.tr.ncolumns; k++) {
h1.put(rs1.tr.column[k], Integer.valueOf(k)); // android-changed
}
for (int k = 0; k < rs1.tr.nrows; k++) {
String r1[] = (String [])(rs1.tr.rows.elementAt(k));
String row[] = new String[cols.length];
row[0] = "";
row[1] = "";
row[2] = table;
col = ((Integer) h1.get("name")).intValue();
row[3] = r1[col];
col = ((Integer) h1.get("seqno")).intValue();
row[4] = Integer.toString(Integer.parseInt(r1[col]) + 1);
row[5] = iname;
tr.newrow(row);
}
}
}
if (tr.nrows > 0) {
return rs;
}
JDBCStatement s1 = new JDBCStatement(conn);
try {
rs0 = (JDBCResultSet)
(s1.executeQuery("PRAGMA table_info(" +
jsqlite.Shell.sql_quote(table) + ")"));
} catch (SQLException e) {
throw e;
} finally {
s1.close();
}
if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) {
Hashtable<String, Integer> h0 = new Hashtable<String, Integer>();
for (int i = 0; i < rs0.tr.ncolumns; i++) {
h0.put(rs0.tr.column[i], Integer.valueOf(i)); // android-changed
}
for (int i = 0; i < rs0.tr.nrows; i++) {
String r0[] = (String [])(rs0.tr.rows.elementAt(i));
int col = ((Integer) h0.get("type")).intValue();
String type = r0[col];
if (!type.equalsIgnoreCase("integer")) {
continue;
}
col = ((Integer) h0.get("pk")).intValue();
String pk = r0[col];
if (pk.charAt(0) == '0') {
continue;
}
String row[] = new String[cols.length];
row[0] = "";
row[1] = "";
row[2] = table;
col = ((Integer) h0.get("name")).intValue();
row[3] = r0[col];
col = ((Integer) h0.get("cid")).intValue();
row[4] = Integer.toString(Integer.parseInt(r0[col]) + 1);
row[5] = "";
tr.newrow(row);
}
}
return rs;
}
private void internalImportedKeys(String table, String pktable,
JDBCResultSet in, TableResultX out) {
Hashtable<String, Integer> h0 = new Hashtable<String, Integer>();
for (int i = 0; i < in.tr.ncolumns; i++) {
h0.put(in.tr.column[i], Integer.valueOf(i)); // android-changed
}
for (int i = 0; i < in.tr.nrows; i++) {
String r0[] = (String [])(in.tr.rows.elementAt(i));
int col = ((Integer) h0.get("table")).intValue();
String pktab = r0[col];
if (pktable != null && !pktable.equalsIgnoreCase(pktab)) {
continue;
}
col = ((Integer) h0.get("from")).intValue();
String fkcol = r0[col];
col = ((Integer) h0.get("to")).intValue();
String pkcol = r0[col];
col = ((Integer) h0.get("seq")).intValue();
String seq = r0[col];
String row[] = new String[out.ncolumns];
row[0] = "";
row[1] = "";
row[2] = pktab;
row[3] = pkcol;
row[4] = "";
row[5] = "";
row[6] = table;
row[7] = fkcol == null ? pkcol : fkcol;
row[8] = Integer.toString(Integer.parseInt(seq) + 1);
row[9] =
"" + java.sql.DatabaseMetaData.importedKeyNoAction;
row[10] =
"" + java.sql.DatabaseMetaData.importedKeyNoAction;
row[11] = null;
row[12] = null;
row[13] =
"" + java.sql.DatabaseMetaData.importedKeyNotDeferrable;
out.newrow(row);
}
}
public ResultSet getImportedKeys(String catalog, String schema,
String table) throws SQLException {
JDBCStatement s0 = new JDBCStatement(conn);
JDBCResultSet rs0 = null;
try {
try {
conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null);
} catch (jsqlite.Exception se) {
throw new SQLException("schema reload failed");
}
rs0 = (JDBCResultSet)
(s0.executeQuery("PRAGMA foreign_key_list(" +
jsqlite.Shell.sql_quote(table) + ")"));
} catch (SQLException e) {
throw e;
} finally {
s0.close();
}
String cols[] = {
"PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME",
"PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM",
"FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ",
"UPDATE_RULE", "DELETE_RULE", "FK_NAME",
"PK_NAME", "DEFERRABILITY"
};
int types[] = {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.SMALLINT,
Types.SMALLINT, Types.SMALLINT, Types.VARCHAR,
Types.VARCHAR, Types.SMALLINT
};
TableResultX tr = new TableResultX();
tr.columns(cols);
tr.sql_types(types);
JDBCResultSet rs = new JDBCResultSet((jsqlite.TableResult) tr, null);
if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) {
internalImportedKeys(table, null, rs0, tr);
}
return rs;
}
public ResultSet getExportedKeys(String catalog, String schema,
String table) throws SQLException {
String cols[] = {
"PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME",
"PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM",
"FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ",
"UPDATE_RULE", "DELETE_RULE", "FK_NAME",
"PK_NAME", "DEFERRABILITY"
};
int types[] = {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.SMALLINT,
Types.SMALLINT, Types.SMALLINT, Types.VARCHAR,
Types.VARCHAR, Types.SMALLINT
};
TableResultX tr = new TableResultX();
tr.columns(cols);
tr.sql_types(types);
JDBCResultSet rs = new JDBCResultSet(tr, null);
return rs;
}
public ResultSet getCrossReference(String primaryCatalog,
String primarySchema,
String primaryTable,
String foreignCatalog,
String foreignSchema,
String foreignTable)
throws SQLException {
JDBCResultSet rs0 = null;
if (foreignTable != null && foreignTable.charAt(0) != '%') {
JDBCStatement s0 = new JDBCStatement(conn);
try {
try {
conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null);
} catch (jsqlite.Exception se) {
throw new SQLException("schema reload failed");
}
rs0 = (JDBCResultSet)
(s0.executeQuery("PRAGMA foreign_key_list(" +
jsqlite.Shell.sql_quote(foreignTable) + ")"));
} catch (SQLException e) {
throw e;
} finally {
s0.close();
}
}
String cols[] = {
"PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME",
"PKCOLUMN_NAME", "FKTABLE_CAT", "FKTABLE_SCHEM",
"FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ",
"UPDATE_RULE", "DELETE_RULE", "FK_NAME",
"PK_NAME", "DEFERRABILITY"
};
int types[] = {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.SMALLINT,
Types.SMALLINT, Types.SMALLINT, Types.VARCHAR,
Types.VARCHAR, Types.SMALLINT
};
TableResultX tr = new TableResultX();
tr.columns(cols);
tr.sql_types(types);
JDBCResultSet rs = new JDBCResultSet(tr, null);
if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) {
String pktable = null;
if (primaryTable != null && primaryTable.charAt(0) != '%') {
pktable = primaryTable;
}
internalImportedKeys(foreignTable, pktable, rs0, tr);
}
return rs;
}
public ResultSet getTypeInfo() throws SQLException {
String cols[] = {
"TYPE_NAME", "DATA_TYPE", "PRECISION",
"LITERAL_PREFIX", "LITERAL_SUFFIX", "CREATE_PARAMS",
"NULLABLE", "CASE_SENSITIVE", "SEARCHABLE",
"UNSIGNED_ATTRIBUTE", "FIXED_PREC_SCALE", "AUTO_INCREMENT",
"LOCAL_TYPE_NAME", "MINIMUM_SCALE", "MAXIMUM_SCALE",
"SQL_DATA_TYPE", "SQL_DATETIME_SUB", "NUM_PREC_RADIX"
};
int types[] = {
Types.VARCHAR, Types.SMALLINT, Types.INTEGER,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.SMALLINT, Types.BIT, Types.SMALLINT,
Types.BIT, Types.BIT, Types.BIT,
Types.VARCHAR, Types.SMALLINT, Types.SMALLINT,
Types.INTEGER, Types.INTEGER, Types.INTEGER
};
TableResultX tr = new TableResultX();
tr.columns(cols);
tr.sql_types(types);
JDBCResultSet rs = new JDBCResultSet(tr, null);
String row1[] = {
"VARCHAR", "" + Types.VARCHAR, "65536",
"'", "'", null,
"" + typeNullable, "1", "" + typeSearchable,
"0", "0", "0",
null, "0", "0",
"0", "0", "0"
};
tr.newrow(row1);
String row2[] = {
"INTEGER", "" + Types.INTEGER, "32",
null, null, null,
"" + typeNullable, "0", "" + typeSearchable,
"0", "0", "1",
null, "0", "0",
"0", "0", "2"
};
tr.newrow(row2);
String row3[] = {
"DOUBLE", "" + Types.DOUBLE, "16",
null, null, null,
"" + typeNullable, "0", "" + typeSearchable,
"0", "0", "1",
null, "0", "0",
"0", "0", "10"
};
tr.newrow(row3);
String row4[] = {
"FLOAT", "" + Types.FLOAT, "7",
null, null, null,
"" + typeNullable, "0", "" + typeSearchable,
"0", "0", "1",
null, "0", "0",
"0", "0", "10"
};
tr.newrow(row4);
String row5[] = {
"SMALLINT", "" + Types.SMALLINT, "16",
null, null, null,
"" + typeNullable, "0", "" + typeSearchable,
"0", "0", "1",
null, "0", "0",
"0", "0", "2"
};
tr.newrow(row5);
String row6[] = {
"BIT", "" + Types.BIT, "1",
null, null, null,
"" + typeNullable, "0", "" + typeSearchable,
"0", "0", "1",
null, "0", "0",
"0", "0", "2"
};
tr.newrow(row6);
String row7[] = {
"TIMESTAMP", "" + Types.TIMESTAMP, "30",
null, null, null,
"" + typeNullable, "0", "" + typeSearchable,
"0", "0", "1",
null, "0", "0",
"0", "0", "0"
};
tr.newrow(row7);
String row8[] = {
"DATE", "" + Types.DATE, "10",
null, null, null,
"" + typeNullable, "0", "" + typeSearchable,
"0", "0", "1",
null, "0", "0",
"0", "0", "0"
};
tr.newrow(row8);
String row9[] = {
"TIME", "" + Types.TIME, "8",
null, null, null,
"" + typeNullable, "0", "" + typeSearchable,
"0", "0", "1",
null, "0", "0",
"0", "0", "0"
};
tr.newrow(row9);
String row10[] = {
"BINARY", "" + Types.BINARY, "65536",
null, null, null,
"" + typeNullable, "0", "" + typeSearchable,
"0", "0", "1",
null, "0", "0",
"0", "0", "0"
};
tr.newrow(row10);
String row11[] = {
"VARBINARY", "" + Types.VARBINARY, "65536",
null, null, null,
"" + typeNullable, "0", "" + typeSearchable,
"0", "0", "1",
null, "0", "0",
"0", "0", "0"
};
tr.newrow(row11);
String row12[] = {
"REAL", "" + Types.REAL, "16",
null, null, null,
"" + typeNullable, "0", "" + typeSearchable,
"0", "0", "1",
null, "0", "0",
"0", "0", "10"
};
tr.newrow(row12);
return rs;
}
public ResultSet getIndexInfo(String catalog, String schema, String table,
boolean unique, boolean approximate)
throws SQLException {
JDBCStatement s0 = new JDBCStatement(conn);
JDBCResultSet rs0 = null;
try {
try {
conn.db.exec("SELECT 1 FROM sqlite_master LIMIT 1", null);
} catch (jsqlite.Exception se) {
throw new SQLException("schema reload failed");
}
rs0 = (JDBCResultSet)
(s0.executeQuery("PRAGMA index_list(" +
jsqlite.Shell.sql_quote(table) + ")"));
} catch (SQLException e) {
throw e;
} finally {
s0.close();
}
String cols[] = {
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
"NON_UNIQUE", "INDEX_QUALIFIER", "INDEX_NAME",
"TYPE", "ORDINAL_POSITION", "COLUMN_NAME",
"ASC_OR_DESC", "CARDINALITY", "PAGES",
"FILTER_CONDITION"
};
int types[] = {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.BIT, Types.VARCHAR, Types.VARCHAR,
Types.SMALLINT, Types.SMALLINT, Types.VARCHAR,
Types.VARCHAR, Types.INTEGER, Types.INTEGER,
Types.VARCHAR
};
TableResultX tr = new TableResultX();
tr.columns(cols);
tr.sql_types(types);
JDBCResultSet rs = new JDBCResultSet(tr, null);
if (rs0 != null && rs0.tr != null && rs0.tr.nrows > 0) {
Hashtable<String, Integer> h0 = new Hashtable<String, Integer>();
for (int i = 0; i < rs0.tr.ncolumns; i++) {
h0.put(rs0.tr.column[i], Integer.valueOf(i)); // android-changed
}
for (int i = 0; i < rs0.tr.nrows; i++) {
String r0[] = (String [])(rs0.tr.rows.elementAt(i));
int col = ((Integer) h0.get("unique")).intValue();
String uniq = r0[col];
col = ((Integer) h0.get("name")).intValue();
String iname = r0[col];
if (unique && uniq.charAt(0) == '0') {
continue;
}
JDBCStatement s1 = new JDBCStatement(conn);
JDBCResultSet rs1 = null;
try {
rs1 = (JDBCResultSet)
(s1.executeQuery("PRAGMA index_info(" +
jsqlite.Shell.sql_quote(iname) + ")"));
} catch (SQLException e) {
} finally {
s1.close();
}
if (rs1 == null || rs1.tr == null || rs1.tr.nrows <= 0) {
continue;
}
Hashtable<String, Integer> h1 =
new Hashtable<String, Integer>();
for (int k = 0; k < rs1.tr.ncolumns; k++) {
h1.put(rs1.tr.column[k], Integer.valueOf(k)); // android-changed
}
for (int k = 0; k < rs1.tr.nrows; k++) {
String r1[] = (String [])(rs1.tr.rows.elementAt(k));
String row[] = new String[cols.length];
row[0] = "";
row[1] = "";
row[2] = table;
row[3] = (uniq.charAt(0) != '0' ||
(iname.charAt(0) == '(' &&
iname.indexOf(" autoindex ") > 0)) ? "0" : "1";
row[4] = "";
row[5] = iname;
row[6] = "" + tableIndexOther;
col = ((Integer) h1.get("seqno")).intValue();
row[7] = Integer.toString(Integer.parseInt(r1[col]) + 1);
col = ((Integer) h1.get("name")).intValue();
row[8] = r1[col];
row[9] = "A";
row[10] = "0";
row[11] = "0";
row[12] = null;
tr.newrow(row);
}
}
}
return rs;
}
public boolean supportsResultSetType(int type) throws SQLException {
return type == ResultSet.TYPE_FORWARD_ONLY ||
type == ResultSet.TYPE_SCROLL_INSENSITIVE ||
type == ResultSet.TYPE_SCROLL_SENSITIVE;
}
public boolean supportsResultSetConcurrency(int type, int concurrency)
throws SQLException {
if (type == ResultSet.TYPE_FORWARD_ONLY ||
type == ResultSet.TYPE_SCROLL_INSENSITIVE ||
type == ResultSet.TYPE_SCROLL_SENSITIVE) {
return concurrency == ResultSet.CONCUR_READ_ONLY ||
concurrency == ResultSet.CONCUR_UPDATABLE;
}
return false;
}
public boolean ownUpdatesAreVisible(int type) throws SQLException {
if (type == ResultSet.TYPE_FORWARD_ONLY ||
type == ResultSet.TYPE_SCROLL_INSENSITIVE ||
type == ResultSet.TYPE_SCROLL_SENSITIVE) {
return true;
}
return false;
}
public boolean ownDeletesAreVisible(int type) throws SQLException {
if (type == ResultSet.TYPE_FORWARD_ONLY ||
type == ResultSet.TYPE_SCROLL_INSENSITIVE ||
type == ResultSet.TYPE_SCROLL_SENSITIVE) {
return true;
}
return false;
}
public boolean ownInsertsAreVisible(int type) throws SQLException {
if (type == ResultSet.TYPE_FORWARD_ONLY ||
type == ResultSet.TYPE_SCROLL_INSENSITIVE ||
type == ResultSet.TYPE_SCROLL_SENSITIVE) {
return true;
}
return false;
}
public boolean othersUpdatesAreVisible(int type) throws SQLException {
return false;
}
public boolean othersDeletesAreVisible(int type) throws SQLException {
return false;
}
public boolean othersInsertsAreVisible(int type) throws SQLException {
return false;
}
public boolean updatesAreDetected(int type) throws SQLException {
return false;
}
public boolean deletesAreDetected(int type) throws SQLException {
return false;
}
public boolean insertsAreDetected(int type) throws SQLException {
return false;
}
public boolean supportsBatchUpdates() throws SQLException {
return true;
}
public ResultSet getUDTs(String catalog, String schemaPattern,
String typeNamePattern, int[] types)
throws SQLException {
return null;
}
public Connection getConnection() throws SQLException {
return conn;
}
static String mapTypeName(int type) {
switch (type) {
case Types.INTEGER: return "integer";
case Types.SMALLINT: return "smallint";
case Types.FLOAT: return "float";
case Types.DOUBLE: return "double";
case Types.TIMESTAMP: return "timestamp";
case Types.DATE: return "date";
case Types.TIME: return "time";
case Types.BINARY: return "binary";
case Types.VARBINARY: return "varbinary";
case Types.REAL: return "real";
}
return "varchar";
}
static int mapSqlType(String type) {
if (type == null) {
return Types.VARCHAR;
}
type = type.toLowerCase();
if (type.startsWith("inter")) {
return Types.VARCHAR;
}
if (type.startsWith("numeric") ||
type.startsWith("int")) {
return Types.INTEGER;
}
if (type.startsWith("tinyint") ||
type.startsWith("smallint")) {
return Types.SMALLINT;
}
if (type.startsWith("float")) {
return Types.FLOAT;
}
if (type.startsWith("double")) {
return Types.DOUBLE;
}
if (type.startsWith("datetime") ||
type.startsWith("timestamp")) {
return Types.TIMESTAMP;
}
if (type.startsWith("date")) {
return Types.DATE;
}
if (type.startsWith("time")) {
return Types.TIME;
}
if (type.startsWith("blob")) {
return Types.BINARY;
}
if (type.startsWith("binary")) {
return Types.BINARY;
}
if (type.startsWith("varbinary")) {
return Types.VARBINARY;
}
if (type.startsWith("real")) {
return Types.REAL;
}
return Types.VARCHAR;
}
static int getM(String typeStr, int type) {
int m = 65536;
switch (type) {
case Types.INTEGER: m = 11; break;
case Types.SMALLINT: m = 6; break;
case Types.FLOAT: m = 25; break;
case Types.REAL:
case Types.DOUBLE: m = 54; break;
case Types.TIMESTAMP: return 30;
case Types.DATE: return 10;
case Types.TIME: return 8;
}
typeStr = typeStr.toLowerCase();
int i1 = typeStr.indexOf('(');
if (i1 > 0) {
++i1;
int i2 = typeStr.indexOf(',', i1);
if (i2 < 0) {
i2 = typeStr.indexOf(')', i1);
}
if (i2 - i1 > 0) {
String num = typeStr.substring(i1, i2);
try {
m = java.lang.Integer.parseInt(num, 10);
} catch (NumberFormatException e) {
}
}
}
return m;
}
static int getD(String typeStr, int type) {
int d = 0;
switch (type) {
case Types.INTEGER: d = 10; break;
case Types.SMALLINT: d = 5; break;
case Types.FLOAT: d = 24; break;
case Types.REAL:
case Types.DOUBLE: d = 53; break;
default: return getM(typeStr, type);
}
typeStr = typeStr.toLowerCase();
int i1 = typeStr.indexOf('(');
if (i1 > 0) {
++i1;
int i2 = typeStr.indexOf(',', i1);
if (i2 < 0) {
return getM(typeStr, type);
}
i1 = i2;
i2 = typeStr.indexOf(')', i1);
if (i2 - i1 > 0) {
String num = typeStr.substring(i1, i2);
try {
d = java.lang.Integer.parseInt(num, 10);
} catch (NumberFormatException e) {
}
}
}
return d;
}
public boolean supportsSavepoints() {
return false;
}
public boolean supportsNamedParameters() {
return false;
}
public boolean supportsMultipleOpenResults() {
return false;
}
public boolean supportsGetGeneratedKeys() {
return false;
}
public boolean supportsResultSetHoldability(int x) {
return false;
}
public boolean supportsStatementPooling() {
return false;
}
public boolean locatorsUpdateCopy() throws SQLException {
throw new SQLException("not supported");
}
public ResultSet getSuperTypes(String catalog, String schemaPattern,
String typeNamePattern)
throws SQLException {
throw new SQLException("not supported");
}
public ResultSet getSuperTables(String catalog, String schemaPattern,
String tableNamePattern)
throws SQLException {
throw new SQLException("not supported");
}
public ResultSet getAttributes(String catalog, String schemaPattern,
String typeNamePattern,
String attributeNamePattern)
throws SQLException {
throw new SQLException("not supported");
}
public int getResultSetHoldability() throws SQLException {
return ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
public int getDatabaseMajorVersion() {
return jsqlite.JDBCDriver.MAJORVERSION;
}
public int getDatabaseMinorVersion() {
return jsqlite.Constants.drv_minor;
}
public int getJDBCMajorVersion() {
return 1;
}
public int getJDBCMinorVersion() {
return 0;
}
public int getSQLStateType() throws SQLException {
return sqlStateXOpen;
}
public RowIdLifetime getRowIdLifetime() throws SQLException {
return RowIdLifetime.ROWID_UNSUPPORTED;
}
public ResultSet getSchemas(String cat, String schema)
throws SQLException {
throw new SQLException("not supported");
}
public boolean supportsStoredFunctionsUsingCallSyntax()
throws SQLException {
return false;
}
public boolean autoCommitFailureClosesAllResultSets()
throws SQLException {
return false;
}
public ResultSet getClientInfoProperties() throws SQLException {
throw new SQLException("unsupported");
}
public ResultSet getFunctions(String cat, String schema, String func)
throws SQLException {
throw new SQLException("unsupported");
}
public ResultSet getFunctionColumns(String cat, String schema,
String func, String colpat)
throws SQLException {
throw new SQLException("unsupported");
}
public <T> T unwrap(java.lang.Class<T> iface) throws SQLException {
throw new SQLException("unsupported");
}
public boolean isWrapperFor(java.lang.Class iface) throws SQLException {
return false;
}
}
| Java |
package jsqlite.JDBC2z;
import java.sql.*;
import java.math.BigDecimal;
public class JDBCResultSet implements java.sql.ResultSet {
/**
* Current row to be retrieved.
*/
private int row;
/**
* Table returned by Database.get_table()
*/
protected jsqlite.TableResult tr;
/**
* Statement from which result set was produced.
*/
private JDBCStatement s;
/**
* Meta data for result set or null.
*/
private JDBCResultSetMetaData md;
/**
* Last result cell retrieved or null.
*/
private String lastg;
/**
* Updatability of this result set.
*/
private int updatable;
/**
* When updatable this is the table name.
*/
private String uptable;
/**
* When updatable these are the PK column names of uptable.
*/
private String pkcols[];
/**
* When updatable these are the PK column indices (0-based) of uptable.
*/
private int pkcoli[];
/*
* Constants to reflect updateability.
*/
private final static int UPD_UNKNOWN = -1;
private final static int UPD_NO = 0;
private final static int UPD_INS = 1;
private final static int UPD_INSUPDDEL = 2;
/**
* Flag for cursor being (not) on insert row.
*/
private boolean oninsrow;
/**
* Row buffer for insert/update row.
*/
private String rowbuf[];
private static final boolean nullrepl =
jsqlite.Database.version().compareTo("2.5.0") < 0;
public JDBCResultSet(jsqlite.TableResult tr, JDBCStatement s) {
this.tr = tr;
this.s = s;
this.md = null;
this.lastg = null;
this.row = -1;
this.updatable = UPD_UNKNOWN;
this.oninsrow = false;
this.rowbuf = null;
}
public boolean isUpdatable() throws SQLException {
if (updatable == UPD_UNKNOWN) {
try {
JDBCResultSetMetaData m =
(JDBCResultSetMetaData) getMetaData();
java.util.HashSet<String> h = new java.util.HashSet<String>();
String lastt = null;
for (int i = 1; i <= tr.ncolumns; i++) {
lastt = m.getTableName(i);
h.add(lastt);
}
if (h.size() > 1 || lastt == null) {
updatable = UPD_NO;
throw new SQLException("view or join");
}
updatable = UPD_INS;
uptable = lastt;
JDBCResultSet pk = (JDBCResultSet)
s.conn.getMetaData().getPrimaryKeys(null, null, uptable);
if (pk.tr.nrows > 0) {
boolean colnotfound = false;
pkcols = new String[pk.tr.nrows];
pkcoli = new int[pk.tr.nrows];
for (int i = 0; i < pk.tr.nrows; i++) {
String rd[] = (String []) pk.tr.rows.elementAt(i);
pkcols[i] = rd[3];
try {
pkcoli[i] = findColumn(pkcols[i]) - 1;
} catch (SQLException ee) {
colnotfound = true;
}
}
if (!colnotfound) {
updatable = UPD_INSUPDDEL;
}
}
pk.close();
} catch (SQLException e) {
updatable = UPD_NO;
}
}
if (updatable < UPD_INS) {
throw new SQLException("result set not updatable");
}
return true;
}
public void fillRowbuf() throws SQLException {
if (rowbuf == null) {
if (row < 0) {
throw new SQLException("cursor outside of result set");
}
rowbuf = new String[tr.ncolumns];
System.arraycopy((String []) tr.rows.elementAt(row), 0,
rowbuf, 0, tr.ncolumns);
}
}
public boolean next() throws SQLException {
if (tr == null) {
return false;
}
row++;
return row < tr.nrows;
}
public int findColumn(String columnName) throws SQLException {
JDBCResultSetMetaData m = (JDBCResultSetMetaData) getMetaData();
return m.findColByName(columnName);
}
public int getRow() throws SQLException {
if (tr == null) {
throw new SQLException("no rows");
}
return row + 1;
}
public boolean previous() throws SQLException {
if (tr == null) {
throw new SQLException("result set already closed.");
}
if (row >= 0) {
row--;
}
return row >= 0;
}
public boolean absolute(int row) throws SQLException {
if (tr == null) {
return false;
}
if (row < 0) {
row = tr.nrows + 1 + row;
}
row--;
if (row < 0 || row > tr.nrows) {
return false;
}
this.row = row;
return true;
}
public boolean relative(int row) throws SQLException {
if (tr == null) {
return false;
}
if (this.row + row < 0 || this.row + row >= tr.nrows) {
return false;
}
this.row += row;
return true;
}
public void setFetchDirection(int dir) throws SQLException {
if (dir != ResultSet.FETCH_FORWARD) {
throw new SQLException("only forward fetch direction supported");
}
}
public int getFetchDirection() throws SQLException {
return ResultSet.FETCH_FORWARD;
}
public void setFetchSize(int fsize) throws SQLException {
if (fsize != 1) {
throw new SQLException("fetch size must be 1");
}
}
public int getFetchSize() throws SQLException {
return 1;
}
public String getString(int columnIndex) throws SQLException {
if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) {
throw new SQLException("column " + columnIndex + " not found");
}
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[columnIndex - 1];
return lastg;
}
public String getString(String columnName) throws SQLException {
int col = findColumn(columnName);
return getString(col);
}
public int getInt(int columnIndex) throws SQLException {
Integer i = internalGetInt(columnIndex);
if (i != null) {
return i.intValue();
}
return 0;
}
private Integer internalGetInt(int columnIndex) throws SQLException {
if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) {
throw new SQLException("column " + columnIndex + " not found");
}
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[columnIndex - 1];
try {
return Integer.valueOf(lastg);
} catch (java.lang.Exception e) {
lastg = null;
}
return null;
}
public int getInt(String columnName) throws SQLException {
int col = findColumn(columnName);
return getInt(col);
}
public boolean getBoolean(int columnIndex) throws SQLException {
return getInt(columnIndex) == 1 ||
Boolean.parseBoolean(getString(columnIndex));
}
public boolean getBoolean(String columnName) throws SQLException {
int col = findColumn(columnName);
return getBoolean(col);
}
public ResultSetMetaData getMetaData() throws SQLException {
if (md == null) {
md = new JDBCResultSetMetaData(this);
}
return md;
}
public short getShort(int columnIndex) throws SQLException {
Short sh = internalGetShort(columnIndex);
if (sh != null) {
return sh.shortValue();
}
return 0;
}
private Short internalGetShort(int columnIndex) throws SQLException {
if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) {
throw new SQLException("column " + columnIndex + " not found");
}
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[columnIndex - 1];
try {
return Short.valueOf(lastg);
} catch (java.lang.Exception e) {
lastg = null;
}
return null;
}
public short getShort(String columnName) throws SQLException {
int col = findColumn(columnName);
return getShort(col);
}
public java.sql.Time getTime(int columnIndex) throws SQLException {
return internalGetTime(columnIndex, null);
}
private java.sql.Time internalGetTime(int columnIndex,
java.util.Calendar cal)
throws SQLException {
if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) {
throw new SQLException("column " + columnIndex + " not found");
}
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[columnIndex - 1];
try {
if (s.conn.useJulian) {
try {
return new java.sql.Time(jsqlite.Database.long_from_julian(lastg));
} catch (java.lang.Exception ee) {
return java.sql.Time.valueOf(lastg);
}
} else {
try {
return java.sql.Time.valueOf(lastg);
} catch (java.lang.Exception ee) {
return new java.sql.Time(jsqlite.Database.long_from_julian(lastg));
}
}
} catch (java.lang.Exception e) {
lastg = null;
}
return null;
}
public java.sql.Time getTime(String columnName) throws SQLException {
int col = findColumn(columnName);
return getTime(col);
}
public java.sql.Time getTime(int columnIndex, java.util.Calendar cal)
throws SQLException {
return internalGetTime(columnIndex, cal);
}
public java.sql.Time getTime(String columnName, java.util.Calendar cal)
throws SQLException{
int col = findColumn(columnName);
return getTime(col, cal);
}
public java.sql.Timestamp getTimestamp(int columnIndex)
throws SQLException{
return internalGetTimestamp(columnIndex, null);
}
private java.sql.Timestamp internalGetTimestamp(int columnIndex,
java.util.Calendar cal)
throws SQLException {
if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) {
throw new SQLException("column " + columnIndex + " not found");
}
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[columnIndex - 1];
try {
if (s.conn.useJulian) {
try {
return new java.sql.Timestamp(jsqlite.Database.long_from_julian(lastg));
} catch (java.lang.Exception ee) {
return java.sql.Timestamp.valueOf(lastg);
}
} else {
try {
return java.sql.Timestamp.valueOf(lastg);
} catch (java.lang.Exception ee) {
return new java.sql.Timestamp(jsqlite.Database.long_from_julian(lastg));
}
}
} catch (java.lang.Exception e) {
lastg = null;
}
return null;
}
public java.sql.Timestamp getTimestamp(String columnName)
throws SQLException{
int col = findColumn(columnName);
return getTimestamp(col);
}
public java.sql.Timestamp getTimestamp(int columnIndex,
java.util.Calendar cal)
throws SQLException {
return internalGetTimestamp(columnIndex, cal);
}
public java.sql.Timestamp getTimestamp(String columnName,
java.util.Calendar cal)
throws SQLException {
int col = findColumn(columnName);
return getTimestamp(col, cal);
}
public java.sql.Date getDate(int columnIndex) throws SQLException {
return internalGetDate(columnIndex, null);
}
private java.sql.Date internalGetDate(int columnIndex,
java.util.Calendar cal)
throws SQLException {
if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) {
throw new SQLException("column " + columnIndex + " not found");
}
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[columnIndex - 1];
try {
if (s.conn.useJulian) {
try {
return new java.sql.Date(jsqlite.Database.long_from_julian(lastg));
} catch (java.lang.Exception ee) {
return java.sql.Date.valueOf(lastg);
}
} else {
try {
return java.sql.Date.valueOf(lastg);
} catch (java.lang.Exception ee) {
return new java.sql.Date(jsqlite.Database.long_from_julian(lastg));
}
}
} catch (java.lang.Exception e) {
lastg = null;
}
return null;
}
public java.sql.Date getDate(String columnName) throws SQLException {
int col = findColumn(columnName);
return getDate(col);
}
public java.sql.Date getDate(int columnIndex, java.util.Calendar cal)
throws SQLException{
return internalGetDate(columnIndex, cal);
}
public java.sql.Date getDate(String columnName, java.util.Calendar cal)
throws SQLException{
int col = findColumn(columnName);
return getDate(col, cal);
}
public double getDouble(int columnIndex) throws SQLException {
Double d = internalGetDouble(columnIndex);
if (d != null) {
return d.doubleValue();
}
return 0;
}
private Double internalGetDouble(int columnIndex) throws SQLException {
if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) {
throw new SQLException("column " + columnIndex + " not found");
}
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[columnIndex - 1];
try {
return Double.valueOf(lastg);
} catch (java.lang.Exception e) {
lastg = null;
}
return null;
}
public double getDouble(String columnName) throws SQLException {
int col = findColumn(columnName);
return getDouble(col);
}
public float getFloat(int columnIndex) throws SQLException {
Float f = internalGetFloat(columnIndex);
if (f != null) {
return f.floatValue();
}
return 0;
}
private Float internalGetFloat(int columnIndex) throws SQLException {
if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) {
throw new SQLException("column " + columnIndex + " not found");
}
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[columnIndex - 1];
try {
return Float.valueOf(lastg);
} catch (java.lang.Exception e) {
lastg = null;
}
return null;
}
public float getFloat(String columnName) throws SQLException {
int col = findColumn(columnName);
return getFloat(col);
}
public long getLong(int columnIndex) throws SQLException {
Long l = internalGetLong(columnIndex);
if (l != null) {
return l.longValue();
}
return 0;
}
private Long internalGetLong(int columnIndex) throws SQLException {
if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) {
throw new SQLException("column " + columnIndex + " not found");
}
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[columnIndex - 1];
try {
return Long.valueOf(lastg);
} catch (java.lang.Exception e) {
lastg = null;
}
return null;
}
public long getLong(String columnName) throws SQLException {
int col = findColumn(columnName);
return getLong(col);
}
@Deprecated
public java.io.InputStream getUnicodeStream(int columnIndex)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Deprecated
public java.io.InputStream getUnicodeStream(String columnName)
throws SQLException {
int col = findColumn(columnName);
return getUnicodeStream(col);
}
public java.io.InputStream getAsciiStream(String columnName)
throws SQLException {
int col = findColumn(columnName);
return getAsciiStream(col);
}
public java.io.InputStream getAsciiStream(int columnIndex)
throws SQLException {
throw new SQLException("not supported");
}
public BigDecimal getBigDecimal(String columnName)
throws SQLException {
int col = findColumn(columnName);
return getBigDecimal(col);
}
@Deprecated
public BigDecimal getBigDecimal(String columnName, int scale)
throws SQLException {
int col = findColumn(columnName);
return getBigDecimal(col, scale);
}
public BigDecimal getBigDecimal(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Deprecated
public BigDecimal getBigDecimal(int columnIndex, int scale)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public java.io.InputStream getBinaryStream(int columnIndex)
throws SQLException {
byte data[] = getBytes(columnIndex);
if (data != null) {
return new java.io.ByteArrayInputStream(data);
}
return null;
}
public java.io.InputStream getBinaryStream(String columnName)
throws SQLException {
byte data[] = getBytes(columnName);
if (data != null) {
return new java.io.ByteArrayInputStream(data);
}
return null;
}
public byte getByte(int columnIndex) throws SQLException {
throw new SQLException("not supported");
}
public byte getByte(String columnName) throws SQLException {
int col = findColumn(columnName);
return getByte(col);
}
public byte[] getBytes(int columnIndex) throws SQLException {
if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) {
throw new SQLException("column " + columnIndex + " not found");
}
byte ret[] = null;
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[columnIndex - 1];
if (lastg != null) {
ret = jsqlite.StringEncoder.decode(lastg);
}
return ret;
}
public byte[] getBytes(String columnName) throws SQLException {
int col = findColumn(columnName);
return getBytes(col);
}
public String getCursorName() throws SQLException {
return null;
}
public Object getObject(int columnIndex) throws SQLException {
if (tr == null || columnIndex < 1 || columnIndex > tr.ncolumns) {
throw new SQLException("column " + columnIndex + " not found");
}
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[columnIndex - 1];
Object ret = lastg;
if (tr instanceof TableResultX) {
switch (((TableResultX) tr).sql_type[columnIndex - 1]) {
case Types.SMALLINT:
ret = internalGetShort(columnIndex);
break;
case Types.INTEGER:
ret = internalGetInt(columnIndex);
break;
case Types.DOUBLE:
ret = internalGetDouble(columnIndex);
break;
case Types.FLOAT:
ret = internalGetFloat(columnIndex);
break;
case Types.BIGINT:
ret = internalGetLong(columnIndex);
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
ret = getBytes(columnIndex);
break;
case Types.NULL:
ret = null;
break;
/* defaults to String below */
}
}
return ret;
}
public Object getObject(String columnName) throws SQLException {
int col = findColumn(columnName);
return getObject(col);
}
public Object getObject(int columnIndex, java.util.Map map)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public Object getObject(String columnName, java.util.Map map)
throws SQLException {
int col = findColumn(columnName);
return getObject(col, map);
}
public java.sql.Ref getRef(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public java.sql.Ref getRef(String columnName) throws SQLException {
int col = findColumn(columnName);
return getRef(col);
}
public java.sql.Blob getBlob(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public java.sql.Blob getBlob(String columnName) throws SQLException {
int col = findColumn(columnName);
return getBlob(col);
}
public java.sql.Clob getClob(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public java.sql.Clob getClob(String columnName) throws SQLException {
int col = findColumn(columnName);
return getClob(col);
}
public java.sql.Array getArray(int columnIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public java.sql.Array getArray(String columnName) throws SQLException {
int col = findColumn(columnName);
return getArray(col);
}
public java.io.Reader getCharacterStream(int columnIndex)
throws SQLException {
String data = getString(columnIndex);
if (data != null) {
char[] cdata = data.toCharArray();
return new java.io.CharArrayReader(cdata);
}
return null;
}
public java.io.Reader getCharacterStream(String columnName)
throws SQLException {
String data = getString(columnName);
if (data != null) {
char[] cdata = data.toCharArray();
return new java.io.CharArrayReader(cdata);
}
return null;
}
public SQLWarning getWarnings() throws SQLException {
throw new SQLException("not supported");
}
public boolean wasNull() throws SQLException {
return lastg == null;
}
public void clearWarnings() throws SQLException {
throw new SQLException("not supported");
}
public boolean isFirst() throws SQLException {
if (tr == null) {
return true;
}
return row == 0;
}
public boolean isBeforeFirst() throws SQLException {
if (tr == null || tr.nrows <= 0) {
return false;
}
return row < 0;
}
public void beforeFirst() throws SQLException {
if (tr == null) {
return;
}
row = -1;
}
public boolean first() throws SQLException {
if (tr == null || tr.nrows <= 0) {
return false;
}
row = 0;
return true;
}
public boolean isAfterLast() throws SQLException {
if (tr == null || tr.nrows <= 0) {
return false;
}
return row >= tr.nrows;
}
public void afterLast() throws SQLException {
if (tr == null) {
return;
}
row = tr.nrows;
}
public boolean isLast() throws SQLException {
if (tr == null) {
return true;
}
return row == tr.nrows - 1;
}
public boolean last() throws SQLException {
if (tr == null || tr.nrows <= 0) {
return false;
}
row = tr.nrows -1;
return true;
}
public int getType() throws SQLException {
return TYPE_SCROLL_SENSITIVE;
}
public int getConcurrency() throws SQLException {
return CONCUR_UPDATABLE;
}
public boolean rowUpdated() throws SQLException {
return false;
}
public boolean rowInserted() throws SQLException {
return false;
}
public boolean rowDeleted() throws SQLException {
return false;
}
public void insertRow() throws SQLException {
isUpdatable();
if (!oninsrow || rowbuf == null) {
throw new SQLException("no insert data provided");
}
JDBCResultSetMetaData m = (JDBCResultSetMetaData) getMetaData();
StringBuffer sb = new StringBuffer();
sb.append("INSERT INTO ");
sb.append(jsqlite.Shell.sql_quote_dbl(uptable));
sb.append("(");
for (int i = 0; i < tr.ncolumns; i++) {
sb.append(jsqlite.Shell.sql_quote_dbl(m.getColumnName(i + 1)));
if (i < tr.ncolumns - 1) {
sb.append(",");
}
}
sb.append(") VALUES(");
for (int i = 0; i < tr.ncolumns; i++) {
sb.append(nullrepl ? "'%q'" : "%Q");
if (i < tr.ncolumns - 1) {
sb.append(",");
}
}
sb.append(")");
try {
this.s.conn.db.exec(sb.toString(), null, rowbuf);
} catch (jsqlite.Exception e) {
throw new SQLException(e.getMessage());
}
tr.newrow(rowbuf);
rowbuf = null;
oninsrow = false;
last();
}
public void updateRow() throws SQLException {
isUpdatable();
if (rowbuf == null) {
throw new SQLException("no update data provided");
}
if (oninsrow) {
throw new SQLException("cursor on insert row");
}
if (updatable < UPD_INSUPDDEL) {
throw new SQLException("no primary key on table defined");
}
String rd[] = (String []) tr.rows.elementAt(row);
JDBCResultSetMetaData m = (JDBCResultSetMetaData) getMetaData();
String args[] = new String[tr.ncolumns + pkcols.length];
StringBuffer sb = new StringBuffer();
sb.append("UPDATE ");
sb.append(jsqlite.Shell.sql_quote_dbl(uptable));
sb.append(" SET ");
int i;
for (i = 0; i < tr.ncolumns; i++) {
sb.append(jsqlite.Shell.sql_quote_dbl(m.getColumnName(i + 1)));
sb.append(" = " + (nullrepl ? "'%q'" : "%Q"));
if (i < tr.ncolumns - 1) {
sb.append(",");
}
args[i] = rowbuf[i];
}
sb. append(" WHERE ");
for (int k = 0; k < pkcols.length; k++, i++) {
sb.append(jsqlite.Shell.sql_quote_dbl(pkcols[k]));
sb.append(" = " + (nullrepl ? "'%q'" : "%Q"));
if (k < pkcols.length - 1) {
sb.append(" AND ");
}
args[i] = rd[pkcoli[k]];
}
try {
this.s.conn.db.exec(sb.toString(), null, args);
} catch (jsqlite.Exception e) {
throw new SQLException(e.getMessage());
}
System.arraycopy(rowbuf, 0, rd, 0, rowbuf.length);
rowbuf = null;
}
public void deleteRow() throws SQLException {
isUpdatable();
if (oninsrow) {
throw new SQLException("cursor on insert row");
}
if (updatable < UPD_INSUPDDEL) {
throw new SQLException("no primary key on table defined");
}
fillRowbuf();
StringBuffer sb = new StringBuffer();
sb.append("DELETE FROM ");
sb.append(jsqlite.Shell.sql_quote_dbl(uptable));
sb.append(" WHERE ");
String args[] = new String[pkcols.length];
for (int i = 0; i < pkcols.length; i++) {
sb.append(jsqlite.Shell.sql_quote_dbl(pkcols[i]));
sb.append(" = " + (nullrepl ? "'%q'" : "%Q"));
if (i < pkcols.length - 1) {
sb.append(" AND ");
}
args[i] = rowbuf[pkcoli[i]];
}
try {
this.s.conn.db.exec(sb.toString(), null, args);
} catch (jsqlite.Exception e) {
throw new SQLException(e.getMessage());
}
rowbuf = null;
}
public void refreshRow() throws SQLException {
isUpdatable();
if (oninsrow) {
throw new SQLException("cursor on insert row");
}
if (updatable < UPD_INSUPDDEL) {
throw new SQLException("no primary key on table defined");
}
JDBCResultSetMetaData m = (JDBCResultSetMetaData) getMetaData();
String rd[] = (String []) tr.rows.elementAt(row);
StringBuffer sb = new StringBuffer();
sb.append("SELECT ");
for (int i = 0; i < tr.ncolumns; i++) {
sb.append(jsqlite.Shell.sql_quote_dbl(m.getColumnName(i + 1)));
if (i < tr.ncolumns - 1) {
sb.append(",");
}
}
sb.append(" FROM ");
sb.append(jsqlite.Shell.sql_quote_dbl(uptable));
sb.append(" WHERE ");
String args[] = new String[pkcols.length];
for (int i = 0; i < pkcols.length; i++) {
sb.append(jsqlite.Shell.sql_quote_dbl(pkcols[i]));
sb.append(" = " + (nullrepl ? "'%q'" : "%Q"));
if (i < pkcols.length - 1) {
sb.append(" AND ");
}
args[i] = rd[pkcoli[i]];
}
jsqlite.TableResult trnew = null;
try {
trnew = this.s.conn.db.get_table(sb.toString(), args);
} catch (jsqlite.Exception e) {
throw new SQLException(e.getMessage());
}
if (trnew.nrows != 1) {
throw new SQLException("wrong size of result set");
}
rowbuf = null;
tr.rows.setElementAt(trnew.rows.elementAt(0), row);
}
public void cancelRowUpdates() throws SQLException {
rowbuf = null;
}
public void moveToInsertRow() throws SQLException {
isUpdatable();
if (!oninsrow) {
oninsrow = true;
rowbuf = new String[tr.nrows];
}
}
public void moveToCurrentRow() throws SQLException {
if (oninsrow) {
oninsrow = false;
rowbuf = null;
}
}
public void updateNull(int colIndex) throws SQLException {
isUpdatable();
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
fillRowbuf();
rowbuf[colIndex - 1] = null;
}
public void updateBoolean(int colIndex, boolean b) throws SQLException {
updateString(colIndex, b ? "1" : "0");
}
public void updateByte(int colIndex, byte b) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateShort(int colIndex, short b) throws SQLException {
isUpdatable();
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
fillRowbuf();
rowbuf[colIndex - 1] = Short.toString(b);
}
public void updateInt(int colIndex, int b) throws SQLException {
isUpdatable();
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
fillRowbuf();
rowbuf[colIndex - 1] = Integer.toString(b);
}
public void updateLong(int colIndex, long b) throws SQLException {
isUpdatable();
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
fillRowbuf();
rowbuf[colIndex - 1] = Long.toString(b);
}
public void updateFloat(int colIndex, float f) throws SQLException {
isUpdatable();
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
fillRowbuf();
rowbuf[colIndex - 1] = Float.toString(f);
}
public void updateDouble(int colIndex, double f) throws SQLException {
isUpdatable();
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
fillRowbuf();
rowbuf[colIndex - 1] = Double.toString(f);
}
public void updateBigDecimal(int colIndex, BigDecimal f)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateString(int colIndex, String s) throws SQLException {
isUpdatable();
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
fillRowbuf();
rowbuf[colIndex - 1] = s;
}
public void updateBytes(int colIndex, byte[] s) throws SQLException {
isUpdatable();
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
fillRowbuf();
if (this.s.conn.db.is3()) {
rowbuf[colIndex - 1] = jsqlite.StringEncoder.encodeX(s);
} else {
rowbuf[colIndex - 1] = jsqlite.StringEncoder.encode(s);
}
}
public void updateDate(int colIndex, java.sql.Date d) throws SQLException {
isUpdatable();
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
fillRowbuf();
rowbuf[colIndex - 1] = d.toString();
}
public void updateTime(int colIndex, java.sql.Time t) throws SQLException {
isUpdatable();
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
fillRowbuf();
rowbuf[colIndex - 1] = t.toString();
}
public void updateTimestamp(int colIndex, java.sql.Timestamp t)
throws SQLException {
isUpdatable();
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
fillRowbuf();
rowbuf[colIndex - 1] = t.toString();
}
public void updateAsciiStream(int colIndex, java.io.InputStream in, int s)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateBinaryStream(int colIndex, java.io.InputStream in, int s)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateCharacterStream(int colIndex, java.io.Reader in, int s)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateObject(int colIndex, Object obj) throws SQLException {
updateString(colIndex, obj.toString());
}
public void updateObject(int colIndex, Object obj, int s)
throws SQLException {
updateString(colIndex, obj.toString());
}
public void updateNull(String colName) throws SQLException {
int col = findColumn(colName);
updateNull(col);
}
public void updateBoolean(String colName, boolean b) throws SQLException {
int col = findColumn(colName);
updateBoolean(col, b);
}
public void updateByte(String colName, byte b) throws SQLException {
int col = findColumn(colName);
updateByte(col, b);
}
public void updateShort(String colName, short b) throws SQLException {
int col = findColumn(colName);
updateShort(col, b);
}
public void updateInt(String colName, int b) throws SQLException {
int col = findColumn(colName);
updateInt(col, b);
}
public void updateLong(String colName, long b) throws SQLException {
int col = findColumn(colName);
updateLong(col, b);
}
public void updateFloat(String colName, float f) throws SQLException {
int col = findColumn(colName);
updateFloat(col, f);
}
public void updateDouble(String colName, double f) throws SQLException {
int col = findColumn(colName);
updateDouble(col, f);
}
public void updateBigDecimal(String colName, BigDecimal f)
throws SQLException {
int col = findColumn(colName);
updateBigDecimal(col, f);
}
public void updateString(String colName, String s) throws SQLException {
int col = findColumn(colName);
updateString(col, s);
}
public void updateBytes(String colName, byte[] s) throws SQLException {
int col = findColumn(colName);
updateBytes(col, s);
}
public void updateDate(String colName, java.sql.Date d)
throws SQLException {
int col = findColumn(colName);
updateDate(col, d);
}
public void updateTime(String colName, java.sql.Time t)
throws SQLException {
int col = findColumn(colName);
updateTime(col, t);
}
public void updateTimestamp(String colName, java.sql.Timestamp t)
throws SQLException {
int col = findColumn(colName);
updateTimestamp(col, t);
}
public void updateAsciiStream(String colName, java.io.InputStream in,
int s)
throws SQLException {
int col = findColumn(colName);
updateAsciiStream(col, in, s);
}
public void updateBinaryStream(String colName, java.io.InputStream in,
int s)
throws SQLException {
int col = findColumn(colName);
updateBinaryStream(col, in, s);
}
public void updateCharacterStream(String colName, java.io.Reader in,
int s)
throws SQLException {
int col = findColumn(colName);
updateCharacterStream(col, in, s);
}
public void updateObject(String colName, Object obj)
throws SQLException {
int col = findColumn(colName);
updateObject(col, obj);
}
public void updateObject(String colName, Object obj, int s)
throws SQLException {
int col = findColumn(colName);
updateObject(col, obj, s);
}
public Statement getStatement() throws SQLException {
if (s == null) {
throw new SQLException("stale result set");
}
return s;
}
public void close() throws SQLException {
s = null;
tr = null;
lastg = null;
oninsrow = false;
rowbuf = null;
row = -1;
}
public java.net.URL getURL(int colIndex) throws SQLException {
if (tr == null || colIndex < 1 || colIndex > tr.ncolumns) {
throw new SQLException("column " + colIndex + " not found");
}
String rd[] = (String []) tr.rows.elementAt(row);
lastg = rd[colIndex - 1];
java.net.URL url = null;
if (lastg == null) {
return url;
}
try {
url = new java.net.URL(lastg);
} catch (java.lang.Exception e) {
url = null;
}
return url;
}
public java.net.URL getURL(String colName) throws SQLException {
int col = findColumn(colName);
return getURL(col);
}
public void updateRef(int colIndex, java.sql.Ref x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateRef(String colName, java.sql.Ref x)
throws SQLException {
int col = findColumn(colName);
updateRef(col, x);
}
public void updateBlob(int colIndex, java.sql.Blob x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateBlob(String colName, java.sql.Blob x)
throws SQLException {
int col = findColumn(colName);
updateBlob(col, x);
}
public void updateClob(int colIndex, java.sql.Clob x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateClob(String colName, java.sql.Clob x)
throws SQLException {
int col = findColumn(colName);
updateClob(col, x);
}
public void updateArray(int colIndex, java.sql.Array x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateArray(String colName, java.sql.Array x)
throws SQLException {
int col = findColumn(colName);
updateArray(col, x);
}
public RowId getRowId(int colIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public RowId getRowId(String colName) throws SQLException {
int col = findColumn(colName);
return getRowId(col);
}
public void updateRowId(int colIndex, RowId x) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateRowId(String colName, RowId x) throws SQLException {
int col = findColumn(colName);
updateRowId(col, x);
}
public int getHoldability() throws SQLException {
return ResultSet.CLOSE_CURSORS_AT_COMMIT;
}
public boolean isClosed() throws SQLException {
return tr == null;
}
public void updateNString(int colIndex, String nString)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateNString(String colName, String nString)
throws SQLException {
int col = findColumn(colName);
updateNString(col, nString);
}
public void updateNClob(int colIndex, NClob nclob)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateNClob(String colName, NClob nclob)
throws SQLException {
int col = findColumn(colName);
updateNClob(col, nclob);
}
public NClob getNClob(int colIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public NClob getNClob(String colName) throws SQLException {
int col = findColumn(colName);
return getNClob(col);
}
public SQLXML getSQLXML(int colIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public SQLXML getSQLXML(String colName) throws SQLException {
int col = findColumn(colName);
return getSQLXML(col);
}
public void updateSQLXML(int colIndex, SQLXML xml)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateSQLXML(String colName, SQLXML xml)
throws SQLException {
int col = findColumn(colName);
updateSQLXML(col, xml);
}
public String getNString(int colIndex) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public String getNString(String colName) throws SQLException {
int col = findColumn(colName);
return getNString(col);
}
public java.io.Reader getNCharacterStream(int colIndex)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public java.io.Reader getNCharacterStream(String colName)
throws SQLException {
int col = findColumn(colName);
return getNCharacterStream(col);
}
public void updateNCharacterStream(int colIndex, java.io.Reader x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateNCharacterStream(String colName, java.io.Reader x,
long len)
throws SQLException {
int col = findColumn(colName);
updateNCharacterStream(col, x, len);
}
public void updateAsciiStream(int colIndex, java.io.InputStream x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateAsciiStream(String colName, java.io.InputStream x,
long len)
throws SQLException {
int col = findColumn(colName);
updateAsciiStream(col, x, len);
}
public void updateBinaryStream(int colIndex, java.io.InputStream x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateBinaryStream(String colName, java.io.InputStream x,
long len)
throws SQLException {
int col = findColumn(colName);
updateBinaryStream(col, x, len);
}
public void updateCharacterStream(int colIndex, java.io.Reader x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateCharacterStream(String colName, java.io.Reader x,
long len)
throws SQLException {
int col = findColumn(colName);
updateCharacterStream(col, x, len);
}
public void updateBlob(int colIndex, java.io.InputStream x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateBlob(String colName, java.io.InputStream x,
long len)
throws SQLException {
int col = findColumn(colName);
updateBlob(col, x, len);
}
public void updateClob(int colIndex, java.io.Reader x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateClob(String colName, java.io.Reader x,
long len)
throws SQLException {
int col = findColumn(colName);
updateClob(col, x, len);
}
public void updateNClob(int colIndex, java.io.Reader x,
long len)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateNClob(String colName, java.io.Reader x,
long len)
throws SQLException {
int col = findColumn(colName);
updateNClob(col, x, len);
}
public void updateNCharacterStream(int colIndex, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateNCharacterStream(String colName, java.io.Reader x)
throws SQLException {
int col = findColumn(colName);
updateNCharacterStream(col, x);
}
public void updateAsciiStream(int colIndex, java.io.InputStream x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateAsciiStream(String colName, java.io.InputStream x)
throws SQLException {
int col = findColumn(colName);
updateAsciiStream(col, x);
}
public void updateBinaryStream(int colIndex, java.io.InputStream x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateBinaryStream(String colName, java.io.InputStream x)
throws SQLException {
int col = findColumn(colName);
updateBinaryStream(col, x);
}
public void updateCharacterStream(int colIndex, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateCharacterStream(String colName, java.io.Reader x)
throws SQLException {
int col = findColumn(colName);
updateCharacterStream(col, x);
}
public void updateBlob(int colIndex, java.io.InputStream x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateBlob(String colName, java.io.InputStream x)
throws SQLException {
int col = findColumn(colName);
updateBlob(col, x);
}
public void updateClob(int colIndex, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateClob(String colName, java.io.Reader x)
throws SQLException {
int col = findColumn(colName);
updateClob(col, x);
}
public void updateNClob(int colIndex, java.io.Reader x)
throws SQLException {
throw new SQLFeatureNotSupportedException();
}
public void updateNClob(String colName, java.io.Reader x)
throws SQLException {
int col = findColumn(colName);
updateNClob(col, x);
}
public <T> T unwrap(java.lang.Class<T> iface) throws SQLException {
throw new SQLException("unsupported");
}
public boolean isWrapperFor(java.lang.Class iface) throws SQLException {
return false;
}
}
| Java |
package jsqlite;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* SQLite command line shell. This is a partial reimplementation
* of sqlite/src/shell.c and can be invoked by:<P>
*
* <verb>
* java jsqlite.Shell [OPTIONS] database [SHELLCMD]
* or
* java -jar sqlite.jar [OPTIONS] database [SHELLCMD]
* </verb>
*/
public class Shell implements Callback {
Database db;
boolean echo;
int count;
int mode;
boolean showHeader;
String tableName;
String sep;
String cols[];
int colwidth[];
String destTable;
PrintWriter pw;
PrintWriter err;
static final int MODE_Line = 0;
static final int MODE_Column = 1;
static final int MODE_List = 2;
static final int MODE_Semi = 3;
static final int MODE_Html = 4;
static final int MODE_Insert = 5;
static final int MODE_Insert2 = 6;
public Shell(PrintWriter pw, PrintWriter err) {
this.pw = pw;
this.err = err;
}
public Shell(PrintStream ps, PrintStream errs) {
pw = new PrintWriter(ps);
err = new PrintWriter(errs);
}
protected Object clone() {
Shell s = new Shell(this.pw, this.err);
s.db = db;
s.echo = echo;
s.mode = mode;
s.count = 0;
s.showHeader = showHeader;
s.tableName = tableName;
s.sep = sep;
s.colwidth = colwidth;
return s;
}
static public String sql_quote_dbl(String str) {
if (str == null) {
return "NULL";
}
int i, single = 0, dbl = 0;
for (i = 0; i < str.length(); i++) {
if (str.charAt(i) == '\'') {
single++;
} else if (str.charAt(i) == '"') {
dbl++;
}
}
if (dbl == 0) {
return "\"" + str + "\"";
}
StringBuffer sb = new StringBuffer("\"");
for (i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '"') {
sb.append("\"\"");
} else {
sb.append(c);
}
}
return sb.toString();
}
static public String sql_quote(String str) {
if (str == null) {
return "NULL";
}
int i, single = 0, dbl = 0;
for (i = 0; i < str.length(); i++) {
if (str.charAt(i) == '\'') {
single++;
} else if (str.charAt(i) == '"') {
dbl++;
}
}
if (single == 0) {
return "'" + str + "'";
}
if (dbl == 0) {
return "\"" + str + "\"";
}
StringBuffer sb = new StringBuffer("'");
for (i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '\'') {
sb.append("''");
} else {
sb.append(c);
}
}
return sb.toString();
}
static String html_quote(String str) {
if (str == null) {
return "NULL";
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '<') {
sb.append("<");
} else if (c == '>') {
sb.append(">");
} else if (c == '&') {
sb.append("&");
} else {
int x = c;
if (x < 32 || x > 127) {
sb.append("&#" + x + ";");
} else {
sb.append(c);
}
}
}
return sb.toString();
}
static boolean is_numeric(String str) {
try {
Double d = Double.valueOf(str);
} catch (java.lang.Exception e) {
return false;
}
return true;
}
void set_table_name(String str) {
if (str == null) {
tableName = "";
return;
}
if (db.is3()) {
tableName = Shell.sql_quote_dbl(str);
} else {
tableName = Shell.sql_quote(str);
}
}
public void columns(String args[]) {
cols = args;
}
public void types(String args[]) {
/* Empty body to satisfy jsqlite.Callback interface. */
}
public boolean newrow(String args[]) {
int i;
String tname;
switch (mode) {
case Shell.MODE_Line:
if (args.length == 0) {
break;
}
if (count++ > 0) {
pw.println("");
}
for (i = 0; i < args.length; i++) {
pw.println(cols[i] + " = " +
args[i] == null ? "NULL" : args[i]);
}
break;
case Shell.MODE_Column:
String csep = "";
if (count++ == 0) {
colwidth = new int[args.length];
for (i = 0; i < args.length; i++) {
int w;
w = cols[i].length();
if (w < 10) {
w = 10;
}
colwidth[i] = w;
if (showHeader) {
pw.print(csep + cols[i]);
csep = " ";
}
}
if (showHeader) {
pw.println("");
}
}
if (args.length == 0) {
break;
}
csep = "";
for (i = 0; i < args.length; i++) {
pw.print(csep + (args[i] == null ? "NULL" : args[i]));
csep = " ";
}
pw.println("");
break;
case Shell.MODE_Semi:
case Shell.MODE_List:
if (count++ == 0 && showHeader) {
for (i = 0; i < args.length; i++) {
pw.print(cols[i] +
(i == args.length - 1 ? "\n" : sep));
}
}
if (args.length == 0) {
break;
}
for (i = 0; i < args.length; i++) {
pw.print(args[i] == null ? "NULL" : args[i]);
if (mode == Shell.MODE_Semi) {
pw.print(";");
} else if (i < args.length - 1) {
pw.print(sep);
}
}
pw.println("");
break;
case MODE_Html:
if (count++ == 0 && showHeader) {
pw.print("<TR>");
for (i = 0; i < args.length; i++) {
pw.print("<TH>" + html_quote(cols[i]) + "</TH>");
}
pw.println("</TR>");
}
if (args.length == 0) {
break;
}
pw.print("<TR>");
for (i = 0; i < args.length; i++) {
pw.print("<TD>" + html_quote(args[i]) + "</TD>");
}
pw.println("</TR>");
break;
case MODE_Insert:
if (args.length == 0) {
break;
}
tname = tableName;
if (destTable != null) {
tname = destTable;
}
pw.print("INSERT INTO " + tname + " VALUES(");
for (i = 0; i < args.length; i++) {
String tsep = i > 0 ? "," : "";
if (args[i] == null) {
pw.print(tsep + "NULL");
} else if (is_numeric(args[i])) {
pw.print(tsep + args[i]);
} else {
pw.print(tsep + sql_quote(args[i]));
}
}
pw.println(");");
break;
case MODE_Insert2:
if (args.length == 0) {
break;
}
tname = tableName;
if (destTable != null) {
tname = destTable;
}
pw.print("INSERT INTO " + tname + " VALUES(");
for (i = 0; i < args.length; i++) {
String tsep = i > 0 ? "," : "";
pw.print(tsep + args[i]);
}
pw.println(");");
break;
}
return false;
}
void do_meta(String line) {
StringTokenizer st = new StringTokenizer(line.toLowerCase());
int n = st.countTokens();
if (n <= 0) {
return;
}
String cmd = st.nextToken();
String args[] = new String[n - 1];
int i = 0;
while (st.hasMoreTokens()) {
args[i] = st.nextToken();
++i;
}
if (cmd.compareTo(".dump") == 0) {
new DBDump(this, args);
return;
}
if (cmd.compareTo(".echo") == 0) {
if (args.length > 0 &&
(args[0].startsWith("y") || args[0].startsWith("on"))) {
echo = true;
}
return;
}
if (cmd.compareTo(".exit") == 0) {
try {
db.close();
} catch (Exception e) {
}
System.exit(0);
}
if (cmd.compareTo(".header") == 0) {
if (args.length > 0 &&
(args[0].startsWith("y") || args[0].startsWith("on"))) {
showHeader = true;
}
return;
}
if (cmd.compareTo(".help") == 0) {
pw.println(".dump ?TABLE? ... Dump database in text fmt");
pw.println(".echo ON|OFF Command echo on or off");
pw.println(".enc ?NAME? Change encoding");
pw.println(".exit Exit program");
pw.println(".header ON|OFF Display headers on or off");
pw.println(".help This message");
pw.println(".mode MODE Set output mode to\n" +
" line, column, insert\n" +
" list, or html");
pw.println(".mode insert TABLE Generate SQL insert stmts");
pw.println(".schema ?PATTERN? List table schema");
pw.println(".separator STRING Set separator string");
pw.println(".tables ?PATTERN? List table names");
return;
}
if (cmd.compareTo(".mode") == 0) {
if (args.length > 0) {
if (args[0].compareTo("line") == 0) {
mode = Shell.MODE_Line;
} else if (args[0].compareTo("column") == 0) {
mode = Shell.MODE_Column;
} else if (args[0].compareTo("list") == 0) {
mode = Shell.MODE_List;
} else if (args[0].compareTo("html") == 0) {
mode = Shell.MODE_Html;
} else if (args[0].compareTo("insert") == 0) {
mode = Shell.MODE_Insert;
if (args.length > 1) {
destTable = args[1];
}
}
}
return;
}
if (cmd.compareTo(".separator") == 0) {
if (args.length > 0) {
sep = args[0];
}
return;
}
if (cmd.compareTo(".tables") == 0) {
TableResult t = null;
if (args.length > 0) {
try {
String qarg[] = new String[1];
qarg[0] = args[0];
t = db.get_table("SELECT name FROM sqlite_master " +
"WHERE type='table' AND " +
"name LIKE '%%%q%%' " +
"ORDER BY name", qarg);
} catch (Exception e) {
err.println("SQL Error: " + e);
err.flush();
}
} else {
try {
t = db.get_table("SELECT name FROM sqlite_master " +
"WHERE type='table' ORDER BY name");
} catch (Exception e) {
err.println("SQL Error: " + e);
err.flush();
}
}
if (t != null) {
for (i = 0; i < t.nrows; i++) {
String tab = ((String[]) t.rows.elementAt(i))[0];
if (tab != null) {
pw.println(tab);
}
}
}
return;
}
if (cmd.compareTo(".schema") == 0) {
if (args.length > 0) {
try {
String qarg[] = new String[1];
qarg[0] = args[0];
db.exec("SELECT sql FROM sqlite_master " +
"WHERE type!='meta' AND " +
"name LIKE '%%%q%%' AND " +
"sql NOTNULL " +
"ORDER BY type DESC, name",
this, qarg);
} catch (Exception e) {
err.println("SQL Error: " + e);
err.flush();
}
} else {
try {
db.exec("SELECT sql FROM sqlite_master " +
"WHERE type!='meta' AND " +
"sql NOTNULL " +
"ORDER BY tbl_name, type DESC, name",
this);
} catch (Exception e) {
err.println("SQL Error: " + e);
err.flush();
}
}
return;
}
if (cmd.compareTo(".enc") == 0) {
try {
db.set_encoding(args.length > 0 ? args[0] : null);
} catch (Exception e) {
err.println("" + e);
err.flush();
}
return;
}
if (cmd.compareTo(".rekey") == 0) {
try {
db.rekey(args.length > 0 ? args[0] : null);
} catch (Exception e) {
err.println("" + e);
err.flush();
}
return;
}
err.println("Unknown command '" + cmd + "'");
err.flush();
}
String read_line(BufferedReader is, String prompt) {
try {
if (prompt != null) {
pw.print(prompt);
pw.flush();
}
String line = is.readLine();
return line;
} catch (IOException e) {
return null;
}
}
void do_input(BufferedReader is) {
String line, sql = null;
String prompt = "SQLITE> ";
while ((line = read_line(is, prompt)) != null) {
if (echo) {
pw.println(line);
}
if (line.length() > 0 && line.charAt(0) == '.') {
do_meta(line);
} else {
if (sql == null) {
sql = line;
} else {
sql = sql + " " + line;
}
if (Database.complete(sql)) {
try {
db.exec(sql, this);
} catch (Exception e) {
if (!echo) {
err.println(sql);
}
err.println("SQL Error: " + e);
err.flush();
}
sql = null;
prompt = "SQLITE> ";
} else {
prompt = "SQLITE? ";
}
}
pw.flush();
}
if (sql != null) {
err.println("Incomplete SQL: " + sql);
err.flush();
}
}
void do_cmd(String sql) {
if (db == null) {
return;
}
if (sql.length() > 0 && sql.charAt(0) == '.') {
do_meta(sql);
} else {
try {
db.exec(sql, this);
} catch (Exception e) {
err.println("SQL Error: " + e);
err.flush();
}
}
}
public static void main(String args[]) {
String key = null;
Shell s = new Shell(System.out, System.err);
s.mode = Shell.MODE_List;
s.sep = "|";
s.showHeader = false;
s.db = new Database();
String dbname = null, sql = null;
for (int i = 0; i < args.length; i++) {
if(args[i].compareTo("-html") ==0) {
s.mode = Shell.MODE_Html;
} else if (args[i].compareTo("-list") == 0) {
s.mode = Shell.MODE_List;
} else if (args[i].compareTo("-line") == 0) {
s.mode = Shell.MODE_Line;
} else if (i < args.length - 1 &&
args[i].compareTo("-separator") == 0) {
++i;
s.sep = args[i];
} else if (args[i].compareTo("-header") == 0) {
s.showHeader = true;
} else if (args[i].compareTo("-noheader") == 0) {
s.showHeader = false;
} else if (args[i].compareTo("-echo") == 0) {
s.echo = true;
} else if (args[i].compareTo("-key") == 0) {
++i;
key = args[i];
} else if (dbname == null) {
dbname = args[i];
} else if (sql == null) {
sql = args[i];
} else {
System.err.println("Arguments: ?OPTIONS? FILENAME ?SQL?");
System.exit(1);
}
}
if (dbname == null) {
System.err.println("No database file given");
System.exit(1);
}
try {
s.db.open(dbname, jsqlite.Constants.SQLITE_OPEN_READWRITE |
jsqlite.Constants.SQLITE_OPEN_CREATE);
} catch (Exception e) {
System.err.println("Unable to open database: " + e);
System.exit(1);
}
if (key != null) {
try {
s.db.key(key);
} catch (Exception e) {
System.err.println("Unable to set key: " + e);
System.exit(1);
}
}
if (sql != null) {
s.do_cmd(sql);
s.pw.flush();
} else {
BufferedReader is =
new BufferedReader(new InputStreamReader(System.in));
s.do_input(is);
s.pw.flush();
}
try {
s.db.close();
} catch (Exception ee) {
}
}
}
/**
* Internal class for dumping an entire database.
* It contains a special callback interface to traverse the
* tables of the current database and output create SQL statements
* and for the data insert SQL statements.
*/
class DBDump implements Callback {
Shell s;
DBDump(Shell s, String tables[]) {
this.s = s;
s.pw.println("BEGIN TRANSACTION;");
if (tables == null || tables.length == 0) {
try {
s.db.exec("SELECT name, type, sql FROM sqlite_master " +
"WHERE type!='meta' AND sql NOT NULL " +
"ORDER BY substr(type,2,1), name", this);
} catch (Exception e) {
s.err.println("SQL Error: " + e);
s.err.flush();
}
} else {
String arg[] = new String[1];
for (int i = 0; i < tables.length; i++) {
arg[0] = tables[i];
try {
s.db.exec("SELECT name, type, sql FROM sqlite_master " +
"WHERE tbl_name LIKE '%q' AND type!='meta' " +
" AND sql NOT NULL " +
" ORDER BY substr(type,2,1), name",
this, arg);
} catch (Exception e) {
s.err.println("SQL Error: " + e);
s.err.flush();
}
}
}
s.pw.println("COMMIT;");
}
public void columns(String col[]) {
/* Empty body to satisfy jsqlite.Callback interface. */
}
public void types(String args[]) {
/* Empty body to satisfy jsqlite.Callback interface. */
}
public boolean newrow(String args[]) {
if (args.length != 3) {
return true;
}
s.pw.println(args[2] + ";");
if (args[1].compareTo("table") == 0) {
Shell s2 = (Shell) s.clone();
s2.mode = Shell.MODE_Insert;
s2.set_table_name(args[0]);
String qargs[] = new String[1];
qargs[0] = args[0];
try {
if (s2.db.is3()) {
TableResult t = null;
t = s2.db.get_table("PRAGMA table_info('%q')", qargs);
String query;
if (t != null) {
StringBuffer sb = new StringBuffer();
String sep = "";
sb.append("SELECT ");
for (int i = 0; i < t.nrows; i++) {
String col = ((String[]) t.rows.elementAt(i))[1];
sb.append(sep + "quote(" +
Shell.sql_quote_dbl(col) + ")");
sep = ",";
}
sb.append(" from '%q'");
query = sb.toString();
s2.mode = Shell.MODE_Insert2;
} else {
query = "SELECT * from '%q'";
}
s2.db.exec(query, s2, qargs);
} else {
s2.db.exec("SELECT * from '%q'", s2, qargs);
}
} catch (Exception e) {
s.err.println("SQL Error: " + e);
s.err.flush();
return true;
}
}
return false;
}
}
| Java |
package jsqlite;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* SQLite SQL restore utility.
*/
public class SQLRestore {
BufferedReader is;
Database db;
public SQLRestore(InputStream is, Database db) {
this.is = new BufferedReader(new InputStreamReader(is));
this.db = db;
}
public void restore() throws jsqlite.Exception {
String line = null, sql = null;
while (true) {
try {
line = is.readLine();
} catch (EOFException e) {
line = null;
} catch (IOException e) {
throw new jsqlite.Exception("I/O error: " + e);
}
if (line == null) {
break;
}
if (sql == null) {
sql = line;
} else {
sql = sql + " " + line;
}
if (Database.complete(sql)) {
db.exec(sql, null);
sql = null;
}
}
if (sql != null) {
throw new jsqlite.Exception("Incomplete SQL: " + sql);
}
}
}
| Java |
package jsqlite;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* SQLite SQL dump utility.
*/
public class SQLDump implements Callback {
PrintWriter pw;
PrintWriter err;
Database db;
Shell s;
public SQLDump(PrintWriter pw, Database db) {
this.pw = pw;
this.err = this.pw;
this.db = db;
s = new Shell(this.pw, this.err);
s.mode = Shell.MODE_Insert;
s.db = db;
}
public SQLDump(PrintStream ps, Database db) {
this.pw = new PrintWriter(ps);
this.err = this.pw;
this.db = db;
s = new Shell(this.pw, this.err);
s.mode = Shell.MODE_Insert;
s.db = db;
}
public void dump() throws jsqlite.Exception {
pw.println("BEGIN TRANSACTION;");
db.exec("SELECT name, type, sql FROM sqlite_master " +
"WHERE type!='meta' AND sql NOT NULL " +
"ORDER BY substr(type,2,1), name", this);
pw.println("COMMIT;");
pw.flush();
}
public void columns(String col[]) {
/* Empty body to satisfy jsqlite.Callback interface. */
}
public void types(String args[]) {
/* Empty body to satisfy jsqlite.Callback interface. */
}
public boolean newrow(String args[]) {
if (args.length != 3) {
return true;
}
pw.println(args[2] + ";");
if (args[1].compareTo("table") == 0) {
s.mode = Shell.MODE_Insert;
s.set_table_name(args[0]);
String qargs[] = new String[1];
qargs[0] = args[0];
try {
if (s.db.is3()) {
TableResult t = null;
t = s.db.get_table("PRAGMA table_info('%q')", qargs);
String query;
if (t != null) {
StringBuffer sb = new StringBuffer();
String sep = "";
sb.append("SELECT ");
for (int i = 0; i < t.nrows; i++) {
String col = ((String[]) t.rows.elementAt(i))[1];
sb.append(sep + "quote(" +
Shell.sql_quote_dbl(col) + ")");
sep = ",";
}
sb.append(" from '%q'");
query = sb.toString();
s.mode = Shell.MODE_Insert2;
} else {
query = "SELECT * from '%q'";
}
s.db.exec(query, s, qargs);
pw.flush();
} else {
s.db.exec("SELECT * from '%q'", s, qargs);
pw.flush();
}
} catch (Exception e) {
return true;
}
}
s.mode = Shell.MODE_Line;
return false;
}
}
| Java |
package jsqlite;
/**
* Class to represent compiled SQLite VM.
*/
public class Vm {
/**
* Internal handle for the compiled SQLite VM.
*/
private long handle = 0;
/**
* Internal last error code for compile()/step() methods.
*/
protected int error_code = 0;
/**
* Perform one step on compiled SQLite VM.
* The result row is passed to the given callback interface.<BR><BR>
*
* Example:<BR>
* <PRE>
* ...
* try {
* Vm vm = db.compile("select * from x; select * from y;");
* while (vm.step(cb)) {
* ...
* }
* while (vm.compile()) {
* while (vm.step(cb)) {
* ...
* }
* }
* } catch (SQLite.Exception e) {
* }
* </PRE>
*
* @param cb the object implementing the callback methods.
* @return true as long as more row data can be retrieved,
* false, otherwise.
*/
public native boolean step(Callback cb) throws jsqlite.Exception;
/**
* Compile the next SQL statement for the SQLite VM instance.
* @return true when SQL statement has been compiled, false
* on end of statement sequence.
*/
public native boolean compile() throws jsqlite.Exception;
/**
* Abort the compiled SQLite VM.
*/
public native void stop() throws jsqlite.Exception;
/**
* Destructor for object.
*/
protected native void finalize();
/**
* Internal native initializer.
*/
private static native void internal_init();
static {
internal_init();
}
}
| Java |
package jsqlite;
/**
* Callback interface for SQLite's user defined progress handler.
*/
public interface ProgressHandler {
/**
* Invoked for N SQLite VM opcodes.
* The method should return true to continue the
* current query, or false in order
* to abandon the action.<BR><BR>
*/
public boolean progress();
}
| Java |
package jsqlite;
/**
* Callback interface for SQLite's profile function.
*/
public interface Profile {
/**
* Callback to profile (ie log) one SQL statement
* with its estimated execution time.
*
* @param stmt SQL statement string
* @param est estimated execution time in milliseconds.
*/
public void profile(String stmt, long est);
}
| Java |
/*
* This is a sample implementation of the
* Transaction Processing Performance Council
* Benchmark B coded in Java/JDBC and ANSI SQL2.
*
* This version is using one connection per
* thread to parallellize server operations.
*/
package jsqlite;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Vector;
public abstract class Benchmark {
/* the tps scaling factor: here it is 1 */
public static int tps = 1;
/* number of branches in 1 tps db */
public static int nbranches = 1;
/* number of tellers in 1 tps db */
public static int ntellers = 10;
/* number of accounts in 1 tps db */
public static int naccounts = 50000;
/* number of history recs in 1 tps db */
public static int nhistory = 864000;
public final static int TELLER = 0;
public final static int BRANCH = 1;
public final static int ACCOUNT = 2;
int failed_transactions = 0;
int transaction_count = 0;
static int n_clients = 10;
static int n_txn_per_client = 10;
long start_time = 0;
static boolean transactions = true;
static boolean prepared_stmt = false;
static boolean verbose = false;
/*
* main program
* creates a 1-tps database:
* i.e. 1 branch, 10 tellers,...
* runs one TPC BM B transaction
*/
public void run(String[] args) {
String DriverName = "";
String DBUrl = "";
String DBUser = "";
String DBPassword = "";
boolean initialize_dataset = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-clients")) {
if (i + 1 < args.length) {
i++;
n_clients = Integer.parseInt(args[i]);
}
} else if (args[i].equals("-driver")) {
if (i + 1 < args.length) {
i++;
DriverName = args[i];
}
} else if (args[i].equals("-url")) {
if (i + 1 < args.length) {
i++;
DBUrl = args[i];
}
} else if (args[i].equals("-user")) {
if (i + 1 < args.length) {
i++;
DBUser = args[i];
}
} else if (args[i].equals("-password")) {
if (i + 1 < args.length) {
i++;
DBPassword = args[i];
}
} else if (args[i].equals("-tpc")) {
if (i + 1 < args.length) {
i++;
n_txn_per_client = Integer.parseInt(args[i]);
}
} else if (args[i].equals("-init")) {
initialize_dataset = true;
} else if (args[i].equals("-tps")) {
if (i + 1 < args.length) {
i++;
tps = Integer.parseInt(args[i]);
}
} else if (args[i].equals("-v")) {
verbose = true;
}
}
if (DriverName.length() == 0 || DBUrl.length() == 0) {
System.out.println("JDBC based benchmark program\n\n" +
"JRE usage:\n\njava jsqlite.BenchmarkDriver " +
"-url [url_to_db] \\\n " +
"[-user [username]] " +
"[-password [password]] " +
"[-driver [driver_class_name]] \\\n " +
"[-v] [-init] [-tpc N] [-tps N] " +
"[-clients N]\n");
System.out.println("OJEC usage:\n\ncvm jsqlite.BenchmarkDataSource " +
"[-user [username]] " +
"[-password [password]] " +
"[-driver [driver_class_name]] \\\n " +
"[-v] [-init] [-tpc N] [-tps N] " +
"[-clients N]\n");
System.out.println();
System.out.println("-v verbose mode");
System.out.println("-init initialize the tables");
System.out.println("-tpc N transactions per client");
System.out.println("-tps N scale factor");
System.out.println("-clients N number of simultaneous clients/threads");
System.out.println();
System.out.println("Default driver class is jsqlite.JDBCDriver");
System.out.println("in this case use an -url parameter of the form");
System.out.println(" jdbc:sqlite:/[path]");
System.exit(1);
}
System.out.println("Driver: " + DriverName);
System.out.println("URL:" + DBUrl);
System.out.println();
System.out.println("Scale factor value: " + tps);
System.out.println("Number of clients: " + n_clients);
System.out.println("Number of transactions per client: " +
n_txn_per_client);
System.out.println();
try {
benchmark(DBUrl, DBUser, DBPassword, initialize_dataset);
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void benchmark(String url, String user, String password, boolean init) {
Vector vClient = new Vector();
Thread Client = null;
Enumeration en = null;
try {
if (init) {
System.out.print("Initializing dataset...");
createDatabase(url, user, password);
System.out.println("done.\n");
}
System.out.println("* Starting Benchmark Run *");
transactions = false;
prepared_stmt = false;
start_time = System.currentTimeMillis();
for (int i = 0; i < n_clients; i++) {
Client = new BenchmarkThread(n_txn_per_client, url, user,
password, this);
Client.start();
vClient.addElement(Client);
}
/*
* Barrier to complete this test session
*/
en = vClient.elements();
while (en.hasMoreElements()) {
Client = (Thread) en.nextElement();
Client.join();
}
vClient.removeAllElements();
reportDone();
transactions = true;
prepared_stmt = false;
start_time = System.currentTimeMillis();
for (int i = 0; i < n_clients; i++) {
Client = new BenchmarkThread(n_txn_per_client, url,
user, password, this);
Client.start();
vClient.addElement(Client);
}
/*
* Barrier to complete this test session
*/
en = vClient.elements();
while (en.hasMoreElements()) {
Client = (Thread) en.nextElement();
Client.join();
}
vClient.removeAllElements();
reportDone();
transactions = false;
prepared_stmt = true;
start_time = System.currentTimeMillis();
for (int i = 0; i < n_clients; i++) {
Client = new BenchmarkThread(n_txn_per_client, url,
user, password, this);
Client.start();
vClient.addElement(Client);
}
/*
* Barrier to complete this test session
*/
en = vClient.elements();
while (en.hasMoreElements()) {
Client = (Thread) en.nextElement();
Client.join();
}
vClient.removeAllElements();
reportDone();
transactions = true;
prepared_stmt = true;
start_time = System.currentTimeMillis();
for (int i = 0; i < n_clients; i++) {
Client = new BenchmarkThread(n_txn_per_client, url,
user, password, this);
Client.start();
vClient.addElement(Client);
}
/*
* Barrier to complete this test session
*/
en = vClient.elements();
while (en.hasMoreElements()) {
Client = (Thread) en.nextElement();
Client.join();
}
vClient.removeAllElements();
reportDone();
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
System.exit(0);
}
}
public void reportDone() {
long end_time = System.currentTimeMillis();
double completion_time =
((double)end_time - (double)start_time) / 1000;
System.out.println("\n* Benchmark Report *" );
System.out.print("* Featuring ");
if (prepared_stmt) {
System.out.print("<prepared statements> ");
} else {
System.out.print("<direct queries> ");
}
if (transactions) {
System.out.print("<transactions> ");
} else {
System.out.print("<auto-commit> ");
}
System.out.println("\n--------------------");
System.out.println("Time to execute " +
transaction_count + " transactions: " +
completion_time + " seconds.");
System.out.println(failed_transactions + " / " +
transaction_count + " failed to complete.");
double rate = (transaction_count - failed_transactions)
/ completion_time;
System.out.println("Transaction rate: " + rate + " txn/sec.");
transaction_count = 0;
failed_transactions = 0;
System.gc();
}
public synchronized void incrementTransactionCount() {
transaction_count++;
}
public synchronized void incrementFailedTransactionCount() {
failed_transactions++;
}
void createDatabase(String url, String user, String password)
throws java.lang.Exception {
Connection Conn = connect(url, user, password);
String s = Conn.getMetaData().getDatabaseProductName();
System.out.println("DBMS: "+s);
transactions = true;
if (transactions) {
try {
Conn.setAutoCommit(false);
System.out.println("In transaction mode");
} catch (SQLException etxn) {
transactions = false;
}
}
try {
int accountsnb = 0;
Statement Stmt = Conn.createStatement();
String Query;
Query = "SELECT count(*) FROM accounts";
ResultSet RS = Stmt.executeQuery(Query);
Stmt.clearWarnings();
while (RS.next()) {
accountsnb = RS.getInt(1);
}
if (transactions) {
Conn.commit();
}
Stmt.close();
if (accountsnb == (naccounts*tps)) {
System.out.println("Already initialized");
connectClose(Conn);
return;
}
} catch (java.lang.Exception e) {
}
System.out.println("Drop old tables if they exist");
try {
Statement Stmt = Conn.createStatement();
String Query;
Query = "DROP TABLE history";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DROP TABLE accounts";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DROP TABLE tellers";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DROP TABLE branches";
Stmt.execute(Query);
Stmt.clearWarnings();
if (transactions) {
Conn.commit();
}
Stmt.close();
} catch (java.lang.Exception e) {
}
System.out.println("Creates tables");
try {
Statement Stmt = Conn.createStatement();
String Query;
Query = "CREATE TABLE branches (";
Query += "Bid INTEGER NOT NULL PRIMARY KEY,";
Query += "Bbalance INTEGER,";
Query += "filler CHAR(88))"; /* pad to 100 bytes */
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "CREATE TABLE tellers (";
Query += "Tid INTEGER NOT NULL PRIMARY KEY,";
Query += "Bid INTEGER,";
Query += "Tbalance INTEGER,";
Query += "filler CHAR(84))"; /* pad to 100 bytes */
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "CREATE TABLE accounts (";
Query += "Aid INTEGER NOT NULL PRIMARY KEY,";
Query += "Bid INTEGER,";
Query += "Abalance INTEGER,";
Query += "filler CHAR(84))"; /* pad to 100 bytes */
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "CREATE TABLE history (";
Query += "Tid INTEGER,";
Query += "Bid INTEGER,";
Query += "Aid INTEGER,";
Query += "delta INTEGER,";
Query += "tstime TIMESTAMP,";
Query += "filler CHAR(22))"; /* pad to 50 bytes */
Stmt.execute(Query);
Stmt.clearWarnings();
if (transactions) {
Conn.commit();
}
Stmt.close();
} catch (java.lang.Exception e) {
}
System.out.println("Delete elements in table in case DROP didn't work");
try {
Statement Stmt = Conn.createStatement();
String Query;
Query = "DELETE FROM history";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DELETE FROM accounts";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DELETE FROM tellers";
Stmt.execute(Query);
Stmt.clearWarnings();
Query = "DELETE FROM branches";
Stmt.execute(Query);
Stmt.clearWarnings();
if (transactions) {
Conn.commit();
}
/*
* prime database using TPC BM B scaling rules.
* Note that for each branch and teller:
* branch_id = teller_id / ntellers
* branch_id = account_id / naccounts
*/
PreparedStatement pstmt = null;
prepared_stmt = true;
if (prepared_stmt) {
try {
Query = "INSERT INTO branches(Bid,Bbalance) VALUES (?,0)";
pstmt = Conn.prepareStatement(Query);
System.out.println("Using prepared statements");
} catch (SQLException estmt) {
pstmt = null;
prepared_stmt = false;
}
}
System.out.println("Insert data in branches table");
for (int i = 0; i < nbranches * tps; i++) {
if (prepared_stmt) {
pstmt.setInt(1,i);
pstmt.executeUpdate();
pstmt.clearWarnings();
} else {
Query = "INSERT INTO branches(Bid,Bbalance) VALUES (" +
i + ",0)";
Stmt.executeUpdate(Query);
}
if ((i%100==0) && (transactions)) {
Conn.commit();
}
}
if (prepared_stmt) {
pstmt.close();
}
if (transactions) {
Conn.commit();
}
if (prepared_stmt) {
Query = "INSERT INTO tellers(Tid,Bid,Tbalance) VALUES (?,?,0)";
pstmt = Conn.prepareStatement(Query);
}
System.out.println("Insert data in tellers table");
for (int i = 0; i < ntellers * tps; i++) {
if (prepared_stmt) {
pstmt.setInt(1,i);
pstmt.setInt(2,i/ntellers);
pstmt.executeUpdate();
pstmt.clearWarnings();
} else {
Query = "INSERT INTO tellers(Tid,Bid,Tbalance) VALUES (" +
i + "," + i / ntellers + ",0)";
Stmt.executeUpdate(Query);
}
if ((i%100==0) && (transactions)) {
Conn.commit();
}
}
if (prepared_stmt) {
pstmt.close();
}
if (transactions) {
Conn.commit();
}
if (prepared_stmt) {
Query = "INSERT INTO accounts(Aid,Bid,Abalance) VALUES (?,?,0)";
pstmt = Conn.prepareStatement(Query);
}
System.out.println("Insert data in accounts table");
for (int i = 0; i < naccounts*tps; i++) {
if (prepared_stmt) {
pstmt.setInt(1,i);
pstmt.setInt(2,i/naccounts);
pstmt.executeUpdate();
pstmt.clearWarnings();
} else {
Query = "INSERT INTO accounts(Aid,Bid,Abalance) VALUES (" +
i + "," + i / naccounts + ",0)";
Stmt.executeUpdate(Query);
}
if ((i%10000==0) && (transactions)) {
Conn.commit();
}
if ((i>0) && ((i%10000)==0)) {
System.out.println("\t" + i + "\t records inserted");
}
}
if (prepared_stmt) {
pstmt.close();
}
if (transactions) {
Conn.commit();
}
System.out.println("\t" + (naccounts*tps) + "\t records inserted");
Stmt.close();
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
connectClose(Conn);
}
public static int getRandomInt(int lo, int hi) {
int ret = 0;
ret = (int)(Math.random() * (hi - lo + 1));
ret += lo;
return ret;
}
public static int getRandomID(int type) {
int min, max, num;
max = min = 0;
num = naccounts;
switch(type) {
case TELLER:
min += nbranches;
num = ntellers;
/* FALLTHROUGH */
case BRANCH:
if (type == BRANCH) {
num = nbranches;
}
min += naccounts;
/* FALLTHROUGH */
case ACCOUNT:
max = min + num - 1;
}
return (getRandomInt(min, max));
}
public abstract Connection connect(String DBUrl, String DBUser,
String DBPassword);
public static void connectClose(Connection c) {
if (c == null) {
return;
}
try {
c.close();
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
class BenchmarkThread extends Thread {
int ntrans = 0;
Connection Conn;
Benchmark bench;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
PreparedStatement pstmt3 = null;
PreparedStatement pstmt4 = null;
PreparedStatement pstmt5 = null;
public BenchmarkThread(int number_of_txns,String url,
String user, String password,
Benchmark b) {
bench = b;
ntrans = number_of_txns;
Conn = b.connect(url, user, password);
if (Conn == null) {
return;
}
try {
if (Benchmark.transactions) {
Conn.setAutoCommit(false);
}
if (Benchmark.prepared_stmt) {
String Query;
Query = "UPDATE accounts";
Query += " SET Abalance = Abalance + ?";
Query += " WHERE Aid = ?";
pstmt1 = Conn.prepareStatement(Query);
Query = "SELECT Abalance";
Query += " FROM accounts";
Query += " WHERE Aid = ?";
pstmt2 = Conn.prepareStatement(Query);
Query = "UPDATE tellers";
Query += " SET Tbalance = Tbalance + ?";
Query += " WHERE Tid = ?";
pstmt3 = Conn.prepareStatement(Query);
Query = "UPDATE branches";
Query += " SET Bbalance = Bbalance + ?";
Query += " WHERE Bid = ?";
pstmt4 = Conn.prepareStatement(Query);
Query = "INSERT INTO history(Tid, Bid, Aid, delta)";
Query += " VALUES (?,?,?,?)";
pstmt5 = Conn.prepareStatement(Query);
}
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void run() {
while (ntrans-- > 0) {
int account = Benchmark.getRandomID(Benchmark.ACCOUNT);
int branch = Benchmark.getRandomID(Benchmark.BRANCH);
int teller = Benchmark.getRandomID(Benchmark.TELLER);
int delta = Benchmark.getRandomInt(0, 1000);
doOne(branch, teller, account, delta);
bench.incrementTransactionCount();
}
if (Benchmark.prepared_stmt) {
try {
if (pstmt1 != null) {
pstmt1.close();
}
if (pstmt2 != null) {
pstmt2.close();
}
if (pstmt3 != null) {
pstmt3.close();
}
if (pstmt4 != null) {
pstmt4.close();
}
if (pstmt5 != null) {
pstmt5.close();
}
} catch (java.lang.Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
Benchmark.connectClose(Conn);
Conn = null;
}
/*
* Executes a single TPC BM B transaction.
*/
int doOne(int bid, int tid, int aid, int delta) {
int aBalance = 0;
if (Conn == null) {
bench.incrementFailedTransactionCount();
return 0;
}
try {
if (Benchmark.prepared_stmt) {
pstmt1.setInt(1,delta);
pstmt1.setInt(2,aid);
pstmt1.executeUpdate();
pstmt1.clearWarnings();
pstmt2.setInt(1,aid);
ResultSet RS = pstmt2.executeQuery();
pstmt2.clearWarnings();
while (RS.next()) {
aBalance = RS.getInt(1);
}
pstmt3.setInt(1,delta);
pstmt3.setInt(2,tid);
pstmt3.executeUpdate();
pstmt3.clearWarnings();
pstmt4.setInt(1,delta);
pstmt4.setInt(2,bid);
pstmt4.executeUpdate();
pstmt4.clearWarnings();
pstmt5.setInt(1,tid);
pstmt5.setInt(2,bid);
pstmt5.setInt(3,aid);
pstmt5.setInt(4,delta);
pstmt5.executeUpdate();
pstmt5.clearWarnings();
} else {
Statement Stmt = Conn.createStatement();
String Query = "UPDATE accounts";
Query += " SET Abalance = Abalance + " + delta;
Query += " WHERE Aid = " + aid;
Stmt.executeUpdate(Query);
Stmt.clearWarnings();
Query = "SELECT Abalance";
Query += " FROM accounts";
Query += " WHERE Aid = " + aid;
ResultSet RS = Stmt.executeQuery(Query);
Stmt.clearWarnings();
while (RS.next()) {
aBalance = RS.getInt(1);
}
Query = "UPDATE tellers";
Query += " SET Tbalance = Tbalance + " + delta;
Query += " WHERE Tid = " + tid;
Stmt.executeUpdate(Query);
Stmt.clearWarnings();
Query = "UPDATE branches";
Query += " SET Bbalance = Bbalance + " + delta;
Query += " WHERE Bid = " + bid;
Stmt.executeUpdate(Query);
Stmt.clearWarnings();
Query = "INSERT INTO history(Tid, Bid, Aid, delta)";
Query += " VALUES (";
Query += tid + ",";
Query += bid + ",";
Query += aid + ",";
Query += delta + ")";
Stmt.executeUpdate(Query);
Stmt.clearWarnings();
Stmt.close();
}
if (Benchmark.transactions) {
Conn.commit();
}
return aBalance;
} catch (java.lang.Exception e) {
if (Benchmark.verbose) {
System.out.println("Transaction failed: "
+ e.getMessage());
e.printStackTrace();
}
bench.incrementFailedTransactionCount();
if (Benchmark.transactions) {
try {
Conn.rollback();
} catch (SQLException e1) {
}
}
}
return 0;
}
}
| Java |
package jsqlite;
/**
* Main class wrapping an SQLite database.
*/
public class Database {
/**
* Internal handle for the native SQLite API.
*/
protected long handle = 0;
/**
* Internal last error code for exec() methods.
*/
protected int error_code = 0;
/**
* Open an SQLite database file.
*
* @param filename the name of the database file
* @param mode open mode (e.g. SQLITE_OPEN_READONLY)
*/
public void open(String filename, int mode) throws jsqlite.Exception {
if ((mode & 0200) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READWRITE |
jsqlite.Constants.SQLITE_OPEN_CREATE;
} else if ((mode & 0400) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READONLY;
}
synchronized(this) {
try {
_open4(filename, mode, null, false);
} catch (jsqlite.Exception se) {
throw se;
} catch (java.lang.OutOfMemoryError me) {
throw me;
} catch (Throwable t) {
_open(filename, mode);
}
}
}
/**
* Open an SQLite database file.
*
* @param filename the name of the database file
* @param mode open mode (e.g. SQLITE_OPEN_READONLY)
* @param vfs VFS name (for SQLite >= 3.5)
*/
public void open(String filename, int mode, String vfs)
throws jsqlite.Exception {
if ((mode & 0200) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READWRITE |
jsqlite.Constants.SQLITE_OPEN_CREATE;
} else if ((mode & 0400) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READONLY;
}
synchronized(this) {
try {
_open4(filename, mode, vfs, false);
} catch (jsqlite.Exception se) {
throw se;
} catch (java.lang.OutOfMemoryError me) {
throw me;
} catch (Throwable t) {
_open(filename, mode);
}
}
}
/**
* Open an SQLite database file.
*
* @param filename the name of the database file
* @param mode open mode (e.g. SQLITE_OPEN_READONLY)
* @param vfs VFS name (for SQLite >= 3.5)
* @param ver2 flag to force version on create (false = SQLite3, true = SQLite2)
*/
public void open(String filename, int mode, String vfs, boolean ver2)
throws jsqlite.Exception {
if ((mode & 0200) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READWRITE |
jsqlite.Constants.SQLITE_OPEN_CREATE;
} else if ((mode & 0400) != 0) {
mode = jsqlite.Constants.SQLITE_OPEN_READONLY;
}
synchronized(this) {
try {
_open4(filename, mode, vfs, ver2);
} catch (jsqlite.Exception se) {
throw se;
} catch (java.lang.OutOfMemoryError me) {
throw me;
} catch (Throwable t) {
_open(filename, mode);
}
}
}
/*
* For backward compatibility to older sqlite.jar, sqlite_jni
*/
private native void _open(String filename, int mode)
throws jsqlite.Exception;
/*
* Newer full interface
*/
private native void _open4(String filename, int mode, String vfs,
boolean ver2)
throws jsqlite.Exception;
/**
* Open SQLite auxiliary database file for temporary
* tables.
*
* @param filename the name of the auxiliary file or null
*/
public void open_aux_file(String filename) throws jsqlite.Exception {
synchronized(this) {
_open_aux_file(filename);
}
}
private native void _open_aux_file(String filename)
throws jsqlite.Exception;
/**
* Destructor for object.
*/
protected void finalize() {
synchronized(this) {
_finalize();
}
}
private native void _finalize();
/**
* Close the underlying SQLite database file.
*/
public void close() throws jsqlite.Exception {
synchronized(this) {
_close();
}
}
private native void _close()
throws jsqlite.Exception;
/**
* Execute an SQL statement and invoke callback methods
* for each row of the result set.<P>
*
* It the method fails, an SQLite.Exception is thrown and
* an error code is set, which later can be retrieved by
* the last_error() method.
*
* @param sql the SQL statement to be executed
* @param cb the object implementing the callback methods
*/
public void exec(String sql, jsqlite.Callback cb) throws jsqlite.Exception {
synchronized(this) {
_exec(sql, cb);
}
}
private native void _exec(String sql, jsqlite.Callback cb)
throws jsqlite.Exception;
/**
* Execute an SQL statement and invoke callback methods
* for each row of the result set. Each '%q' or %Q in the
* statement string is substituted by its corresponding
* element in the argument vector.
* <BR><BR>
* Example:<BR>
* <PRE>
* String args[] = new String[1];
* args[0] = "tab%";
* db.exec("select * from sqlite_master where type like '%q'",
* null, args);
* </PRE>
*
* It the method fails, an SQLite.Exception is thrown and
* an error code is set, which later can be retrieved by
* the last_error() method.
*
* @param sql the SQL statement to be executed
* @param cb the object implementing the callback methods
* @param args arguments for the SQL statement, '%q' substitution
*/
public void exec(String sql, jsqlite.Callback cb,
String args[]) throws jsqlite.Exception {
synchronized(this) {
_exec(sql, cb, args);
}
}
private native void _exec(String sql, jsqlite.Callback cb, String args[])
throws jsqlite.Exception;
/**
* Return the row identifier of the last inserted
* row.
*/
public long last_insert_rowid() {
synchronized(this) {
return _last_insert_rowid();
}
}
private native long _last_insert_rowid();
/**
* Abort the current SQLite operation.
*/
public void interrupt() {
synchronized(this) {
_interrupt();
}
}
private native void _interrupt();
/**
* Return the number of changed rows for the last statement.
*/
public long changes() {
synchronized(this) {
return _changes();
}
}
private native long _changes();
/**
* Establish a busy callback method which gets called when
* an SQLite table is locked.
*
* @param bh the object implementing the busy callback method
*/
public void busy_handler(jsqlite.BusyHandler bh) {
synchronized(this) {
_busy_handler(bh);
}
}
private native void _busy_handler(jsqlite.BusyHandler bh);
/**
* Set the timeout for waiting for an SQLite table to become
* unlocked.
*
* @param ms number of millisecond to wait
*/
public void busy_timeout(int ms) {
synchronized(this) {
_busy_timeout(ms);
}
}
private native void _busy_timeout(int ms);
/**
* Convenience method to retrieve an entire result
* set into memory.
*
* @param sql the SQL statement to be executed
* @param maxrows the max. number of rows to retrieve
* @return result set
*/
public TableResult get_table(String sql, int maxrows)
throws jsqlite.Exception {
TableResult ret = new TableResult(maxrows);
if (!is3()) {
try {
exec(sql, ret);
} catch (jsqlite.Exception e) {
if (maxrows <= 0 || !ret.atmaxrows) {
throw e;
}
}
} else {
synchronized(this) {
/* only one statement !!! */
Vm vm = compile(sql);
set_last_error(vm.error_code);
if (ret.maxrows > 0) {
while (ret.nrows < ret.maxrows && vm.step(ret)) {
set_last_error(vm.error_code);
}
} else {
while (vm.step(ret)) {
set_last_error(vm.error_code);
}
}
vm.finalize();
}
}
return ret;
}
/**
* Convenience method to retrieve an entire result
* set into memory.
*
* @param sql the SQL statement to be executed
* @return result set
*/
public TableResult get_table(String sql) throws jsqlite.Exception {
return get_table(sql, 0);
}
/**
* Convenience method to retrieve an entire result
* set into memory.
*
* @param sql the SQL statement to be executed
* @param maxrows the max. number of rows to retrieve
* @param args arguments for the SQL statement, '%q' substitution
* @return result set
*/
public TableResult get_table(String sql, int maxrows, String args[])
throws jsqlite.Exception {
TableResult ret = new TableResult(maxrows);
if (!is3()) {
try {
exec(sql, ret, args);
} catch (jsqlite.Exception e) {
if (maxrows <= 0 || !ret.atmaxrows) {
throw e;
}
}
} else {
synchronized(this) {
/* only one statement !!! */
Vm vm = compile(sql, args);
set_last_error(vm.error_code);
if (ret.maxrows > 0) {
while (ret.nrows < ret.maxrows && vm.step(ret)) {
set_last_error(vm.error_code);
}
} else {
while (vm.step(ret)) {
set_last_error(vm.error_code);
}
}
vm.finalize();
}
}
return ret;
}
/**
* Convenience method to retrieve an entire result
* set into memory.
*
* @param sql the SQL statement to be executed
* @param args arguments for the SQL statement, '%q' substitution
* @return result set
*/
public TableResult get_table(String sql, String args[])
throws jsqlite.Exception {
return get_table(sql, 0, args);
}
/**
* Convenience method to retrieve an entire result
* set into memory.
*
* @param sql the SQL statement to be executed
* @param args arguments for the SQL statement, '%q' substitution
* @param tbl TableResult to receive result set
*/
public void get_table(String sql, String args[], TableResult tbl)
throws jsqlite.Exception {
tbl.clear();
if (!is3()) {
try {
exec(sql, tbl, args);
} catch (jsqlite.Exception e) {
if (tbl.maxrows <= 0 || !tbl.atmaxrows) {
throw e;
}
}
} else {
synchronized(this) {
/* only one statement !!! */
Vm vm = compile(sql, args);
if (tbl.maxrows > 0) {
while (tbl.nrows < tbl.maxrows && vm.step(tbl)) {
set_last_error(vm.error_code);
}
} else {
while (vm.step(tbl)) {
set_last_error(vm.error_code);
}
}
vm.finalize();
}
}
}
/**
* See if an SQL statement is complete.
* Returns true if the input string comprises
* one or more complete SQL statements.
*
* @param sql the SQL statement to be checked
*/
public synchronized static boolean complete(String sql) {
return _complete(sql);
}
private native static boolean _complete(String sql);
/**
* Return SQLite version number as string.
* Don't rely on this when both SQLite 2 and 3 are compiled
* into the native part. Use the class method in this case.
*/
public native static String version();
/**
* Return SQLite version number as string.
* If the database is not open, <tt>unknown</tt> is returned.
*/
public native String dbversion();
/**
* Create regular function.
*
* @param name the name of the new function
* @param nargs number of arguments to function
* @param f interface of function
*/
public void create_function(String name, int nargs, Function f) {
synchronized(this) {
_create_function(name, nargs, f);
}
}
private native void _create_function(String name, int nargs, Function f);
/**
* Create aggregate function.
*
* @param name the name of the new function
* @param nargs number of arguments to function
* @param f interface of function
*/
public void create_aggregate(String name, int nargs, Function f) {
synchronized(this) {
_create_aggregate(name, nargs, f);
}
}
private native void _create_aggregate(String name, int nargs, Function f);
/**
* Set function return type. Only available in SQLite 2.6.0 and
* above, otherwise a no-op.
*
* @param name the name of the function whose return type is to be set
* @param type return type code, e.g. jsqlite.Constants.SQLITE_NUMERIC
*/
public void function_type(String name, int type) {
synchronized(this) {
_function_type(name, type);
}
}
private native void _function_type(String name, int type);
/**
* Return the code of the last error occured in
* any of the exec() methods. The value is valid
* after an Exception has been reported by one of
* these methods. See the <A HREF="Constants.html">Constants</A>
* class for possible values.
*
* @return SQLite error code
*/
public int last_error() {
return error_code;
}
/**
* Internal: set error code.
* @param error_code new error code
*/
protected void set_last_error(int error_code) {
this.error_code = error_code;
}
/**
* Return last error message of SQLite3 engine.
*
* @return error string or null
*/
public String error_message() {
synchronized(this) {
return _errmsg();
}
}
private native String _errmsg();
/**
* Return error string given SQLite error code (SQLite2).
*
* @param error_code the error code
* @return error string
*/
public static native String error_string(int error_code);
/**
* Set character encoding.
* @param enc name of encoding
*/
public void set_encoding(String enc) throws jsqlite.Exception {
synchronized(this) {
_set_encoding(enc);
}
}
private native void _set_encoding(String enc)
throws jsqlite.Exception;
/**
* Set authorizer function. Only available in SQLite 2.7.6 and
* above, otherwise a no-op.
*
* @param auth the authorizer function
*/
public void set_authorizer(Authorizer auth) {
synchronized(this) {
_set_authorizer(auth);
}
}
private native void _set_authorizer(Authorizer auth);
/**
* Set trace function. Only available in SQLite 2.7.6 and above,
* otherwise a no-op.
*
* @param tr the trace function
*/
public void trace(Trace tr) {
synchronized(this) {
_trace(tr);
}
}
private native void _trace(Trace tr);
/**
* Initiate a database backup, SQLite 3.x only.
*
* @param dest destination database
* @param destName schema of destination database to be backed up
* @param srcName schema of source database
* @return Backup object to perform the backup operation
*/
public Backup backup(Database dest, String destName, String srcName)
throws jsqlite.Exception {
synchronized(this) {
Backup b = new Backup();
_backup(b, dest, destName, this, srcName);
return b;
}
}
private static native void _backup(Backup b, Database dest,
String destName, Database src,
String srcName)
throws jsqlite.Exception;
/**
* Set profile function. Only available in SQLite 3.6 and above,
* otherwise a no-op.
*
* @param pr the trace function
*/
public void profile(Profile pr) {
synchronized(this) {
_profile(pr);
}
}
private native void _profile(Profile pr);
/**
* Return information on SQLite runtime status.
* Only available in SQLite 3.6 and above,
* otherwise a no-op.
*
* @param op operation code
* @param info output buffer, must be able to hold two
* values (current/highwater)
* @param flag reset flag
* @return SQLite error code
*/
public synchronized static int status(int op, int info[], boolean flag) {
return _status(op, info, flag);
}
private native static int _status(int op, int info[], boolean flag);
/**
* Return information on SQLite connection status.
* Only available in SQLite 3.6 and above,
* otherwise a no-op.
*
* @param op operation code
* @param info output buffer, must be able to hold two
* values (current/highwater)
* @param flag reset flag
* @return SQLite error code
*/
public int db_status(int op, int info[], boolean flag) {
synchronized(this) {
return _db_status(op, info, flag);
}
}
private native int _db_status(int op, int info[], boolean flag);
/**
* Compile and return SQLite VM for SQL statement. Only available
* in SQLite 2.8.0 and above, otherwise a no-op.
*
* @param sql SQL statement to be compiled
* @return a Vm object
*/
public Vm compile(String sql) throws jsqlite.Exception {
synchronized(this) {
Vm vm = new Vm();
vm_compile(sql, vm);
return vm;
}
}
/**
* Compile and return SQLite VM for SQL statement. Only available
* in SQLite 3.0 and above, otherwise a no-op.
*
* @param sql SQL statement to be compiled
* @param args arguments for the SQL statement, '%q' substitution
* @return a Vm object
*/
public Vm compile(String sql, String args[]) throws jsqlite.Exception {
synchronized(this) {
Vm vm = new Vm();
vm_compile_args(sql, vm, args);
return vm;
}
}
/**
* Prepare and return SQLite3 statement for SQL. Only available
* in SQLite 3.0 and above, otherwise a no-op.
*
* @param sql SQL statement to be prepared
* @return a Stmt object
*/
public Stmt prepare(String sql) throws jsqlite.Exception {
synchronized(this) {
Stmt stmt = new Stmt();
stmt_prepare(sql, stmt);
return stmt;
}
}
/**
* Open an SQLite3 blob. Only available in SQLite 3.4.0 and above.
* @param db database name
* @param table table name
* @param column column name
* @param row row identifier
* @param rw if true, open for read-write, else read-only
* @return a Blob object
*/
public Blob open_blob(String db, String table, String column,
long row, boolean rw) throws jsqlite.Exception {
synchronized(this) {
Blob blob = new Blob();
_open_blob(db, table, column, row, rw, blob);
return blob;
}
}
/**
* Check type of open database.
* @return true if SQLite3 database
*/
public native boolean is3();
/**
* Internal compile method.
* @param sql SQL statement
* @param vm Vm object
*/
private native void vm_compile(String sql, Vm vm)
throws jsqlite.Exception;
/**
* Internal compile method, SQLite 3.0 only.
* @param sql SQL statement
* @param args arguments for the SQL statement, '%q' substitution
* @param vm Vm object
*/
private native void vm_compile_args(String sql, Vm vm, String args[])
throws jsqlite.Exception;
/**
* Internal SQLite3 prepare method.
* @param sql SQL statement
* @param stmt Stmt object
*/
private native void stmt_prepare(String sql, Stmt stmt)
throws jsqlite.Exception;
/**
* Internal SQLite open blob method.
* @param db database name
* @param table table name
* @param column column name
* @param row row identifier
* @param rw if true, open for read-write, else read-only
* @param blob Blob object
*/
private native void _open_blob(String db, String table, String column,
long row, boolean rw, Blob blob)
throws jsqlite.Exception;
/**
* Establish a progress callback method which gets called after
* N SQLite VM opcodes.
*
* @param n number of SQLite VM opcodes until callback is invoked
* @param p the object implementing the progress callback method
*/
public void progress_handler(int n, jsqlite.ProgressHandler p) {
synchronized(this) {
_progress_handler(n, p);
}
}
private native void _progress_handler(int n, jsqlite.ProgressHandler p);
/**
* Specify key for encrypted database. To be called
* right after open() on SQLite3 databases.
* Not available in public releases of SQLite.
*
* @param ekey the key as byte array
*/
public void key(byte[] ekey) throws jsqlite.Exception {
synchronized(this) {
_key(ekey);
}
}
/**
* Specify key for encrypted database. To be called
* right after open() on SQLite3 databases.
* Not available in public releases of SQLite.
*
* @param skey the key as String
*/
public void key(String skey) throws jsqlite.Exception {
synchronized(this) {
byte ekey[] = null;
if (skey != null && skey.length() > 0) {
ekey = new byte[skey.length()];
for (int i = 0; i< skey.length(); i++) {
char c = skey.charAt(i);
ekey[i] = (byte) ((c & 0xff) ^ (c >> 8));
}
}
_key(ekey);
}
}
private native void _key(byte[] ekey);
/**
* Change the key of a encrypted database. The
* SQLite3 database must have been open()ed.
* Not available in public releases of SQLite.
*
* @param ekey the key as byte array
*/
public void rekey(byte[] ekey) throws jsqlite.Exception {
synchronized(this) {
_rekey(ekey);
}
}
/**
* Change the key of a encrypted database. The
* SQLite3 database must have been open()ed.
* Not available in public releases of SQLite.
*
* @param skey the key as String
*/
public void rekey(String skey) throws jsqlite.Exception {
synchronized(this) {
byte ekey[] = null;
if (skey != null && skey.length() > 0) {
ekey = new byte[skey.length()];
for (int i = 0; i< skey.length(); i++) {
char c = skey.charAt(i);
ekey[i] = (byte) ((c & 0xff) ^ (c >> 8));
}
}
_rekey(ekey);
}
}
private native void _rekey(byte[] ekey);
/**
* Enable/disable shared cache mode (SQLite 3.x only).
*
* @param onoff boolean to enable or disable shared cache
* @return boolean when true, function supported/succeeded
*/
protected static native boolean _enable_shared_cache(boolean onoff);
/**
* Internal native initializer.
*/
private static native void internal_init();
/**
* Make long value from julian date for java.lang.Date
*
* @param d double value (julian date in SQLite3 format)
* @return long
*/
public static long long_from_julian(double d) {
d -= 2440587.5;
d *= 86400000.0;
return (long) d;
}
/**
* Make long value from julian date for java.lang.Date
*
* @param s string (double value) (julian date in SQLite3 format)
* @return long
*/
public static long long_from_julian(String s) throws jsqlite.Exception {
try {
double d = Double.valueOf(s).doubleValue();
return long_from_julian(d);
} catch (java.lang.Exception ee) {
throw new jsqlite.Exception("not a julian date: " + s + ": " + ee);
}
}
/**
* Make julian date value from java.lang.Date
*
* @param ms millisecond value of java.lang.Date
* @return double
*/
public static double julian_from_long(long ms) {
double adj = (ms < 0) ? 0 : 0.5;
double d = (ms + adj) / 86400000.0 + 2440587.5;
return d;
}
public native void spatialite_create();
/**
* Static initializer to load the native part.
*/
static {
try {
System.loadLibrary("jsqlite");
} catch (Throwable t) {
System.err.println("Unable to load sqlite_jni: " + t);
}
/*
* Call native initializer functions now, since the
* native part could have been linked statically, i.e.
* the try/catch above would have failed in that case.
*/
try {
internal_init();
new FunctionContext();
} catch (java.lang.Exception e) {
}
}
}
| Java |
package jsqlite;
/**
* Callback interface for SQLite's user defined busy handler.
*/
public interface BusyHandler {
/**
* Invoked when a table is locked by another process
* or thread. The method should return true for waiting
* until the table becomes unlocked, or false in order
* to abandon the action.<BR><BR>
*
* @param table the name of the locked table
* @param count number of times the table was locked
*/
public boolean busy(String table, int count);
}
| Java |
package jsqlite;
import java.sql.*;
import java.util.Properties;
public class JDBCDriver implements java.sql.Driver {
public static final int MAJORVERSION = 1;
public static boolean sharedCache = false;
public static String vfs = null;
private static java.lang.reflect.Constructor makeConn = null;
protected Connection conn;
static {
try {
Class connClass = null;
Class args[] = new Class[5];
args[0] = Class.forName("java.lang.String");
args[1] = args[0];
args[2] = args[0];
args[3] = args[0];
args[4] = args[0];
String jvers = java.lang.System.getProperty("java.version");
String cvers;
if (jvers == null || jvers.startsWith("1.0")) {
throw new java.lang.Exception("unsupported java version");
} else if (jvers.startsWith("1.1")) {
cvers = "jsqlite.JDBC1.JDBCConnection";
} else if (jvers.startsWith("1.2") || jvers.startsWith("1.3")) {
cvers = "jsqlite.JDBC2.JDBCConnection";
} else if (jvers.startsWith("1.4")) {
cvers = "jsqlite.JDBC2x.JDBCConnection";
} else if (jvers.startsWith("1.5")) {
cvers = "jsqlite.JDBC2y.JDBCConnection";
try {
Class.forName(cvers);
} catch (java.lang.Exception e) {
cvers = "jsqlite.JDBC2x.JDBCConnection";
}
} else {
cvers = "jsqlite.JDBC2z.JDBCConnection";
try {
Class.forName(cvers);
} catch (java.lang.Exception e) {
cvers = "jsqlite.JDBC2y.JDBCConnection";
try {
Class.forName(cvers);
} catch (java.lang.Exception ee) {
cvers = "jsqlite.JDBC2x.JDBCConnection";
}
}
}
connClass = Class.forName(cvers);
makeConn = connClass.getConstructor(args);
java.sql.DriverManager.registerDriver(new JDBCDriver());
try {
String shcache =
java.lang.System.getProperty("SQLite.sharedcache");
if (shcache != null &&
(shcache.startsWith("y") || shcache.startsWith("Y"))) {
sharedCache = jsqlite.Database._enable_shared_cache(true);
}
} catch (java.lang.Exception e) {
}
try {
String tvfs =
java.lang.System.getProperty("SQLite.vfs");
if (tvfs != null) {
vfs = tvfs;
}
} catch (java.lang.Exception e) {
}
} catch (java.lang.Exception e) {
System.err.println(e);
}
}
public JDBCDriver() {
}
public boolean acceptsURL(String url) throws SQLException {
return url.startsWith("jsqlite:/") ||
url.startsWith("jdbc:jsqlite:/");
}
public Connection connect(String url, Properties info)
throws SQLException {
if (!acceptsURL(url)) {
return null;
}
Object args[] = new Object[5];
args[0] = url;
if (info != null) {
args[1] = info.getProperty("encoding");
args[2] = info.getProperty("password");
args[3] = info.getProperty("daterepr");
args[4] = info.getProperty("vfs");
}
if (args[1] == null) {
args[1] = java.lang.System.getProperty("SQLite.encoding");
}
if (args[4] == null) {
args[4] = vfs;
}
try {
conn = (Connection) makeConn.newInstance(args);
} catch (java.lang.reflect.InvocationTargetException ie) {
throw new SQLException(ie.getTargetException().toString());
} catch (java.lang.Exception e) {
throw new SQLException(e.toString());
}
return conn;
}
public int getMajorVersion() {
return MAJORVERSION;
}
public int getMinorVersion() {
return Constants.drv_minor;
}
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
throws SQLException {
DriverPropertyInfo p[] = new DriverPropertyInfo[4];
DriverPropertyInfo pp = new DriverPropertyInfo("encoding", "");
p[0] = pp;
pp = new DriverPropertyInfo("password", "");
p[1] = pp;
pp = new DriverPropertyInfo("daterepr", "normal");
p[2] = pp;
pp = new DriverPropertyInfo("vfs", vfs);
p[3] = pp;
return p;
}
public boolean jdbcCompliant() {
return false;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.