code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ShareTrack; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import android.content.Context; import android.net.Uri; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class GpxSharing extends GpxCreator { public GpxSharing(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener) { super(context, trackUri, chosenBaseFileName, attachments, listener); } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); ShareTrack.sendFile(mContext, resultFilename, mContext.getString(R.string.email_gpxbody), getContentType()); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/GpxSharing.java
Java
gpl3
2,365
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.util.Constants; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpPost; import org.apache.ogt.http.entity.mime.MultipartEntity; import org.apache.ogt.http.entity.mime.content.FileBody; import org.apache.ogt.http.entity.mime.content.StringBody; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import android.content.Context; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class JogmapSharing extends GpxCreator { private static final String TAG = "OGT.JogmapSharing"; private String jogmapResponseText; public JogmapSharing(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener) { super(context, trackUri, chosenBaseFileName, attachments, listener); } @Override protected Uri doInBackground(Void... params) { Uri result = super.doInBackground(params); sendToJogmap(result); return result; } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); CharSequence text = mContext.getString(R.string.osm_success) + jogmapResponseText; Toast toast = Toast.makeText(mContext, text, Toast.LENGTH_LONG); toast.show(); } private void sendToJogmap(Uri fileUri) { String authCode = PreferenceManager.getDefaultSharedPreferences(mContext).getString(Constants.JOGRUNNER_AUTH, ""); File gpxFile = new File(fileUri.getEncodedPath()); HttpClient httpclient = new DefaultHttpClient(); URI jogmap = null; int statusCode = 0; HttpEntity responseEntity = null; try { jogmap = new URI(mContext.getString(R.string.jogmap_post_url)); HttpPost method = new HttpPost(jogmap); MultipartEntity entity = new MultipartEntity(); entity.addPart("id", new StringBody(authCode)); entity.addPart("mFile", new FileBody(gpxFile)); method.setEntity(entity); HttpResponse response = httpclient.execute(method); statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); jogmapResponseText = XmlCreator.convertStreamToString(stream); } catch (IOException e) { String text = mContext.getString(R.string.jogmap_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.jogmap_task), e, text); } catch (URISyntaxException e) { String text = mContext.getString(R.string.jogmap_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.jogmap_task), e, text); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } if (statusCode != 200) { Log.e(TAG, "Wrong status code " + statusCode); jogmapResponseText = mContext.getString(R.string.jogmap_failed) + jogmapResponseText; handleError(mContext.getString(R.string.jogmap_task), new HttpException("Unexpected status reported by Jogmap"), jogmapResponseText); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/JogmapSharing.java
Java
gpl3
5,565
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.Vector; import java.util.concurrent.CancellationException; import java.util.concurrent.Executor; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.ProgressFilterInputStream; import nl.sogeti.android.gpstracker.util.UnicodeReader; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.util.Log; import android.view.Window; public class GpxParser extends AsyncTask<Uri, Void, Uri> { private static final String LATITUDE_ATRIBUTE = "lat"; private static final String LONGITUDE_ATTRIBUTE = "lon"; private static final String TRACK_ELEMENT = "trkpt"; private static final String SEGMENT_ELEMENT = "trkseg"; private static final String NAME_ELEMENT = "name"; private static final String TIME_ELEMENT = "time"; private static final String ELEVATION_ELEMENT = "ele"; private static final String COURSE_ELEMENT = "course"; private static final String ACCURACY_ELEMENT = "accuracy"; private static final String SPEED_ELEMENT = "speed"; public static final SimpleDateFormat ZULU_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); public static final SimpleDateFormat ZULU_DATE_FORMAT_MS = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); public static final SimpleDateFormat ZULU_DATE_FORMAT_BC = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'UTC'"); protected static final int DEFAULT_UNKNOWN_FILESIZE = 1024 * 1024 * 10; private static final String TAG = "OGT.GpxParser"; static { TimeZone utc = TimeZone.getTimeZone("UTC"); ZULU_DATE_FORMAT.setTimeZone(utc); // ZULU_DATE_FORMAT format ends with Z for UTC so make that true ZULU_DATE_FORMAT_MS.setTimeZone(utc); } private ContentResolver mContentResolver; protected String mErrorDialogMessage; protected Exception mErrorDialogException; protected Context mContext; private ProgressListener mProgressListener; protected ProgressAdmin mProgressAdmin; public GpxParser(Context context, ProgressListener progressListener) { mContext = context; mProgressListener = progressListener; mContentResolver = mContext.getContentResolver(); } public void executeOn(Executor executor) { if (Build.VERSION.SDK_INT >= 11) { executeOnExecutor(executor); } else { execute(); } } public void determineProgressGoal(Uri importFileUri) { mProgressAdmin = new ProgressAdmin(); mProgressAdmin.setContentLength(DEFAULT_UNKNOWN_FILESIZE); if (importFileUri != null && importFileUri.getScheme().equals("file")) { File file = new File(importFileUri.getPath()); mProgressAdmin.setContentLength(file.length()); } } public Uri importUri(Uri importFileUri) { Uri result = null; String trackName = null; InputStream fis = null; if (importFileUri.getScheme().equals("file")) { trackName = importFileUri.getLastPathSegment(); } try { fis = mContentResolver.openInputStream(importFileUri); } catch (IOException e) { handleError(e, mContext.getString(R.string.error_importgpx_io)); } result = importTrack( fis, trackName); return result; } /** * Read a stream containing GPX XML into the OGT content provider * * @param fis opened stream the read from, will be closed after this call * @param trackName * @return */ public Uri importTrack( InputStream fis, String trackName ) { Uri trackUri = null; int eventType; ContentValues lastPosition = null; Vector<ContentValues> bulk = new Vector<ContentValues>(); boolean speed = false; boolean accuracy = false; boolean bearing = false; boolean elevation = false; boolean name = false; boolean time = false; Long importDate = Long.valueOf(new Date().getTime()); try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xmlParser = factory.newPullParser(); ProgressFilterInputStream pfis = new ProgressFilterInputStream(fis, mProgressAdmin); BufferedInputStream bis = new BufferedInputStream(pfis); UnicodeReader ur = new UnicodeReader(bis, "UTF-8"); xmlParser.setInput(ur); eventType = xmlParser.getEventType(); String attributeName; Uri segmentUri = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (xmlParser.getName().equals(NAME_ELEMENT)) { name = true; } else { ContentValues trackContent = new ContentValues(); trackContent.put(Tracks.NAME, trackName); if (xmlParser.getName().equals("trk") && trackUri == null) { trackUri = startTrack(trackContent); } else if (xmlParser.getName().equals(SEGMENT_ELEMENT)) { segmentUri = startSegment(trackUri); } else if (xmlParser.getName().equals(TRACK_ELEMENT)) { lastPosition = new ContentValues(); for (int i = 0; i < 2; i++) { attributeName = xmlParser.getAttributeName(i); if (attributeName.equals(LATITUDE_ATRIBUTE)) { lastPosition.put(Waypoints.LATITUDE, Double.valueOf(xmlParser.getAttributeValue(i))); } else if (attributeName.equals(LONGITUDE_ATTRIBUTE)) { lastPosition.put(Waypoints.LONGITUDE, Double.valueOf(xmlParser.getAttributeValue(i))); } } } else if (xmlParser.getName().equals(SPEED_ELEMENT)) { speed = true; } else if (xmlParser.getName().equals(ACCURACY_ELEMENT)) { accuracy = true; } else if (xmlParser.getName().equals(COURSE_ELEMENT)) { bearing = true; } else if (xmlParser.getName().equals(ELEVATION_ELEMENT)) { elevation = true; } else if (xmlParser.getName().equals(TIME_ELEMENT)) { time = true; } } } else if (eventType == XmlPullParser.END_TAG) { if (xmlParser.getName().equals(NAME_ELEMENT)) { name = false; } else if (xmlParser.getName().equals(SPEED_ELEMENT)) { speed = false; } else if (xmlParser.getName().equals(ACCURACY_ELEMENT)) { accuracy = false; } else if (xmlParser.getName().equals(COURSE_ELEMENT)) { bearing = false; } else if (xmlParser.getName().equals(ELEVATION_ELEMENT)) { elevation = false; } else if (xmlParser.getName().equals(TIME_ELEMENT)) { time = false; } else if (xmlParser.getName().equals(SEGMENT_ELEMENT)) { if (segmentUri == null) { segmentUri = startSegment( trackUri ); } mContentResolver.bulkInsert(Uri.withAppendedPath(segmentUri, "waypoints"), bulk.toArray(new ContentValues[bulk.size()])); bulk.clear(); } else if (xmlParser.getName().equals(TRACK_ELEMENT)) { if (!lastPosition.containsKey(Waypoints.TIME)) { lastPosition.put(Waypoints.TIME, importDate); } if (!lastPosition.containsKey(Waypoints.SPEED)) { lastPosition.put(Waypoints.SPEED, 0); } bulk.add(lastPosition); lastPosition = null; } } else if (eventType == XmlPullParser.TEXT) { String text = xmlParser.getText(); if (name) { ContentValues nameValues = new ContentValues(); nameValues.put(Tracks.NAME, text); if (trackUri == null) { trackUri = startTrack(new ContentValues()); } mContentResolver.update(trackUri, nameValues, null, null); } else if (lastPosition != null && speed) { lastPosition.put(Waypoints.SPEED, Double.parseDouble(text)); } else if (lastPosition != null && accuracy) { lastPosition.put(Waypoints.ACCURACY, Double.parseDouble(text)); } else if (lastPosition != null && bearing) { lastPosition.put(Waypoints.BEARING, Double.parseDouble(text)); } else if (lastPosition != null && elevation) { lastPosition.put(Waypoints.ALTITUDE, Double.parseDouble(text)); } else if (lastPosition != null && time) { lastPosition.put(Waypoints.TIME, parseXmlDateTime(text)); } } eventType = xmlParser.next(); } } catch (XmlPullParserException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (IOException e) { handleError(e, mContext.getString(R.string.error_importgpx_io)); } finally { try { fis.close(); } catch (IOException e) { Log.w( TAG, "Failed closing inputstream"); } } return trackUri; } private Uri startSegment(Uri trackUri) { if (trackUri == null) { trackUri = startTrack(new ContentValues()); } return mContentResolver.insert(Uri.withAppendedPath(trackUri, "segments"), new ContentValues()); } private Uri startTrack(ContentValues trackContent) { return mContentResolver.insert(Tracks.CONTENT_URI, trackContent); } public static Long parseXmlDateTime(String text) { Long dateTime = 0L; try { if(text==null) { throw new ParseException("Unable to parse dateTime "+text+" of length ", 0); } int length = text.length(); switch (length) { case 20: synchronized (ZULU_DATE_FORMAT) { dateTime = Long.valueOf(ZULU_DATE_FORMAT.parse(text).getTime()); } break; case 23: synchronized (ZULU_DATE_FORMAT_BC) { dateTime = Long.valueOf(ZULU_DATE_FORMAT_BC.parse(text).getTime()); } break; case 24: synchronized (ZULU_DATE_FORMAT_MS) { dateTime = Long.valueOf(ZULU_DATE_FORMAT_MS.parse(text).getTime()); } break; default: throw new ParseException("Unable to parse dateTime "+text+" of length "+length, 0); } } catch (ParseException e) { Log.w(TAG, "Failed to parse a time-date", e); } return dateTime; } /** * * @param e * @param text */ protected void handleError(Exception dialogException, String dialogErrorMessage) { Log.e(TAG, "Unable to save ", dialogException); mErrorDialogException = dialogException; mErrorDialogMessage = dialogErrorMessage; cancel(false); throw new CancellationException(dialogErrorMessage); } @Override protected void onPreExecute() { mProgressListener.started(); } @Override protected Uri doInBackground(Uri... params) { Uri importUri = params[0]; determineProgressGoal( importUri); Uri result = importUri( importUri ); return result; } @Override protected void onProgressUpdate(Void... values) { mProgressListener.setProgress(mProgressAdmin.getProgress()); } @Override protected void onPostExecute(Uri result) { mProgressListener.finished(result); } @Override protected void onCancelled() { mProgressListener.showError(mContext.getString(R.string.taskerror_gpx_import), mErrorDialogMessage, mErrorDialogException); } public class ProgressAdmin { private long progressedBytes; private long contentLength; private int progress; private long lastUpdate; /** * Get the progress. * * @return Returns the progress as a int. */ public int getProgress() { return progress; } public void addBytesProgress(int addedBytes) { progressedBytes += addedBytes; progress = (int) (Window.PROGRESS_END * progressedBytes / contentLength); considerPublishProgress(); } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public void considerPublishProgress() { long now = new Date().getTime(); if( now - lastUpdate > 1000 ) { lastUpdate = now; publishProgress(); } } } };
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/GpxParser.java
Java
gpl3
16,565
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.File; import java.io.IOException; import java.io.InputStream; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ShareTrack; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.oauth.PrepareRequestTokenActivity; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.viewer.map.LoggerMapHelper; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpPost; import org.apache.ogt.http.entity.mime.HttpMultipartMode; import org.apache.ogt.http.entity.mime.MultipartEntity; import org.apache.ogt.http.entity.mime.content.FileBody; import org.apache.ogt.http.entity.mime.content.StringBody; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class OsmSharing extends GpxCreator { public static final String OAUTH_TOKEN = "openstreetmap_oauth_token"; public static final String OAUTH_TOKEN_SECRET = "openstreetmap_oauth_secret"; private static final String TAG = "OGT.OsmSharing"; public static final String OSM_FILENAME = "OSM_Trace"; private String responseText; private Uri mFileUri; public OsmSharing(Activity context, Uri trackUri, boolean attachments, ProgressListener listener) { super(context, trackUri, OSM_FILENAME, attachments, listener); } public void resumeOsmSharing(Uri fileUri, Uri trackUri) { mFileUri = fileUri; mTrackUri = trackUri; execute(); } @Override protected Uri doInBackground(Void... params) { if( mFileUri == null ) { mFileUri = super.doInBackground(params); } sendToOsm(mFileUri, mTrackUri); return mFileUri; } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); CharSequence text = mContext.getString(R.string.osm_success) + responseText; Toast toast = Toast.makeText(mContext, text, Toast.LENGTH_LONG); toast.show(); } /** * POST a (GPX) file to the 0.6 API of the OpenStreetMap.org website * publishing this track to the public. * * @param fileUri * @param contentType */ private void sendToOsm(final Uri fileUri, final Uri trackUri) { CommonsHttpOAuthConsumer consumer = osmConnectionSetup(); if( consumer == null ) { requestOpenstreetmapOauthToken(); handleError(mContext.getString(R.string.osm_task), null, mContext.getString(R.string.osmauth_message)); } String visibility = PreferenceManager.getDefaultSharedPreferences(mContext).getString(Constants.OSM_VISIBILITY, "trackable"); File gpxFile = new File(fileUri.getEncodedPath()); String url = mContext.getString(R.string.osm_post_url); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; int statusCode = 0; Cursor metaData = null; String sources = null; HttpEntity responseEntity = null; try { metaData = mContext.getContentResolver().query(Uri.withAppendedPath(trackUri, "metadata"), new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { Constants.DATASOURCES_KEY }, null); if (metaData.moveToFirst()) { sources = metaData.getString(0); } if (sources != null && sources.contains(LoggerMapHelper.GOOGLE_PROVIDER)) { throw new IOException("Unable to upload track with materials derived from Google Maps."); } // The POST to the create node HttpPost method = new HttpPost(url); String tags = mContext.getString(R.string.osm_tag) + " " +queryForNotes(); // Build the multipart body with the upload data MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("file", new FileBody(gpxFile)); entity.addPart("description", new StringBody( ShareTrack.queryForTrackName(mContext.getContentResolver(), mTrackUri))); entity.addPart("tags", new StringBody(tags)); entity.addPart("visibility", new StringBody(visibility)); method.setEntity(entity); // Execute the POST to OpenStreetMap consumer.sign(method); response = httpclient.execute(method); // Read the response statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); responseText = XmlCreator.convertStreamToString(stream); } catch (OAuthMessageSignerException e) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } catch (OAuthExpectationFailedException e) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } catch (OAuthCommunicationException e) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } catch (IOException e) { responseText = mContext.getString(R.string.osm_failed) + e.getLocalizedMessage(); handleError(mContext.getString(R.string.osm_task), e, responseText); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } if (metaData != null) { metaData.close(); } } if (statusCode != 200) { Log.e(TAG, "Failed to upload to error code " + statusCode + " " + responseText); String text = mContext.getString(R.string.osm_failed) + responseText; if( statusCode == 401 ) { Editor editor = PreferenceManager.getDefaultSharedPreferences(mContext).edit(); editor.remove(OAUTH_TOKEN); editor.remove(OAUTH_TOKEN_SECRET); editor.commit(); } handleError(mContext.getString(R.string.osm_task), new HttpException("Unexpected status reported by OSM"), text); } } private CommonsHttpOAuthConsumer osmConnectionSetup() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String token = prefs.getString(OAUTH_TOKEN, ""); String secret = prefs.getString(OAUTH_TOKEN_SECRET, ""); boolean mAuthorized = !"".equals(token) && !"".equals(secret); CommonsHttpOAuthConsumer consumer = null; if (mAuthorized) { consumer = new CommonsHttpOAuthConsumer(mContext.getString(R.string.OSM_CONSUMER_KEY), mContext.getString(R.string.OSM_CONSUMER_SECRET)); consumer.setTokenWithSecret(token, secret); } return consumer; } private String queryForNotes() { StringBuilder tags = new StringBuilder(); ContentResolver resolver = mContext.getContentResolver(); Cursor mediaCursor = null; Uri mediaUri = Uri.withAppendedPath(mTrackUri, "media"); try { mediaCursor = resolver.query(mediaUri, new String[] { Media.URI }, null, null, null); if (mediaCursor.moveToFirst()) { do { Uri noteUri = Uri.parse(mediaCursor.getString(0)); if (noteUri.getScheme().equals("content") && noteUri.getAuthority().equals(GPStracking.AUTHORITY + ".string")) { String tag = noteUri.getLastPathSegment().trim(); if (!tag.contains(" ")) { if (tags.length() > 0) { tags.append(" "); } tags.append(tag); } } } while (mediaCursor.moveToNext()); } } finally { if (mediaCursor != null) { mediaCursor.close(); } } return tags.toString(); } public void requestOpenstreetmapOauthToken() { Intent intent = new Intent(mContext.getApplicationContext(), PrepareRequestTokenActivity.class); intent.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_PREF, OAUTH_TOKEN); intent.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_SECRET_PREF, OAUTH_TOKEN_SECRET); intent.putExtra(PrepareRequestTokenActivity.CONSUMER_KEY, mContext.getString(R.string.OSM_CONSUMER_KEY)); intent.putExtra(PrepareRequestTokenActivity.CONSUMER_SECRET, mContext.getString(R.string.OSM_CONSUMER_SECRET)); intent.putExtra(PrepareRequestTokenActivity.REQUEST_URL, Constants.OSM_REQUEST_URL); intent.putExtra(PrepareRequestTokenActivity.ACCESS_URL, Constants.OSM_ACCESS_URL); intent.putExtra(PrepareRequestTokenActivity.AUTHORIZE_URL, Constants.OSM_AUTHORIZE_URL); mContext.startActivity(intent); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/OsmSharing.java
Java
gpl3
12,525
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import org.xmlpull.v1.XmlSerializer; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore.MediaColumns; import android.util.Log; import android.util.Xml; /** * Create a GPX version of a stored track * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class GpxCreator extends XmlCreator { public static final String NS_SCHEMA = "http://www.w3.org/2001/XMLSchema-instance"; public static final String NS_GPX_11 = "http://www.topografix.com/GPX/1/1"; public static final String NS_GPX_10 = "http://www.topografix.com/GPX/1/0"; public static final String NS_OGT_10 = "http://gpstracker.android.sogeti.nl/GPX/1/0"; public static final SimpleDateFormat ZULU_DATE_FORMATER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); static { TimeZone utc = TimeZone.getTimeZone("UTC"); ZULU_DATE_FORMATER.setTimeZone(utc); // ZULU_DATE_FORMAT format ends with Z for UTC so make that true } private String TAG = "OGT.GpxCreator"; private boolean includeAttachments; protected String mName; public GpxCreator(Context context, Uri trackUri, String chosenBaseFileName, boolean attachments, ProgressListener listener) { super(context, trackUri, chosenBaseFileName, listener); includeAttachments = attachments; } @Override protected Uri doInBackground(Void... params) { determineProgressGoal(); Uri resultFilename = exportGpx(); return resultFilename; } protected Uri exportGpx() { String xmlFilePath; if (mFileName.endsWith(".gpx") || mFileName.endsWith(".xml")) { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName.substring(0, mFileName.length() - 4)); xmlFilePath = getExportDirectoryPath() + "/" + mFileName; } else { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName); xmlFilePath = getExportDirectoryPath() + "/" + mFileName + ".gpx"; } new File(getExportDirectoryPath()).mkdirs(); String resultFilename = null; FileOutputStream fos = null; BufferedOutputStream buf = null; try { verifySdCardAvailibility(); XmlSerializer serializer = Xml.newSerializer(); File xmlFile = new File(xmlFilePath); fos = new FileOutputStream(xmlFile); buf = new BufferedOutputStream(fos, 8 * 8192); serializer.setOutput(buf, "UTF-8"); serializeTrack(mTrackUri, serializer); buf.close(); buf = null; fos.close(); fos = null; if (needsBundling()) { resultFilename = bundlingMediaAndXml(xmlFile.getParentFile().getName(), ".zip"); } else { File finalFile = new File(Constants.getSdCardDirectory(mContext) + xmlFile.getName()); xmlFile.renameTo(finalFile); resultFilename = finalFile.getAbsolutePath(); XmlCreator.deleteRecursive(xmlFile.getParentFile()); } mFileName = new File(resultFilename).getName(); } catch (FileNotFoundException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_filenotfound); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } catch (IllegalArgumentException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_filename); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } catch (IllegalStateException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } catch (IOException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_writesdcard); handleError(mContext.getString(R.string.taskerror_gpx_write), e, text); } finally { if (buf != null) { try { buf.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buf after completion, ignoring.", e); } } if (fos != null) { try { fos.close(); } catch (IOException e) { Log.e(TAG, "Failed to close fos after completion, ignoring.", e); } } } return Uri.fromFile(new File(resultFilename)); } private void serializeTrack(Uri trackUri, XmlSerializer serializer) throws IllegalArgumentException, IllegalStateException, IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } serializer.startDocument("UTF-8", true); serializer.setPrefix("xsi", NS_SCHEMA); serializer.setPrefix("gpx10", NS_GPX_10); serializer.setPrefix("ogt10", NS_OGT_10); serializer.text("\n"); serializer.startTag("", "gpx"); serializer.attribute(null, "version", "1.1"); serializer.attribute(null, "creator", "nl.sogeti.android.gpstracker"); serializer.attribute(NS_SCHEMA, "schemaLocation", NS_GPX_11 + " http://www.topografix.com/gpx/1/1/gpx.xsd"); serializer.attribute(null, "xmlns", NS_GPX_11); // <metadata/> Big header of the track serializeTrackHeader(mContext, serializer, trackUri); // <wpt/> [0...] Waypoints if (includeAttachments) { serializeWaypoints(mContext, serializer, Uri.withAppendedPath(trackUri, "/media")); } // <trk/> [0...] Track serializer.text("\n"); serializer.startTag("", "trk"); serializer.text("\n"); serializer.startTag("", "name"); serializer.text(mName); serializer.endTag("", "name"); // The list of segments in the track serializeSegments(serializer, Uri.withAppendedPath(trackUri, "segments")); serializer.text("\n"); serializer.endTag("", "trk"); serializer.text("\n"); serializer.endTag("", "gpx"); serializer.endDocument(); } private void serializeTrackHeader(Context context, XmlSerializer serializer, Uri trackUri) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } ContentResolver resolver = context.getContentResolver(); Cursor trackCursor = null; String databaseName = null; try { trackCursor = resolver.query(trackUri, new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, null, null, null); if (trackCursor.moveToFirst()) { databaseName = trackCursor.getString(1); serializer.text("\n"); serializer.startTag("", "metadata"); serializer.text("\n"); serializer.startTag("", "time"); Date time = new Date(trackCursor.getLong(2)); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(time)); } serializer.endTag("", "time"); serializer.text("\n"); serializer.endTag("", "metadata"); } } finally { if (trackCursor != null) { trackCursor.close(); } } if (mName == null) { mName = "Untitled"; } if (databaseName != null && !databaseName.equals("")) { mName = databaseName; } if (mChosenName != null && !mChosenName.equals("")) { mName = mChosenName; } } private void serializeSegments(XmlSerializer serializer, Uri segments) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } Cursor segmentCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { segmentCursor = resolver.query(segments, new String[] { Segments._ID }, null, null, null); if (segmentCursor.moveToFirst()) { do { Uri waypoints = Uri.withAppendedPath(segments, segmentCursor.getLong(0) + "/waypoints"); serializer.text("\n"); serializer.startTag("", "trkseg"); serializeTrackPoints(serializer, waypoints); serializer.text("\n"); serializer.endTag("", "trkseg"); } while (segmentCursor.moveToNext()); } } finally { if (segmentCursor != null) { segmentCursor.close(); } } } private void serializeTrackPoints(XmlSerializer serializer, Uri waypoints) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } Cursor waypointsCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(waypoints, new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.TIME, Waypoints.ALTITUDE, Waypoints._ID, Waypoints.SPEED, Waypoints.ACCURACY, Waypoints.BEARING }, null, null, null); if (waypointsCursor.moveToFirst()) { do { mProgressAdmin.addWaypointProgress(1); serializer.text("\n"); serializer.startTag("", "trkpt"); serializer.attribute(null, "lat", Double.toString(waypointsCursor.getDouble(1))); serializer.attribute(null, "lon", Double.toString(waypointsCursor.getDouble(0))); serializer.text("\n"); serializer.startTag("", "ele"); serializer.text(Double.toString(waypointsCursor.getDouble(3))); serializer.endTag("", "ele"); serializer.text("\n"); serializer.startTag("", "time"); Date time = new Date(waypointsCursor.getLong(2)); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(time)); } serializer.endTag("", "time"); serializer.text("\n"); serializer.startTag("", "extensions"); double speed = waypointsCursor.getDouble(5); double accuracy = waypointsCursor.getDouble(6); double bearing = waypointsCursor.getDouble(7); if (speed > 0.0) { quickTag(serializer, NS_GPX_10, "speed", Double.toString(speed)); } if (accuracy > 0.0) { quickTag(serializer, NS_OGT_10, "accuracy", Double.toString(accuracy)); } if (bearing != 0.0) { quickTag(serializer, NS_GPX_10, "course", Double.toString(bearing)); } serializer.endTag("", "extensions"); serializer.text("\n"); serializer.endTag("", "trkpt"); } while (waypointsCursor.moveToNext()); } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } private void serializeWaypoints(Context context, XmlSerializer serializer, Uri media) throws IOException { if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } Cursor mediaCursor = null; Cursor waypointCursor = null; BufferedReader buf = null; ContentResolver resolver = context.getContentResolver(); try { mediaCursor = resolver.query(media, new String[] { Media.URI, Media.TRACK, Media.SEGMENT, Media.WAYPOINT }, null, null, null); if (mediaCursor.moveToFirst()) { do { Uri waypointUri = Waypoints.buildUri(mediaCursor.getLong(1), mediaCursor.getLong(2), mediaCursor.getLong(3)); waypointCursor = resolver.query(waypointUri, new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE, Waypoints.ALTITUDE, Waypoints.TIME }, null, null, null); serializer.text("\n"); serializer.startTag("", "wpt"); if (waypointCursor != null && waypointCursor.moveToFirst()) { serializer.attribute(null, "lat", Double.toString(waypointCursor.getDouble(0))); serializer.attribute(null, "lon", Double.toString(waypointCursor.getDouble(1))); serializer.text("\n"); serializer.startTag("", "ele"); serializer.text(Double.toString(waypointCursor.getDouble(2))); serializer.endTag("", "ele"); serializer.text("\n"); serializer.startTag("", "time"); Date time = new Date(waypointCursor.getLong(3)); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(time)); } serializer.endTag("", "time"); } if (waypointCursor != null) { waypointCursor.close(); waypointCursor = null; } Uri mediaUri = Uri.parse(mediaCursor.getString(0)); if (mediaUri.getScheme().equals("file")) { if (mediaUri.getLastPathSegment().endsWith("3gp")) { String fileName = includeMediaFile(mediaUri.getLastPathSegment()); quickTag(serializer, "", "name", fileName); serializer.startTag("", "link"); serializer.attribute(null, "href", fileName); quickTag(serializer, "", "text", fileName); serializer.endTag("", "link"); } else if (mediaUri.getLastPathSegment().endsWith("jpg")) { String mediaPathPrefix = Constants.getSdCardDirectory(mContext); String fileName = includeMediaFile(mediaPathPrefix + mediaUri.getLastPathSegment()); quickTag(serializer, "", "name", fileName); serializer.startTag("", "link"); serializer.attribute(null, "href", fileName); quickTag(serializer, "", "text", fileName); serializer.endTag("", "link"); } else if (mediaUri.getLastPathSegment().endsWith("txt")) { quickTag(serializer, "", "name", mediaUri.getLastPathSegment()); serializer.startTag("", "desc"); if (buf != null) { buf.close(); } buf = new BufferedReader(new FileReader(mediaUri.getEncodedPath())); String line; while ((line = buf.readLine()) != null) { serializer.text(line); serializer.text("\n"); } serializer.endTag("", "desc"); } } else if (mediaUri.getScheme().equals("content")) { if ((GPStracking.AUTHORITY + ".string").equals(mediaUri.getAuthority())) { quickTag(serializer, "", "name", mediaUri.getLastPathSegment()); } else if (mediaUri.getAuthority().equals("media")) { Cursor mediaItemCursor = null; try { mediaItemCursor = resolver.query(mediaUri, new String[] { MediaColumns.DATA, MediaColumns.DISPLAY_NAME }, null, null, null); if (mediaItemCursor.moveToFirst()) { String fileName = includeMediaFile(mediaItemCursor.getString(0)); quickTag(serializer, "", "name", fileName); serializer.startTag("", "link"); serializer.attribute(null, "href", fileName); quickTag(serializer, "", "text", mediaItemCursor.getString(1)); serializer.endTag("", "link"); } } finally { if (mediaItemCursor != null) { mediaItemCursor.close(); } } } } serializer.text("\n"); serializer.endTag("", "wpt"); } while (mediaCursor.moveToNext()); } } finally { if (mediaCursor != null) { mediaCursor.close(); } if (waypointCursor != null) { waypointCursor.close(); } if (buf != null) buf.close(); } } @Override protected String getContentType() { return needsBundling() ? "application/zip" : "text/xml"; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/GpxCreator.java
Java
gpl3
20,276
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.db.GPStracking; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import org.xmlpull.v1.XmlSerializer; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore.MediaColumns; import android.util.Log; import android.util.Xml; /** * Create a KMZ version of a stored track * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class KmzCreator extends XmlCreator { public static final String NS_SCHEMA = "http://www.w3.org/2001/XMLSchema-instance"; public static final String NS_KML_22 = "http://www.opengis.net/kml/2.2"; public static final SimpleDateFormat ZULU_DATE_FORMATER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); static { TimeZone utc = TimeZone.getTimeZone("UTC"); ZULU_DATE_FORMATER.setTimeZone(utc); // ZULU_DATE_FORMAT format ends with Z for UTC so make that true } private String TAG = "OGT.KmzCreator"; public KmzCreator(Context context, Uri trackUri, String chosenFileName, ProgressListener listener) { super(context, trackUri, chosenFileName, listener); } @Override protected Uri doInBackground(Void... params) { determineProgressGoal(); Uri resultFilename = exportKml(); return resultFilename; } private Uri exportKml() { if (mFileName.endsWith(".kmz") || mFileName.endsWith(".zip")) { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName.substring(0, mFileName.length() - 4)); } else { setExportDirectoryPath(Constants.getSdCardDirectory(mContext) + mFileName); } new File(getExportDirectoryPath()).mkdirs(); String xmlFilePath = getExportDirectoryPath() + "/doc.kml"; String resultFilename = null; FileOutputStream fos = null; BufferedOutputStream buf = null; try { verifySdCardAvailibility(); XmlSerializer serializer = Xml.newSerializer(); File xmlFile = new File(xmlFilePath); fos = new FileOutputStream(xmlFile); buf = new BufferedOutputStream(fos, 8192); serializer.setOutput(buf, "UTF-8"); serializeTrack(mTrackUri, mFileName, serializer); buf.close(); buf = null; fos.close(); fos = null; resultFilename = bundlingMediaAndXml(xmlFile.getParentFile().getName(), ".kmz"); mFileName = new File(resultFilename).getName(); } catch (IllegalArgumentException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_filename); handleError(mContext.getString(R.string.taskerror_kmz_write), e, text); } catch (IllegalStateException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_kmz_write), e, text); } catch (IOException e) { String text = mContext.getString(R.string.ticker_failed) + " \"" + xmlFilePath + "\" " + mContext.getString(R.string.error_writesdcard); handleError(mContext.getString(R.string.taskerror_kmz_write), e, text); } finally { if (buf != null) { try { buf.close(); } catch (IOException e) { Log.e(TAG, "Failed to close buf after completion, ignoring.", e); } } if (fos != null) { try { fos.close(); } catch (IOException e) { Log.e(TAG, "Failed to close fos after completion, ignoring.", e); } } } return Uri.fromFile(new File(resultFilename)); } private void serializeTrack(Uri trackUri, String trackName, XmlSerializer serializer) throws IOException { serializer.startDocument("UTF-8", true); serializer.setPrefix("xsi", NS_SCHEMA); serializer.setPrefix("kml", NS_KML_22); serializer.startTag("", "kml"); serializer.attribute(NS_SCHEMA, "schemaLocation", NS_KML_22 + " http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd"); serializer.attribute(null, "xmlns", NS_KML_22); serializer.text("\n"); serializer.startTag("", "Document"); serializer.text("\n"); quickTag(serializer, "", "name", trackName); /* from <name/> upto <Folder/> */ serializeTrackHeader(serializer, trackUri); serializer.text("\n"); serializer.endTag("", "Document"); serializer.endTag("", "kml"); serializer.endDocument(); } private String serializeTrackHeader(XmlSerializer serializer, Uri trackUri) throws IOException { ContentResolver resolver = mContext.getContentResolver(); Cursor trackCursor = null; String name = null; try { trackCursor = resolver.query(trackUri, new String[] { Tracks.NAME }, null, null, null); if (trackCursor.moveToFirst()) { serializer.text("\n"); serializer.startTag("", "Style"); serializer.attribute(null, "id", "lineStyle"); serializer.startTag("", "LineStyle"); serializer.text("\n"); serializer.startTag("", "color"); serializer.text("99ffac59"); serializer.endTag("", "color"); serializer.text("\n"); serializer.startTag("", "width"); serializer.text("6"); serializer.endTag("", "width"); serializer.text("\n"); serializer.endTag("", "LineStyle"); serializer.text("\n"); serializer.endTag("", "Style"); serializer.text("\n"); serializer.startTag("", "Folder"); name = trackCursor.getString(0); serializer.text("\n"); quickTag(serializer, "", "name", name); serializer.text("\n"); serializer.startTag("", "open"); serializer.text("1"); serializer.endTag("", "open"); serializer.text("\n"); serializeSegments(serializer, Uri.withAppendedPath(trackUri, "segments")); serializer.text("\n"); serializer.endTag("", "Folder"); } } finally { if (trackCursor != null) { trackCursor.close(); } } return name; } /** * <pre> * &lt;Folder> * &lt;Placemark> * serializeSegmentToTimespan() * &lt;LineString> * serializeWaypoints() * &lt;/LineString> * &lt;/Placemark> * &lt;Placemark/> * &lt;Placemark/> * &lt;/Folder> * </pre> * * @param serializer * @param segments * @throws IOException */ private void serializeSegments(XmlSerializer serializer, Uri segments) throws IOException { Cursor segmentCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { segmentCursor = resolver.query(segments, new String[] { Segments._ID }, null, null, null); if (segmentCursor.moveToFirst()) { do { Uri waypoints = Uri.withAppendedPath(segments, segmentCursor.getLong(0) + "/waypoints"); serializer.text("\n"); serializer.startTag("", "Folder"); serializer.text("\n"); serializer.startTag("", "name"); serializer.text(String.format("Segment %d", 1 + segmentCursor.getPosition())); serializer.endTag("", "name"); serializer.text("\n"); serializer.startTag("", "open"); serializer.text("1"); serializer.endTag("", "open"); /* Single <TimeSpan/> element */ serializeSegmentToTimespan(serializer, waypoints); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); serializer.startTag("", "name"); serializer.text("Path"); serializer.endTag("", "name"); serializer.text("\n"); serializer.startTag("", "styleUrl"); serializer.text("#lineStyle"); serializer.endTag("", "styleUrl"); serializer.text("\n"); serializer.startTag("", "LineString"); serializer.text("\n"); serializer.startTag("", "tessellate"); serializer.text("0"); serializer.endTag("", "tessellate"); serializer.text("\n"); serializer.startTag("", "altitudeMode"); serializer.text("clampToGround"); serializer.endTag("", "altitudeMode"); /* Single <coordinates/> element */ serializeWaypoints(serializer, waypoints); serializer.text("\n"); serializer.endTag("", "LineString"); serializer.text("\n"); serializer.endTag("", "Placemark"); serializeWaypointDescription(serializer, Uri.withAppendedPath(segments, "/" + segmentCursor.getLong(0) + "/media")); serializer.text("\n"); serializer.endTag("", "Folder"); } while (segmentCursor.moveToNext()); } } finally { if (segmentCursor != null) { segmentCursor.close(); } } } /** * &lt;TimeSpan>&lt;begin>...&lt;/begin>&lt;end>...&lt;/end>&lt;/TimeSpan> * * @param serializer * @param waypoints * @throws IOException */ private void serializeSegmentToTimespan(XmlSerializer serializer, Uri waypoints) throws IOException { Cursor waypointsCursor = null; Date segmentStartTime = null; Date segmentEndTime = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(waypoints, new String[] { Waypoints.TIME }, null, null, null); if (waypointsCursor.moveToFirst()) { segmentStartTime = new Date(waypointsCursor.getLong(0)); if (waypointsCursor.moveToLast()) { segmentEndTime = new Date(waypointsCursor.getLong(0)); serializer.text("\n"); serializer.startTag("", "TimeSpan"); serializer.text("\n"); serializer.startTag("", "begin"); synchronized (ZULU_DATE_FORMATER) { serializer.text(ZULU_DATE_FORMATER.format(segmentStartTime)); serializer.endTag("", "begin"); serializer.text("\n"); serializer.startTag("", "end"); serializer.text(ZULU_DATE_FORMATER.format(segmentEndTime)); } serializer.endTag("", "end"); serializer.text("\n"); serializer.endTag("", "TimeSpan"); } } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } /** * &lt;coordinates>...&lt;/coordinates> * * @param serializer * @param waypoints * @throws IOException */ private void serializeWaypoints(XmlSerializer serializer, Uri waypoints) throws IOException { Cursor waypointsCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(waypoints, new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, null, null, null); if (waypointsCursor.moveToFirst()) { serializer.text("\n"); serializer.startTag("", "coordinates"); do { mProgressAdmin.addWaypointProgress(1); // Single Coordinate tuple serializeCoordinates(serializer, waypointsCursor); serializer.text(" "); } while (waypointsCursor.moveToNext()); serializer.endTag("", "coordinates"); } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } /** * lon,lat,alt tuple without trailing spaces * * @param serializer * @param waypointsCursor * @throws IOException */ private void serializeCoordinates(XmlSerializer serializer, Cursor waypointsCursor) throws IOException { serializer.text(Double.toString(waypointsCursor.getDouble(0))); serializer.text(","); serializer.text(Double.toString(waypointsCursor.getDouble(1))); serializer.text(","); serializer.text(Double.toString(waypointsCursor.getDouble(2))); } private void serializeWaypointDescription(XmlSerializer serializer, Uri media) throws IOException { String mediaPathPrefix = Constants.getSdCardDirectory(mContext); Cursor mediaCursor = null; ContentResolver resolver = mContext.getContentResolver(); BufferedReader buf = null; try { mediaCursor = resolver.query(media, new String[] { Media.URI, Media.TRACK, Media.SEGMENT, Media.WAYPOINT }, null, null, null); if (mediaCursor.moveToFirst()) { do { Uri mediaUri = Uri.parse(mediaCursor.getString(0)); Uri singleWaypointUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mediaCursor.getLong(1) + "/segments/" + mediaCursor.getLong(2) + "/waypoints/" + mediaCursor.getLong(3)); String lastPathSegment = mediaUri.getLastPathSegment(); if (mediaUri.getScheme().equals("file")) { if (lastPathSegment.endsWith("3gp")) { String includedMediaFile = includeMediaFile(lastPathSegment); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializer.text("\n"); serializer.startTag("", "description"); String kmlAudioUnsupported = mContext.getString(R.string.kmlVideoUnsupported); serializer.text(String.format(kmlAudioUnsupported, includedMediaFile)); serializer.endTag("", "description"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } else if (lastPathSegment.endsWith("jpg")) { String includedMediaFile = includeMediaFile(mediaPathPrefix + lastPathSegment); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializer.text("\n"); quickTag(serializer, "", "description", "<img src=\"" + includedMediaFile + "\" width=\"500px\"/><br/>" + lastPathSegment); serializer.text("\n"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } else if (lastPathSegment.endsWith("txt")) { serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializer.text("\n"); serializer.startTag("", "description"); if(buf != null ) buf.close(); buf = new BufferedReader(new FileReader(mediaUri.getEncodedPath())); String line; while ((line = buf.readLine()) != null) { serializer.text(line); serializer.text("\n"); } serializer.endTag("", "description"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } } else if (mediaUri.getScheme().equals("content")) { if (mediaUri.getAuthority().equals(GPStracking.AUTHORITY + ".string")) { serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", lastPathSegment); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } else if (mediaUri.getAuthority().equals("media")) { Cursor mediaItemCursor = null; try { mediaItemCursor = resolver.query(mediaUri, new String[] { MediaColumns.DATA, MediaColumns.DISPLAY_NAME }, null, null, null); if (mediaItemCursor.moveToFirst()) { String includedMediaFile = includeMediaFile(mediaItemCursor.getString(0)); serializer.text("\n"); serializer.startTag("", "Placemark"); serializer.text("\n"); quickTag(serializer, "", "name", mediaItemCursor.getString(1)); serializer.text("\n"); serializer.startTag("", "description"); String kmlAudioUnsupported = mContext.getString(R.string.kmlAudioUnsupported); serializer.text(String.format(kmlAudioUnsupported, includedMediaFile)); serializer.endTag("", "description"); serializeMediaPoint(serializer, singleWaypointUri); serializer.text("\n"); serializer.endTag("", "Placemark"); } } finally { if (mediaItemCursor != null) { mediaItemCursor.close(); } } } } } while (mediaCursor.moveToNext()); } } finally { if (mediaCursor != null) { mediaCursor.close(); } if(buf != null ) buf.close(); } } /** * &lt;Point>...&lt;/Point> &lt;shape>rectangle&lt;/shape> * * @param serializer * @param singleWaypointUri * @throws IllegalArgumentException * @throws IllegalStateException * @throws IOException */ private void serializeMediaPoint(XmlSerializer serializer, Uri singleWaypointUri) throws IllegalArgumentException, IllegalStateException, IOException { Cursor waypointsCursor = null; ContentResolver resolver = mContext.getContentResolver(); try { waypointsCursor = resolver.query(singleWaypointUri, new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, null, null, null); if (waypointsCursor.moveToFirst()) { serializer.text("\n"); serializer.startTag("", "Point"); serializer.text("\n"); serializer.startTag("", "coordinates"); serializeCoordinates(serializer, waypointsCursor); serializer.endTag("", "coordinates"); serializer.text("\n"); serializer.endTag("", "Point"); serializer.text("\n"); } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } @Override protected String getContentType() { return "application/vnd.google-earth.kmz"; } @Override public boolean needsBundling() { return true; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/KmzCreator.java
Java
gpl3
23,091
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Jul 9, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.tasks; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ShareTrack; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import android.content.Context; import android.net.Uri; /** * ???? * * @version $Id:$ * @author rene (c) Jul 9, 2011, Sogeti B.V. */ public class KmzSharing extends KmzCreator { public KmzSharing(Context context, Uri trackUri, String chosenFileName, ProgressListener listener) { super(context, trackUri, chosenFileName, listener); } @Override protected void onPostExecute(Uri resultFilename) { super.onPostExecute(resultFilename); ShareTrack.sendFile(mContext, resultFilename, mContext.getString(R.string.email_kmzbody), getContentType()); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/tasks/KmzSharing.java
Java
gpl3
2,322
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.UnitsI18n; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; public class StatisticsCalulator extends AsyncTask<Uri, Void, Void> { @SuppressWarnings("unused") private static final String TAG = "OGT.StatisticsCalulator"; private Context mContext; private String overallavgSpeedText = "Unknown"; private String avgSpeedText = "Unknown"; private String maxSpeedText = "Unknown"; private String ascensionText = "Unknown"; private String minSpeedText = "Unknown"; private String tracknameText = "Unknown"; private String waypointsText = "Unknown"; private String distanceText = "Unknown"; private long mStarttime = -1; private long mEndtime = -1; private UnitsI18n mUnits; private double mMaxSpeed; private double mMaxAltitude; private double mMinAltitude; private double mAscension; private double mDistanceTraveled; private long mDuration; private double mAverageActiveSpeed; private StatisticsDelegate mDelegate; public StatisticsCalulator( Context ctx, UnitsI18n units, StatisticsDelegate delegate ) { mContext = ctx; mUnits = units; mDelegate = delegate; } private void updateCalculations( Uri trackUri ) { mStarttime = -1; mEndtime = -1; mMaxSpeed = 0; mAverageActiveSpeed = 0; mMaxAltitude = 0; mMinAltitude = 0; mAscension = 0; mDistanceTraveled = 0f; mDuration = 0; long duration = 1; double ascension = 0; ContentResolver resolver = mContext.getContentResolver(); Cursor waypointsCursor = null; try { waypointsCursor = resolver.query( Uri.withAppendedPath( trackUri, "waypoints" ), new String[] { "max (" + Waypoints.TABLE + "." + Waypoints.SPEED + ")" , "max (" + Waypoints.TABLE + "." + Waypoints.ALTITUDE + ")" , "min (" + Waypoints.TABLE + "." + Waypoints.ALTITUDE + ")" , "count(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null ); if( waypointsCursor.moveToLast() ) { mMaxSpeed = waypointsCursor.getDouble( 0 ); mMaxAltitude = waypointsCursor.getDouble( 1 ); mMinAltitude = waypointsCursor.getDouble( 2 ); long nrWaypoints = waypointsCursor.getLong( 3 ); waypointsText = nrWaypoints + ""; } waypointsCursor.close(); waypointsCursor = resolver.query( Uri.withAppendedPath( trackUri, "waypoints" ), new String[] { "avg (" + Waypoints.TABLE + "." + Waypoints.SPEED + ")" }, Waypoints.TABLE + "." + Waypoints.SPEED +" > ?", new String[] { ""+Constants.MIN_STATISTICS_SPEED }, null ); if( waypointsCursor.moveToLast() ) { mAverageActiveSpeed = waypointsCursor.getDouble( 0 ); } } finally { if( waypointsCursor != null ) { waypointsCursor.close(); } } Cursor trackCursor = null; try { trackCursor = resolver.query( trackUri, new String[] { Tracks.NAME }, null, null, null ); if( trackCursor.moveToLast() ) { tracknameText = trackCursor.getString( 0 ); } } finally { if( trackCursor != null ) { trackCursor.close(); } } Cursor segments = null; Location lastLocation = null; Location lastAltitudeLocation = null; Location currentLocation = null; try { Uri segmentsUri = Uri.withAppendedPath( trackUri, "segments" ); segments = resolver.query( segmentsUri, new String[] { Segments._ID }, null, null, null ); if( segments.moveToFirst() ) { do { long segmentsId = segments.getLong( 0 ); Cursor waypoints = null; try { Uri waypointsUri = Uri.withAppendedPath( segmentsUri, segmentsId + "/waypoints" ); waypoints = resolver.query( waypointsUri, new String[] { Waypoints._ID, Waypoints.TIME, Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, null, null, null ); if( waypoints.moveToFirst() ) { do { if( mStarttime < 0 ) { mStarttime = waypoints.getLong( 1 ); } currentLocation = new Location( this.getClass().getName() ); currentLocation.setTime( waypoints.getLong( 1 ) ); currentLocation.setLongitude( waypoints.getDouble( 2 ) ); currentLocation.setLatitude( waypoints.getDouble( 3 ) ); currentLocation.setAltitude( waypoints.getDouble( 4 ) ); // Do no include obvious wrong 0.0 lat 0.0 long, skip to next value in while-loop if( currentLocation.getLatitude() == 0.0d || currentLocation.getLongitude() == 0.0d ) { continue; } if( lastLocation != null ) { float travelPart = lastLocation.distanceTo( currentLocation ); long timePart = currentLocation.getTime() - lastLocation.getTime(); mDistanceTraveled += travelPart; duration += timePart; } if( currentLocation.hasAltitude() ) { if( lastAltitudeLocation != null ) { if( currentLocation.getTime() - lastAltitudeLocation.getTime() > 5*60*1000 ) // more then a 5m of climbing { if( currentLocation.getAltitude() > lastAltitudeLocation.getAltitude()+1 ) // more then 1m climb { ascension += currentLocation.getAltitude() - lastAltitudeLocation.getAltitude(); lastAltitudeLocation = currentLocation; } else { lastAltitudeLocation = currentLocation; } } } else { lastAltitudeLocation = currentLocation; } } lastLocation = currentLocation; mEndtime = lastLocation.getTime(); } while( waypoints.moveToNext() ); mDuration = mEndtime - mStarttime; } } finally { if( waypoints != null ) { waypoints.close(); } } lastLocation = null; } while( segments.moveToNext() ); } } finally { if( segments != null ) { segments.close(); } } double maxSpeed = mUnits.conversionFromMetersPerSecond( mMaxSpeed ); double overallavgSpeedfl = mUnits.conversionFromMeterAndMiliseconds( mDistanceTraveled, mDuration ); double avgSpeedfl = mUnits.conversionFromMeterAndMiliseconds( mDistanceTraveled, duration ); double traveled = mUnits.conversionFromMeter( mDistanceTraveled ); avgSpeedText = mUnits.formatSpeed( avgSpeedfl, true ); overallavgSpeedText = mUnits.formatSpeed( overallavgSpeedfl, true ); maxSpeedText = mUnits.formatSpeed( maxSpeed, true ); distanceText = String.format( "%.2f %s", traveled, mUnits.getDistanceUnit() ); ascensionText = String.format( "%.0f %s", ascension, mUnits.getHeightUnit() ); } /** * Get the overallavgSpeedText. * * @return Returns the overallavgSpeedText as a String. */ public String getOverallavgSpeedText() { return overallavgSpeedText; } /** * Get the avgSpeedText. * * @return Returns the avgSpeedText as a String. */ public String getAvgSpeedText() { return avgSpeedText; } /** * Get the maxSpeedText. * * @return Returns the maxSpeedText as a String. */ public String getMaxSpeedText() { return maxSpeedText; } /** * Get the minSpeedText. * * @return Returns the minSpeedText as a String. */ public String getMinSpeedText() { return minSpeedText; } /** * Get the tracknameText. * * @return Returns the tracknameText as a String. */ public String getTracknameText() { return tracknameText; } /** * Get the waypointsText. * * @return Returns the waypointsText as a String. */ public String getWaypointsText() { return waypointsText; } /** * Get the distanceText. * * @return Returns the distanceText as a String. */ public String getDistanceText() { return distanceText; } /** * Get the starttime. * * @return Returns the starttime as a long. */ public long getStarttime() { return mStarttime; } /** * Get the endtime. * * @return Returns the endtime as a long. */ public long getEndtime() { return mEndtime; } /** * Get the maximum speed. * * @return Returns the maxSpeeddb as m/s in a double. */ public double getMaxSpeed() { return mMaxSpeed; } /** * Get the min speed. * * @return Returns the average speed as m/s in a double. */ public double getAverageStatisicsSpeed() { return mAverageActiveSpeed; } /** * Get the maxAltitude. * * @return Returns the maxAltitude as a double. */ public double getMaxAltitude() { return mMaxAltitude; } /** * Get the minAltitude. * * @return Returns the minAltitude as a double. */ public double getMinAltitude() { return mMinAltitude; } /** * Get the total ascension in m. * * @return Returns the ascension as a double. */ public double getAscension() { return mAscension; } public CharSequence getAscensionText() { return ascensionText; } /** * Get the distanceTraveled. * * @return Returns the distanceTraveled as a float. */ public double getDistanceTraveled() { return mDistanceTraveled; } /** * Get the mUnits. * * @return Returns the mUnits as a UnitsI18n. */ public UnitsI18n getUnits() { return mUnits; } public String getDurationText() { long s = mDuration / 1000; String duration = String.format("%dh:%02dm:%02ds", s/3600, (s%3600)/60, (s%60)); return duration; } @Override protected Void doInBackground(Uri... params) { this.updateCalculations(params[0]); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if( mDelegate != null ) { mDelegate.finishedCalculations(this); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/utils/StatisticsCalulator.java
Java
gpl3
13,828
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import java.text.DateFormat; import java.util.Date; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.UnitsI18n; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.CornerPathEffect; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Typeface; import android.location.Location; import android.net.Uri; import android.util.AttributeSet; import android.view.View; /** * Calculate and draw graphs of track data * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class GraphCanvas extends View { @SuppressWarnings("unused") private static final String TAG = "OGT.GraphCanvas"; public static final int TIMESPEEDGRAPH = 0; public static final int DISTANCESPEEDGRAPH = 1; public static final int TIMEALTITUDEGRAPH = 2; public static final int DISTANCEALTITUDEGRAPH = 3; private Uri mUri; private Bitmap mRenderBuffer; private Canvas mRenderCanvas; private Context mContext; private UnitsI18n mUnits; private int mGraphType = -1; private long mEndTime; private long mStartTime; private double mDistance; private int mHeight; private int mWidth; private int mMinAxis; private int mMaxAxis; private double mMinAlititude; private double mMaxAlititude; private double mHighestSpeedNumber; private double mDistanceDrawn; private long mStartTimeDrawn; private long mEndTimeDrawn; float density = Resources.getSystem().getDisplayMetrics().density; private Paint whiteText ; private Paint ltgreyMatrixDashed; private Paint greenGraphLine; private Paint dkgreyMatrixLine; private Paint whiteCenteredText; private Paint dkgrayLargeType; public GraphCanvas( Context context, AttributeSet attrs ) { this(context, attrs, 0); } public GraphCanvas( Context context, AttributeSet attrs, int defStyle ) { super(context, attrs, defStyle); mContext = context; whiteText = new Paint(); whiteText.setColor( Color.WHITE ); whiteText.setAntiAlias( true ); whiteText.setTextSize( (int)(density * 12) ); whiteCenteredText = new Paint(); whiteCenteredText.setColor( Color.WHITE ); whiteCenteredText.setAntiAlias( true ); whiteCenteredText.setTextAlign( Paint.Align.CENTER ); whiteCenteredText.setTextSize( (int)(density * 12) ); ltgreyMatrixDashed = new Paint(); ltgreyMatrixDashed.setColor( Color.LTGRAY ); ltgreyMatrixDashed.setStrokeWidth( 1 ); ltgreyMatrixDashed.setPathEffect( new DashPathEffect( new float[]{2,4}, 0 ) ); greenGraphLine = new Paint(); greenGraphLine.setPathEffect( new CornerPathEffect( 8 ) ); greenGraphLine.setStyle( Paint.Style.STROKE ); greenGraphLine.setStrokeWidth( 4 ); greenGraphLine.setAntiAlias( true ); greenGraphLine.setColor(Color.GREEN); dkgreyMatrixLine = new Paint(); dkgreyMatrixLine.setColor( Color.DKGRAY ); dkgreyMatrixLine.setStrokeWidth( 2 ); dkgrayLargeType = new Paint(); dkgrayLargeType.setColor( Color.LTGRAY ); dkgrayLargeType.setAntiAlias( true ); dkgrayLargeType.setTextAlign( Paint.Align.CENTER ); dkgrayLargeType.setTextSize( (int)(density * 21) ); dkgrayLargeType.setTypeface( Typeface.DEFAULT_BOLD ); } /** * Set the dataset for which to draw data. Also provide hints and helpers. * * @param uri * @param startTime * @param endTime * @param distance * @param minAlititude * @param maxAlititude * @param maxSpeed * @param units */ public void setData( Uri uri, StatisticsCalulator calc ) { boolean rerender = false; if( uri.equals( mUri ) ) { double distanceDrawnPercentage = mDistanceDrawn / mDistance; double duractionDrawnPercentage = (double)((1d+mEndTimeDrawn-mStartTimeDrawn) / (1d+mEndTime-mStartTime)); rerender = distanceDrawnPercentage < 0.99d || duractionDrawnPercentage < 0.99d; } else { if( mRenderBuffer == null && super.getWidth() > 0 && super.getHeight() > 0 ) { initRenderBuffer(super.getWidth(), super.getHeight()); } rerender = true; } mUri = uri; mUnits = calc.getUnits(); mMinAlititude = mUnits.conversionFromMeterToHeight( calc.getMinAltitude() ); mMaxAlititude = mUnits.conversionFromMeterToHeight( calc.getMaxAltitude() ); if( mUnits.isUnitFlipped() ) { mHighestSpeedNumber = 1.5 * mUnits.conversionFromMetersPerSecond( calc.getAverageStatisicsSpeed() ); } else { mHighestSpeedNumber = mUnits.conversionFromMetersPerSecond( calc.getMaxSpeed() ); } mStartTime = calc.getStarttime(); mEndTime = calc.getEndtime(); mDistance = calc.getDistanceTraveled(); if( rerender ) { renderGraph(); } } public synchronized void clearData() { mUri = null; mUnits = null; mRenderBuffer = null; } public void setType( int graphType) { if( mGraphType != graphType ) { mGraphType = graphType; renderGraph(); } } public int getType() { return mGraphType; } @Override protected synchronized void onSizeChanged( int w, int h, int oldw, int oldh ) { super.onSizeChanged( w, h, oldw, oldh ); initRenderBuffer(w, h); renderGraph(); } private void initRenderBuffer(int w, int h) { mRenderBuffer = Bitmap.createBitmap( w, h, Config.ARGB_8888 ); mRenderCanvas = new Canvas( mRenderBuffer ); } @Override protected synchronized void onDraw( Canvas canvas ) { super.onDraw(canvas); if( mRenderBuffer != null ) { canvas.drawBitmap( mRenderBuffer, 0, 0, null ); } } private synchronized void renderGraph() { if( mRenderBuffer != null && mUri != null ) { mRenderBuffer.eraseColor( Color.TRANSPARENT ); switch( mGraphType ) { case( TIMESPEEDGRAPH ): setupSpeedAxis(); drawGraphType(); drawTimeAxisGraphOnCanvas( new String[] { Waypoints.TIME, Waypoints.SPEED }, Constants.MIN_STATISTICS_SPEED ); drawSpeedsTexts(); drawTimeTexts(); break; case( DISTANCESPEEDGRAPH ): setupSpeedAxis(); drawGraphType(); drawDistanceAxisGraphOnCanvas( new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.SPEED }, Constants.MIN_STATISTICS_SPEED ); drawSpeedsTexts(); drawDistanceTexts(); break; case( TIMEALTITUDEGRAPH ): setupAltitudeAxis(); drawGraphType(); drawTimeAxisGraphOnCanvas( new String[] { Waypoints.TIME, Waypoints.ALTITUDE }, -1000d ); drawAltitudesTexts(); drawTimeTexts(); break; case( DISTANCEALTITUDEGRAPH ): setupAltitudeAxis(); drawGraphType(); drawDistanceAxisGraphOnCanvas( new String[] { Waypoints.LONGITUDE, Waypoints.LATITUDE, Waypoints.ALTITUDE }, -1000d ); drawAltitudesTexts(); drawDistanceTexts(); break; default: break; } mDistanceDrawn = mDistance; mStartTimeDrawn = mStartTime; mEndTimeDrawn = mEndTime; } postInvalidate(); } /** * * @param params * @param minValue Minimum value of params[1] that will be drawn */ private void drawDistanceAxisGraphOnCanvas( String[] params, double minValue ) { ContentResolver resolver = mContext.getContentResolver(); Uri segmentsUri = Uri.withAppendedPath( mUri, "segments" ); Uri waypointsUri = null; Cursor segments = null; Cursor waypoints = null; double[][] values ; int[][] valueDepth; double distance = 1; try { segments = resolver.query( segmentsUri, new String[]{ Segments._ID }, null, null, null ); int segmentCount = segments.getCount(); values = new double[segmentCount][mWidth]; valueDepth = new int[segmentCount][mWidth]; if( segments.moveToFirst() ) { for(int segment=0;segment<segmentCount;segment++) { segments.moveToPosition( segment ); long segmentId = segments.getLong( 0 ); waypointsUri = Uri.withAppendedPath( segmentsUri, segmentId+"/waypoints" ); try { waypoints = resolver.query( waypointsUri, params, null, null, null ); if( waypoints.moveToFirst() ) { Location lastLocation = null; Location currentLocation = null; do { currentLocation = new Location( this.getClass().getName() ); currentLocation.setLongitude( waypoints.getDouble( 0 ) ); currentLocation.setLatitude( waypoints.getDouble( 1 ) ); // Do no include obvious wrong 0.0 lat 0.0 long, skip to next value in while-loop if( currentLocation.getLatitude() == 0.0d || currentLocation.getLongitude() == 0.0d ) { continue; } if( lastLocation != null ) { distance += lastLocation.distanceTo( currentLocation ); } lastLocation = currentLocation; double value = waypoints.getDouble( 2 ); if( value != 0 && value > minValue && segment < values.length ) { int x = (int) ((distance)*(mWidth-1) / mDistance); if( x > 0 && x < valueDepth[segment].length ) { valueDepth[segment][x]++; values[segment][x] = values[segment][x]+((value-values[segment][x])/valueDepth[segment][x]); } } } while( waypoints.moveToNext() ); } } finally { if( waypoints != null ) { waypoints.close(); } } } } } finally { if( segments != null ) { segments.close(); } } for( int segment=0;segment<values.length;segment++) { for( int x=0;x<values[segment].length;x++) { if( valueDepth[segment][x] > 0 ) { values[segment][x] = translateValue( values[segment][x] ); } } } drawGraph( values, valueDepth ); } private void drawTimeAxisGraphOnCanvas( String[] params, double minValue ) { ContentResolver resolver = mContext.getContentResolver(); Uri segmentsUri = Uri.withAppendedPath( mUri, "segments" ); Uri waypointsUri = null; Cursor segments = null; Cursor waypoints = null; long duration = 1+mEndTime - mStartTime; double[][] values ; int[][] valueDepth; try { segments = resolver.query( segmentsUri, new String[]{ Segments._ID }, null, null, null ); int segmentCount = segments.getCount(); values = new double[segmentCount][mWidth]; valueDepth = new int[segmentCount][mWidth]; if( segments.moveToFirst() ) { for(int segment=0;segment<segmentCount;segment++) { segments.moveToPosition( segment ); long segmentId = segments.getLong( 0 ); waypointsUri = Uri.withAppendedPath( segmentsUri, segmentId+"/waypoints" ); try { waypoints = resolver.query( waypointsUri, params, null, null, null ); if( waypoints.moveToFirst() ) { do { long time = waypoints.getLong( 0 ); double value = waypoints.getDouble( 1 ); if( value != 0 && value > minValue && segment < values.length ) { int x = (int) ((time-mStartTime)*(mWidth-1) / duration); if( x > 0 && x < valueDepth[segment].length ) { valueDepth[segment][x]++; values[segment][x] = values[segment][x]+((value-values[segment][x])/valueDepth[segment][x]); } } } while( waypoints.moveToNext() ); } } finally { if( waypoints != null ) { waypoints.close(); } } } } } finally { if( segments != null ) { segments.close(); } } for( int p=0;p<values.length;p++) { for( int x=0;x<values[p].length;x++) { if( valueDepth[p][x] > 0 ) { values[p][x] = translateValue( values[p][x] ); } } } drawGraph( values, valueDepth ); } private void setupAltitudeAxis() { mMinAxis = -4 + 4 * (int)(mMinAlititude / 4); mMaxAxis = 4 + 4 * (int)(mMaxAlititude / 4); mWidth = mRenderCanvas.getWidth()-5; mHeight = mRenderCanvas.getHeight()-10; } private void setupSpeedAxis() { mMinAxis = 0; mMaxAxis = 4 + 4 * (int)( mHighestSpeedNumber / 4); mWidth = mRenderCanvas.getWidth()-5; mHeight = mRenderCanvas.getHeight()-10; } private void drawAltitudesTexts() { mRenderCanvas.drawText( String.format( "%d %s", mMinAxis, mUnits.getHeightUnit() ) , 8, mHeight, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", (mMaxAxis+mMinAxis)/2, mUnits.getHeightUnit() ) , 8, 5+mHeight/2, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", mMaxAxis, mUnits.getHeightUnit() ), 8, 15, whiteText ); } private void drawSpeedsTexts() { mRenderCanvas.drawText( String.format( "%d %s", mMinAxis, mUnits.getSpeedUnit() ) , 8, mHeight, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", (mMaxAxis+mMinAxis)/2, mUnits.getSpeedUnit() ) , 8, 3+mHeight/2, whiteText ); mRenderCanvas.drawText( String.format( "%d %s", mMaxAxis, mUnits.getSpeedUnit() ) , 8, 7+whiteText.getTextSize(), whiteText ); } private void drawGraphType() { //float density = Resources.getSystem().getDisplayMetrics().density; String text; switch( mGraphType ) { case( TIMESPEEDGRAPH ): text = mContext.getResources().getString( R.string.graphtype_timespeed ); break; case( DISTANCESPEEDGRAPH ): text = mContext.getResources().getString( R.string.graphtype_distancespeed ); break; case( TIMEALTITUDEGRAPH ): text = mContext.getResources().getString( R.string.graphtype_timealtitude ); break; case( DISTANCEALTITUDEGRAPH ): text = mContext.getResources().getString( R.string.graphtype_distancealtitude ); break; default: text = "UNKNOWN GRAPH TYPE"; break; } mRenderCanvas.drawText( text, 5+mWidth/2, 5+mHeight/8, dkgrayLargeType ); } private void drawTimeTexts() { DateFormat timeInstance = android.text.format.DateFormat.getTimeFormat(this.getContext().getApplicationContext()); String start = timeInstance.format( new Date( mStartTime ) ); String half = timeInstance.format( new Date( (mEndTime+mStartTime)/2 ) ); String end = timeInstance.format( new Date( mEndTime ) ); Path yAxis; yAxis = new Path(); yAxis.moveTo( 5, 5+mHeight/2 ); yAxis.lineTo( 5, 5 ); mRenderCanvas.drawTextOnPath( String.format( start ), yAxis, 0, whiteCenteredText.getTextSize(), whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth/2 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth/2 , 5 ); mRenderCanvas.drawTextOnPath( String.format( half ), yAxis, 0, -3, whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth-1 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth-1 , 5 ); mRenderCanvas.drawTextOnPath( String.format( end ), yAxis, 0, -3, whiteCenteredText ); } private void drawDistanceTexts() { String start = String.format( "%.0f %s", mUnits.conversionFromMeter(0), mUnits.getDistanceUnit() ) ; String half = String.format( "%.0f %s", mUnits.conversionFromMeter(mDistance)/2, mUnits.getDistanceUnit() ) ; String end = String.format( "%.0f %s", mUnits.conversionFromMeter(mDistance) , mUnits.getDistanceUnit() ) ; Path yAxis; yAxis = new Path(); yAxis.moveTo( 5, 5+mHeight/2 ); yAxis.lineTo( 5, 5 ); mRenderCanvas.drawTextOnPath( String.format( start ), yAxis, 0, whiteText.getTextSize(), whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth/2 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth/2 , 5 ); mRenderCanvas.drawTextOnPath( String.format( half ), yAxis, 0, -3, whiteCenteredText ); yAxis = new Path(); yAxis.moveTo( 5+mWidth-1 , 5+mHeight/2 ); yAxis.lineTo( 5+mWidth-1 , 5 ); mRenderCanvas.drawTextOnPath( String.format( end ), yAxis, 0, -3, whiteCenteredText ); } private double translateValue( double val ) { switch( mGraphType ) { case( TIMESPEEDGRAPH ): case( DISTANCESPEEDGRAPH ): val = mUnits.conversionFromMetersPerSecond( val ); break; case( TIMEALTITUDEGRAPH ): case( DISTANCEALTITUDEGRAPH ): val = mUnits.conversionFromMeterToHeight( val ); break; default: break; } return val; } private void drawGraph( double[][] values, int[][] valueDepth ) { // Matrix // Horizontals mRenderCanvas.drawLine( 5, 5 , 5+mWidth, 5 , ltgreyMatrixDashed ); // top mRenderCanvas.drawLine( 5, 5+mHeight/4 , 5+mWidth, 5+mHeight/4 , ltgreyMatrixDashed ); // 2nd mRenderCanvas.drawLine( 5, 5+mHeight/2 , 5+mWidth, 5+mHeight/2 , ltgreyMatrixDashed ); // middle mRenderCanvas.drawLine( 5, 5+mHeight/4*3, 5+mWidth, 5+mHeight/4*3, ltgreyMatrixDashed ); // 3rd // Verticals mRenderCanvas.drawLine( 5+mWidth/4 , 5, 5+mWidth/4 , 5+mHeight, ltgreyMatrixDashed ); // 2nd mRenderCanvas.drawLine( 5+mWidth/2 , 5, 5+mWidth/2 , 5+mHeight, ltgreyMatrixDashed ); // middle mRenderCanvas.drawLine( 5+mWidth/4*3, 5, 5+mWidth/4*3, 5+mHeight, ltgreyMatrixDashed ); // 3rd mRenderCanvas.drawLine( 5+mWidth-1 , 5, 5+mWidth-1 , 5+mHeight, ltgreyMatrixDashed ); // right // The line Path mPath; int emptyValues = 0; mPath = new Path(); for( int p=0;p<values.length;p++) { int start = 0; while( valueDepth[p][start] == 0 && start < values[p].length-1 ) { start++; } mPath.moveTo( (float)start+5, 5f+ (float) ( mHeight - ( ( values[p][start]-mMinAxis )*mHeight ) / ( mMaxAxis-mMinAxis ) ) ); for( int x=start;x<values[p].length;x++) { double y = mHeight - ( ( values[p][x]-mMinAxis )*mHeight ) / ( mMaxAxis-mMinAxis ) ; if( valueDepth[p][x] > 0 ) { if( emptyValues > mWidth/10 ) { mPath.moveTo( (float)x+5, (float) y+5 ); } else { mPath.lineTo( (float)x+5, (float) y+5 ); } emptyValues = 0; } else { emptyValues++; } } } mRenderCanvas.drawPath( mPath, greenGraphLine ); // Axis's mRenderCanvas.drawLine( 5, 5 , 5 , 5+mHeight, dkgreyMatrixLine ); mRenderCanvas.drawLine( 5, 5+mHeight, 5+mWidth, 5+mHeight, dkgreyMatrixLine ); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/utils/GraphCanvas.java
Java
gpl3
23,312
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import android.app.Activity; import android.net.Uri; /** * Interface to which a Activity / Context can conform to receive progress * updates from async tasks * * @version $Id:$ * @author rene (c) May 29, 2011, Sogeti B.V. */ public interface ProgressListener { void setIndeterminate(boolean indeterminate); /** * Signifies the start of background task, will be followed by setProgress(int) calls. */ void started(); /** * Set the progress on the scale of 0...10000 * * @param value * * @see Activity.setProgress * @see Window.PROGRESS_END */ void setProgress(int value); /** * Signifies end of background task and the location of the result * * @param result */ void finished(Uri result); void showError(String task, String errorMessage, Exception exception); }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/utils/ProgressListener.java
Java
gpl3
2,432
package nl.sogeti.android.gpstracker.actions.utils; public interface StatisticsDelegate { void finishedCalculations(StatisticsCalulator calculated); }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/utils/StatisticsDelegate.java
Java
gpl3
154
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.actions.utils; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.util.Log; /** * Work around based on input from the comment section of * <a href="http://code.google.com/p/android/issues/detail?can=2&q=6191&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&id=6191">Issue 6191</a> * * @version $Id$ * @author rene (c) May 8, 2010, Sogeti B.V. */ public class ViewFlipper extends android.widget.ViewFlipper { private static final String TAG = "OGT.ViewFlipper"; public ViewFlipper(Context context) { super( context ); } public ViewFlipper(Context context, AttributeSet attrs) { super( context, attrs ); } /** * On api level 7 unexpected exception occur during orientation switching. * These are java.lang.IllegalArgumentException: Receiver not registered: android.widget.ViewFlipper$id * exceptions. On level 7, 8 and 9 devices these are ignored. */ @Override protected void onDetachedFromWindow() { if( Build.VERSION.SDK_INT > 7 ) { try { super.onDetachedFromWindow(); } catch( IllegalArgumentException e ) { Log.w( TAG, "Android project issue 6191 workaround." ); /* Quick catch and continue on api level 7+, the Eclair 2.1 / 2.2 */ } finally { super.stopFlipping(); } } else { super.onDetachedFromWindow(); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/actions/utils/ViewFlipper.java
Java
gpl3
3,082
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.adapter; import java.util.LinkedList; import java.util.List; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.GpxParser; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsTracks; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; /** * Organizes Breadcrumbs tasks based on demands on the BaseAdapter functions * * @version $Id:$ * @author rene (c) Apr 24, 2011, Sogeti B.V. */ public class BreadcrumbsAdapter extends BaseAdapter { private static final String TAG = "OGT.BreadcrumbsAdapter"; public static final boolean DEBUG = false; private Activity mContext; private LayoutInflater mInflater; private BreadcrumbsService mService; private List<Pair<Integer, Integer>> breadcrumbItems = new LinkedList<Pair<Integer, Integer>>(); public BreadcrumbsAdapter(Activity ctx, BreadcrumbsService service) { super(); mContext = ctx; mService = service; mInflater = LayoutInflater.from(mContext); } public void setService(BreadcrumbsService service) { mService = service; updateItemList(); } /** * Reloads the current list of known breadcrumb listview items * */ public void updateItemList() { mContext.runOnUiThread(new Runnable() { @Override public void run() { if (mService != null) { breadcrumbItems = mService.getAllItems(); notifyDataSetChanged(); } } }); } /** * @see android.widget.Adapter#getCount() */ @Override public int getCount() { if (mService != null) { if (mService.isAuthorized()) { return breadcrumbItems.size(); } else { return 1; } } else { return 0; } } /** * @see android.widget.Adapter#getItem(int) */ @Override public Object getItem(int position) { if (mService.isAuthorized()) { return breadcrumbItems.get(position); } else { return Constants.BREADCRUMBS_CONNECT; } } /** * @see android.widget.Adapter#getItemId(int) */ @Override public long getItemId(int position) { return position; } /** * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; if (mService.isAuthorized()) { int type = getItemViewType(position); if (convertView == null) { switch (type) { case Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE: view = mInflater.inflate(R.layout.breadcrumbs_bundle, null); break; case Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE: view = mInflater.inflate(R.layout.breadcrumbs_track, null); break; default: view = new TextView(null); break; } } else { view = convertView; } Pair<Integer, Integer> item = breadcrumbItems.get(position); mService.willDisplayItem(item); String name; switch (type) { case Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE: name = mService.getValueForItem((Pair<Integer, Integer>) item, BreadcrumbsTracks.NAME); ((TextView) view.findViewById(R.id.listitem_name)).setText(name); break; case Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE: TextView nameView = (TextView) view.findViewById(R.id.listitem_name); TextView dateView = (TextView) view.findViewById(R.id.listitem_from); nameView.setText(mService.getValueForItem(item, BreadcrumbsTracks.NAME)); String dateString = mService.getValueForItem(item, BreadcrumbsTracks.ENDTIME); if (dateString != null) { Long date = GpxParser.parseXmlDateTime(dateString); dateView.setText(date.toString()); } break; default: view = new TextView(null); break; } } else { if (convertView == null) { view = mInflater.inflate(R.layout.breadcrumbs_connect, null); } else { view = convertView; } ((TextView) view).setText(R.string.breadcrumbs_connect); } return view; } @Override public int getViewTypeCount() { int types = 4; return types; } @Override public int getItemViewType(int position) { if (mService.isAuthorized()) { Pair<Integer, Integer> item = breadcrumbItems.get(position); return item.first; } else { return Constants.BREADCRUMBS_CONNECT_ITEM_VIEW_TYPE; } } @Override public boolean areAllItemsEnabled() { return false; }; @Override public boolean isEnabled(int position) { int itemViewType = getItemViewType(position); return itemViewType == Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE || itemViewType == Constants.BREADCRUMBS_CONNECT_ITEM_VIEW_TYPE; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/adapter/BreadcrumbsAdapter.java
Java
gpl3
7,386
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.adapter; import java.util.LinkedHashMap; import java.util.Map; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import android.content.Context; import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.Adapter; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListAdapter; /** * Combines multiple Adapters into a sectioned ListAdapter * * @version $Id:$ * @author rene (c) Apr 24, 2011, Sogeti B.V. */ public class SectionedListAdapter extends BaseAdapter { @SuppressWarnings("unused") private static final String TAG = "OGT.SectionedListAdapter"; private Map<String, BaseAdapter> mSections; private ArrayAdapter<String> mHeaders; public SectionedListAdapter(Context ctx) { mHeaders = new ArrayAdapter<String>(ctx, R.layout.section_header); mSections = new LinkedHashMap<String, BaseAdapter>(); } public void addSection(String name, BaseAdapter adapter) { mHeaders.add(name); mSections.put(name, adapter); } @Override public void registerDataSetObserver(DataSetObserver observer) { super.registerDataSetObserver(observer); for( Adapter adapter : mSections.values() ) { adapter.registerDataSetObserver(observer); } } @Override public void unregisterDataSetObserver(DataSetObserver observer) { super.unregisterDataSetObserver(observer); for( Adapter adapter : mSections.values() ) { adapter.unregisterDataSetObserver(observer); } } /* * (non-Javadoc) * @see android.widget.Adapter#getCount() */ @Override public int getCount() { int count = 0; for (Adapter adapter : mSections.values()) { count += adapter.getCount() + 1; } return count; } /* * (non-Javadoc) * @see android.widget.Adapter#getItem(int) */ @Override public Object getItem(int position) { int countDown = position; Adapter adapter; for (String section : mSections.keySet()) { adapter = mSections.get(section); if (countDown == 0) { return section; } countDown--; if (countDown < adapter.getCount()) { return adapter.getItem(countDown); } countDown -= adapter.getCount(); } return null; } /* * (non-Javadoc) * @see android.widget.Adapter#getItemId(int) */ @Override public long getItemId(int position) { int countDown = position; Adapter adapter; for (String section : mSections.keySet()) { adapter = mSections.get(section); if (countDown == 0) { return position; } countDown--; if (countDown < adapter.getCount()) { long id = adapter.getItemId(countDown); return id; } countDown -= adapter.getCount(); } return -1; } /* * (non-Javadoc) * @see android.widget.Adapter#getView(int, android.view.View, * android.view.ViewGroup) */ @Override public View getView(final int position, View convertView, ViewGroup parent) { int sectionNumber = 0; int countDown = position; for (String section : mSections.keySet()) { Adapter adapter = mSections.get(section); int size = adapter.getCount() + 1; // check if position inside this section if (countDown == 0) { return mHeaders.getView(sectionNumber, convertView, parent); } if (countDown < size) { return adapter.getView(countDown - 1, convertView, parent); } // otherwise jump into next section countDown -= size; sectionNumber++; } return null; } @Override public int getViewTypeCount() { int types = 1; for (Adapter section : mSections.values()) { types += section.getViewTypeCount(); } return types; } @Override public int getItemViewType(int position) { int type = 1; Adapter adapter; int countDown = position; for (String section : mSections.keySet()) { adapter = mSections.get(section); int size = adapter.getCount() + 1; if (countDown == 0) { return Constants.SECTIONED_HEADER_ITEM_VIEW_TYPE; } else if (countDown < size) { return type + adapter.getItemViewType(countDown - 1); } countDown -= size; type += adapter.getViewTypeCount(); } return ListAdapter.IGNORE_ITEM_VIEW_TYPE; } @Override public boolean areAllItemsEnabled() { return false; }; @Override public boolean isEnabled(int position) { if( getItemViewType(position) == Constants.SECTIONED_HEADER_ITEM_VIEW_TYPE ) { return false; } else { int countDown = position; for (String section : mSections.keySet()) { BaseAdapter adapter = mSections.get(section); countDown--; int size = adapter.getCount() ; if (countDown < size) { return adapter.isEnabled(countDown); } // otherwise jump into next section countDown -= size; } } return false ; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/adapter/SectionedListAdapter.java
Java
gpl3
7,170
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.adapter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OptionalDataException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Set; import java.util.Vector; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.SpinnerAdapter; /** * Model containing agregrated data retrieved from the GoBreadcrumbs.com API * * @version $Id:$ * @author rene (c) May 9, 2011, Sogeti B.V. */ public class BreadcrumbsTracks extends Observable { public static final String DESCRIPTION = "DESCRIPTION"; public static final String NAME = "NAME"; public static final String ENDTIME = "ENDTIME"; public static final String TRACK_ID = "BREADCRUMBS_TRACK_ID"; public static final String BUNDLE_ID = "BREADCRUMBS_BUNDLE_ID"; public static final String ACTIVITY_ID = "BREADCRUMBS_ACTIVITY_ID"; public static final String DIFFICULTY = "DIFFICULTY"; public static final String STARTTIME = "STARTTIME"; public static final String ISPUBLIC = "ISPUBLIC"; public static final String RATING = "RATING"; public static final String LATITUDE = "LATITUDE"; public static final String LONGITUDE = "LONGITUDE"; public static final String TOTALDISTANCE = "TOTALDISTANCE"; public static final String TOTALTIME = "TOTALTIME"; private static final String TAG = "OGT.BreadcrumbsTracks"; private static final Integer CACHE_VERSION = Integer.valueOf(8); private static final String BREADCRUMSB_BUNDLES_CACHE_FILE = "breadcrumbs_bundles_cache.data"; private static final String BREADCRUMSB_ACTIVITY_CACHE_FILE = "breadcrumbs_activity_cache.data"; /** * Time in milliseconds that a persisted breadcrumbs cache is used without a * refresh */ private static final long CACHE_TIMEOUT = 1000 * 60;//1000*60*10 ; /** * Mapping from bundleId to a list of trackIds */ private static HashMap<Integer, List<Integer>> sBundlesWithTracks; /** * Map from activityId to a dictionary containing keys like NAME */ private static HashMap<Integer, Map<String, String>> sActivityMappings; /** * Map from bundleId to a dictionary containing keys like NAME and * DESCRIPTION */ private static HashMap<Integer, Map<String, String>> sBundleMappings; /** * Map from trackId to a dictionary containing keys like NAME, ISPUBLIC, * DESCRIPTION and more */ private static HashMap<Integer, Map<String, String>> sTrackMappings; /** * Cache of OGT Tracks that have a Breadcrumbs track id stored in the * meta-data table */ private Map<Long, Integer> mSyncedTracks = null; private static Set<Pair<Integer, Integer>> sScheduledTracksLoading; static { BreadcrumbsTracks.initCacheVariables(); } private static void initCacheVariables() { sBundlesWithTracks = new HashMap<Integer, List<Integer>>(); sActivityMappings = new HashMap<Integer, Map<String, String>>(); sBundleMappings = new HashMap<Integer, Map<String, String>>(); sTrackMappings = new HashMap<Integer, Map<String, String>>(); sScheduledTracksLoading = new HashSet<Pair<Integer, Integer>>(); } private ContentResolver mResolver; /** * Constructor: create a new BreadcrumbsTracks. * * @param resolver Content resolver to obtain local Breadcrumbs references */ public BreadcrumbsTracks(ContentResolver resolver) { mResolver = resolver; } public void addActivity(int activityId, String activityName) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addActivity(Integer " + activityId + " String " + activityName + ")"); } if (sActivityMappings.get(activityId) == null) { sActivityMappings.put(activityId, new HashMap<String, String>()); } sActivityMappings.get(activityId).put(NAME, activityName); setChanged(); notifyObservers(); } /** * Add bundle to the track list * * @param activityId * @param bundleId * @param bundleName * @param bundleDescription */ public void addBundle(int bundleId, String bundleName, String bundleDescription) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addBundle(Integer " + bundleId + ", String " + bundleName + ", String " + bundleDescription + ")"); } if (sBundleMappings.get(bundleId) == null) { sBundleMappings.put(bundleId, new HashMap<String, String>()); } if (sBundlesWithTracks.get(bundleId) == null) { sBundlesWithTracks.put(bundleId, new ArrayList<Integer>()); } sBundleMappings.get(bundleId).put(NAME, bundleName); sBundleMappings.get(bundleId).put(DESCRIPTION, bundleDescription); setChanged(); notifyObservers(); } /** * Add track to tracklist * * @param trackId * @param trackName * @param bundleId * @param trackDescription * @param difficulty * @param startTime * @param endTime * @param isPublic * @param lat * @param lng * @param totalDistance * @param totalTime * @param trackRating */ public void addTrack(int trackId, String trackName, int bundleId, String trackDescription, String difficulty, String startTime, String endTime, String isPublic, Float lat, Float lng, Float totalDistance, Integer totalTime, String trackRating) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addTrack(Integer " + trackId + ", String " + trackName + ", Integer " + bundleId + "..."); } if (sBundlesWithTracks.get(bundleId) == null) { sBundlesWithTracks.put(bundleId, new ArrayList<Integer>()); } if (!sBundlesWithTracks.get(bundleId).contains(trackId)) { sBundlesWithTracks.get(bundleId).add(trackId); sScheduledTracksLoading.remove(Pair.create(Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE, trackId)); } if (sTrackMappings.get(trackId) == null) { sTrackMappings.put(trackId, new HashMap<String, String>()); } putForTrack(trackId, NAME, trackName); putForTrack(trackId, ISPUBLIC, isPublic); putForTrack(trackId, STARTTIME, startTime); putForTrack(trackId, ENDTIME, endTime); putForTrack(trackId, DESCRIPTION, trackDescription); putForTrack(trackId, DIFFICULTY, difficulty); putForTrack(trackId, RATING, trackRating); putForTrack(trackId, LATITUDE, lat); putForTrack(trackId, LONGITUDE, lng); putForTrack(trackId, TOTALDISTANCE, totalDistance); putForTrack(trackId, TOTALTIME, totalTime); notifyObservers(); } public void addSyncedTrack(Long trackId, int bcTrackId) { if (mSyncedTracks == null) { isLocalTrackOnline(-1l); } mSyncedTracks.put(trackId, bcTrackId); setChanged(); notifyObservers(); } public void addTracksLoadingScheduled(Pair<Integer, Integer> item) { sScheduledTracksLoading.add(item); setChanged(); notifyObservers(); } /** * Cleans old bundles based a set of all bundles * * @param newBundleIds */ public void setAllBundleIds(Set<Integer> currentBundleIds) { Set<Integer> keySet = sBundlesWithTracks.keySet(); for (Integer oldBundleId : keySet) { if (!currentBundleIds.contains(oldBundleId)) { removeBundle(oldBundleId); } } } public void setAllTracksForBundleId(int mBundleId, Set<Integer> updatedbcTracksIdList) { List<Integer> trackIdList = sBundlesWithTracks.get(mBundleId); for (int location = 0; location < trackIdList.size(); location++) { Integer oldTrackId = trackIdList.get(location); if (!updatedbcTracksIdList.contains(oldTrackId)) { removeTrack(mBundleId, oldTrackId); } } setChanged(); notifyObservers(); } private void putForTrack(int trackId, String key, Object value) { if (value != null) { sTrackMappings.get(trackId).put(key, value.toString()); } setChanged(); notifyObservers(); } /** * Remove a bundle * * @param deletedId */ public void removeBundle(int deletedId) { sBundleMappings.remove(deletedId); sBundlesWithTracks.remove(deletedId); setChanged(); notifyObservers(); } /** * Remove a track * * @param deletedId */ public void removeTrack(int bundleId, int trackId) { sTrackMappings.remove(trackId); if (sBundlesWithTracks.get(bundleId) != null) { sBundlesWithTracks.get(bundleId).remove(trackId); } setChanged(); notifyObservers(); mResolver.delete(MetaData.CONTENT_URI, MetaData.TRACK + " = ? AND " + MetaData.KEY + " = ? ", new String[] { Integer.toString(trackId), TRACK_ID }); if (mSyncedTracks != null && mSyncedTracks.containsKey(trackId)) { mSyncedTracks.remove(trackId); } } public int positions() { int size = 0; for (int index = 0; index < sBundlesWithTracks.size(); index++) { // One row for the Bundle header size += 1; List<Integer> trackIds = sBundlesWithTracks.get(index); int bundleSize = trackIds != null ? trackIds.size() : 0; // One row per track in each bundle size += bundleSize; } return size; } public Integer getBundleIdForTrackId(int trackId) { for (Integer bundleId : sBundlesWithTracks.keySet()) { List<Integer> trackIds = sBundlesWithTracks.get(bundleId); if (trackIds.contains(trackId)) { return bundleId; } } return null; } /** * @param position list postition 0...n * @return a pair of a TYPE and an ID */ public Pair<Integer, Integer> getItemForPosition(int position) { int countdown = position; for (Integer bundleId : sBundlesWithTracks.keySet()) { if (countdown == 0) { return Pair.create(Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE, bundleId); } countdown--; int bundleSize = sBundlesWithTracks.get(bundleId) != null ? sBundlesWithTracks.get(bundleId).size() : 0; if (countdown < bundleSize) { Integer trackId = sBundlesWithTracks.get(bundleId).get(countdown); return Pair.create(Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE, trackId); } countdown -= bundleSize; } return null; } public String getValueForItem(Pair<Integer, Integer> item, String key) { String value = null; switch (item.first) { case Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE: value = sBundleMappings.get(item.second).get(key); break; case Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE: value = sTrackMappings.get(item.second).get(key); break; default: value = null; break; } return value; } public SpinnerAdapter getActivityAdapter(Context ctx) { List<String> activities = new Vector<String>(); for (Integer activityId : sActivityMappings.keySet()) { String name = sActivityMappings.get(activityId).get(NAME); name = name != null ? name : ""; activities.add(name); } Collections.sort(activities); ArrayAdapter<String> adapter = new ArrayAdapter<String>(ctx, android.R.layout.simple_spinner_item, activities); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); return adapter; } public SpinnerAdapter getBundleAdapter(Context ctx) { List<String> bundles = new Vector<String>(); for (Integer bundleId : sBundlesWithTracks.keySet()) { bundles.add(sBundleMappings.get(bundleId).get(NAME)); } Collections.sort(bundles); if (!bundles.contains(ctx.getString(R.string.app_name))) { bundles.add(ctx.getString(R.string.app_name)); } ArrayAdapter<String> adapter = new ArrayAdapter<String>(ctx, android.R.layout.simple_spinner_item, bundles); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); return adapter; } public static int getIdForActivity(String selectedItem) { if (selectedItem == null) { return -1; } for (Integer activityId : sActivityMappings.keySet()) { Map<String, String> mapping = sActivityMappings.get(activityId); if (mapping != null && selectedItem.equals(mapping.get(NAME))) { return activityId; } } return -1; } public static int getIdForBundle(int activityId, String selectedItem) { for (Integer bundleId : sBundlesWithTracks.keySet()) { if (selectedItem.equals(sBundleMappings.get(bundleId).get(NAME))) { return bundleId; } } return -1; } private boolean isLocalTrackOnline(Long qtrackId) { if (mSyncedTracks == null) { mSyncedTracks = new HashMap<Long, Integer>(); Cursor cursor = null; try { cursor = mResolver.query(MetaData.CONTENT_URI, new String[] { MetaData.TRACK, MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { TRACK_ID }, null); if (cursor.moveToFirst()) { do { Long trackId = cursor.getLong(0); try { Integer bcTrackId = Integer.valueOf(cursor.getString(1)); mSyncedTracks.put(trackId, bcTrackId); } catch (NumberFormatException e) { Log.w(TAG, "Illigal value stored as track id", e); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } setChanged(); notifyObservers(); } boolean synced = mSyncedTracks.containsKey(qtrackId); return synced; } public boolean isLocalTrackSynced(Long qtrackId) { boolean uploaded = isLocalTrackOnline(qtrackId); Integer trackId = mSyncedTracks.get(qtrackId); boolean synced = trackId != null && sTrackMappings.get(trackId) != null; return uploaded && synced; } public boolean areTracksLoaded(Pair<Integer, Integer> item) { return sBundlesWithTracks.get(item.second) != null && item.first == Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE; } public boolean areTracksLoadingScheduled(Pair<Integer, Integer> item) { return sScheduledTracksLoading.contains(item); } /** * Read the static breadcrumbs data from private file * * @param ctx * @return is refresh is needed */ @SuppressWarnings("unchecked") public boolean readCache(Context ctx) { FileInputStream fis = null; ObjectInputStream ois = null; Date bundlesPersisted = null, activitiesPersisted = null; Object[] cache; synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { try { fis = ctx.openFileInput(BREADCRUMSB_BUNDLES_CACHE_FILE); ois = new ObjectInputStream(fis); cache = (Object[]) ois.readObject(); // new Object[] { CACHE_VERSION, new Date(), sActivitiesWithBundles, sBundlesWithTracks, sBundleMappings, sTrackMappings }; if (cache[0] instanceof Integer && CACHE_VERSION.equals(cache[0])) { bundlesPersisted = (Date) cache[1]; HashMap<Integer, List<Integer>> bundles = (HashMap<Integer, List<Integer>>) cache[2]; HashMap<Integer, Map<String, String>> bundlemappings = (HashMap<Integer, Map<String, String>>) cache[3]; HashMap<Integer, Map<String, String>> trackmappings = (HashMap<Integer, Map<String, String>>) cache[4]; sBundlesWithTracks = bundles != null ? bundles : sBundlesWithTracks; sBundleMappings = bundlemappings != null ? bundlemappings : sBundleMappings; sTrackMappings = trackmappings != null ? trackmappings : sTrackMappings; } else { clearPersistentCache(ctx); } fis = ctx.openFileInput(BREADCRUMSB_ACTIVITY_CACHE_FILE); ois = new ObjectInputStream(fis); cache = (Object[]) ois.readObject(); // new Object[] { CACHE_VERSION, new Date(), sActivityMappings }; if (cache[0] instanceof Integer && CACHE_VERSION.equals(cache[0])) { activitiesPersisted = (Date) cache[1]; HashMap<Integer, Map<String, String>> activitymappings = (HashMap<Integer, Map<String, String>>) cache[2]; sActivityMappings = activitymappings != null ? activitymappings : sActivityMappings; } else { clearPersistentCache(ctx); } } catch (OptionalDataException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ClassNotFoundException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (IOException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ClassCastException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ArrayIndexOutOfBoundsException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { Log.w(TAG, "Error closing file stream after reading cache", e); } } if (ois != null) { try { ois.close(); } catch (IOException e) { Log.w(TAG, "Error closing object stream after reading cache", e); } } } } setChanged(); notifyObservers(); boolean refreshNeeded = false; refreshNeeded = refreshNeeded || bundlesPersisted == null || activitiesPersisted == null; refreshNeeded = refreshNeeded || (activitiesPersisted.getTime() < new Date().getTime() - CACHE_TIMEOUT * 10); refreshNeeded = refreshNeeded || (bundlesPersisted.getTime() < new Date().getTime() - CACHE_TIMEOUT); return refreshNeeded; } public void persistCache(Context ctx) { FileOutputStream fos = null; ObjectOutputStream oos = null; Object[] cache; synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { try { fos = ctx.openFileOutput(BREADCRUMSB_BUNDLES_CACHE_FILE, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); cache = new Object[] { CACHE_VERSION, new Date(), sBundlesWithTracks, sBundleMappings, sTrackMappings }; oos.writeObject(cache); fos = ctx.openFileOutput(BREADCRUMSB_ACTIVITY_CACHE_FILE, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); cache = new Object[] { CACHE_VERSION, new Date(), sActivityMappings }; oos.writeObject(cache); } catch (FileNotFoundException e) { Log.e(TAG, "Error in file stream during persist cache", e); } catch (IOException e) { Log.e(TAG, "Error in object stream during persist cache", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { Log.w(TAG, "Error closing file stream after writing cache", e); } } if (oos != null) { try { oos.close(); } catch (IOException e) { Log.w(TAG, "Error closing object stream after writing cache", e); } } } } } public void clearAllCache(Context ctx) { BreadcrumbsTracks.initCacheVariables(); setChanged(); clearPersistentCache(ctx); notifyObservers(); } public void clearPersistentCache(Context ctx) { Log.w(TAG, "Deleting old Breadcrumbs cache files"); synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { ctx.deleteFile(BREADCRUMSB_ACTIVITY_CACHE_FILE); ctx.deleteFile(BREADCRUMSB_BUNDLES_CACHE_FILE); } } @Override public String toString() { return "BreadcrumbsTracks [mActivityMappings=" + sActivityMappings + ", mBundleMappings=" + sBundleMappings + ", mTrackMappings=" + sTrackMappings + ", mActivities=" + sActivityMappings + ", mBundles=" + sBundlesWithTracks + "]"; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/adapter/BreadcrumbsTracks.java
Java
gpl3
23,924
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Mar 10, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.util; import nl.sogeti.android.gpstracker.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.View; /** * ???? * * @version $Id:$ * @author rene (c) Mar 10, 2012, Sogeti B.V. */ public class SlidingIndicatorView extends View { private static final String TAG = "OGT.SlidingIndicatorView"; private float mMinimum = 0; private float mMaximum = 100 ; private float mValue = 0; private Drawable mIndicator; private int mIntrinsicHeight; public SlidingIndicatorView(Context context) { super(context); } public SlidingIndicatorView(Context context, AttributeSet attrs) { super(context, attrs); } public SlidingIndicatorView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if( mIndicator == null ) { mIndicator = getResources().getDrawable(R.drawable.stip); mIntrinsicHeight = mIndicator.getIntrinsicHeight(); mIndicator.setBounds(0, 0, getWidth(), mIntrinsicHeight); } int height = getHeight(); float scale = Math.abs( mValue/(mMaximum-mMinimum) ); float y = height - height*scale; float translate = y-mIntrinsicHeight; canvas.save(); canvas.translate(0, translate); mIndicator.draw(canvas); canvas.restore(); } public float getMin() { return mMinimum; } public void setMin(float min) { if(mMaximum-mMinimum == 0 ) { Log.w(TAG, "Minimum and maximum difference must be greater then 0"); return; } this.mMinimum = min; } public float getMax() { return mMaximum; } public void setMax(float max) { if(mMaximum-mMinimum == 0 ) { Log.w(TAG, "Minimum and maximum difference must be greater then 0"); return; } this.mMaximum = max; } public float getValue() { return mValue; } public void setValue(float value) { this.mValue = value; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/util/SlidingIndicatorView.java
Java
gpl3
3,065
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import java.util.Locale; import nl.sogeti.android.gpstracker.R; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.Configuration; import android.content.res.Resources; import android.preference.PreferenceManager; import android.util.TypedValue; /** * Collection of methods to provide metric and imperial data based on locale or * overridden by configuration * * @version $Id$ * @author rene (c) Feb 2, 2010, Sogeti B.V. */ public class UnitsI18n { private Context mContext; private double mConversion_from_mps_to_speed; private double mConversion_from_meter_to_distance; private double mConversion_from_meter_to_height; private String mSpeed_unit; private String mDistance_unit; private String mHeight_unit; private UnitsChangeListener mListener; private OnSharedPreferenceChangeListener mPreferenceListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.UNITS)) { initBasedOnPreferences(sharedPreferences); if (mListener != null) { mListener.onUnitsChange(); } } } }; private boolean needsUnitFlip; private int mUnits; @SuppressWarnings("unused") private static final String TAG = "OGT.UnitsI18n"; public UnitsI18n(Context ctx, UnitsChangeListener listener) { this(ctx); mListener = listener; } public UnitsI18n(Context ctx) { mContext = ctx; initBasedOnPreferences(PreferenceManager.getDefaultSharedPreferences(mContext)); } private void initBasedOnPreferences(SharedPreferences sharedPreferences) { mUnits = Integer.parseInt(sharedPreferences.getString(Constants.UNITS, Integer.toString(Constants.UNITS_DEFAULT))); switch (mUnits) { case (Constants.UNITS_DEFAULT): setToDefault(); break; case (Constants.UNITS_IMPERIAL): setToImperial(); break; case (Constants.UNITS_METRIC): setToMetric(); break; case (Constants.UNITS_NAUTIC): setToMetric(); overrideWithNautic(mContext.getResources()); break; case (Constants.UNITS_METRICPACE): setToMetric(); overrideWithPace(mContext.getResources()); break; case (Constants.UNITS_IMPERIALPACE): setToImperial(); overrideWithPaceImperial(mContext.getResources()); break; case Constants.UNITS_IMPERIALSURFACE: setToImperial(); overrideWithSurfaceImperial(); break; case Constants.UNITS_METRICSURFACE: setToMetric(); overrideWithSurfaceMetric(); break; default: setToDefault(); break; } } private void setToDefault() { Resources resources = mContext.getResources(); init(resources); } private void setToMetric() { Resources resources = mContext.getResources(); Configuration config = resources.getConfiguration(); Locale oldLocale = config.locale; config.locale = new Locale(""); resources.updateConfiguration(config, resources.getDisplayMetrics()); init(resources); config.locale = oldLocale; resources.updateConfiguration(config, resources.getDisplayMetrics()); } private void setToImperial() { Resources resources = mContext.getResources(); Configuration config = resources.getConfiguration(); Locale oldLocale = config.locale; config.locale = Locale.US; resources.updateConfiguration(config, resources.getDisplayMetrics()); init(resources); config.locale = oldLocale; resources.updateConfiguration(config, resources.getDisplayMetrics()); } /** * Based on a given Locale prefetch the units conversions and names. * * @param resources Resources initialized with a Locale */ private void init(Resources resources) { TypedValue outValue = new TypedValue(); needsUnitFlip = false; resources.getValue(R.raw.conversion_from_mps, outValue, false); mConversion_from_mps_to_speed = outValue.getFloat(); resources.getValue(R.raw.conversion_from_meter, outValue, false); mConversion_from_meter_to_distance = outValue.getFloat(); resources.getValue(R.raw.conversion_from_meter_to_height, outValue, false); mConversion_from_meter_to_height = outValue.getFloat(); mSpeed_unit = resources.getString(R.string.speed_unitname); mDistance_unit = resources.getString(R.string.distance_unitname); mHeight_unit = resources.getString(R.string.distance_smallunitname); } private void overrideWithNautic(Resources resources) { TypedValue outValue = new TypedValue(); resources.getValue(R.raw.conversion_from_mps_to_knot, outValue, false); mConversion_from_mps_to_speed = outValue.getFloat(); resources.getValue(R.raw.conversion_from_meter_to_nauticmile, outValue, false); mConversion_from_meter_to_distance = outValue.getFloat(); mSpeed_unit = resources.getString(R.string.knot_unitname); mDistance_unit = resources.getString(R.string.nautic_unitname); } private void overrideWithPace(Resources resources) { needsUnitFlip = true; mSpeed_unit = resources.getString(R.string.pace_unitname); } private void overrideWithPaceImperial(Resources resources) { needsUnitFlip = true; mSpeed_unit = resources.getString(R.string.pace_unitname_imperial); } private void overrideWithSurfaceImperial() { float width = getWidthPreference(); Resources resources = mContext.getResources(); TypedValue outValue = new TypedValue(); resources.getValue(R.raw.conversion_from_mps_to_acres_hour, outValue, false); mConversion_from_mps_to_speed = outValue.getFloat() * width; mSpeed_unit = resources.getString(R.string.surface_unitname_imperial); } private float getWidthPreference() { return Float.parseFloat(PreferenceManager.getDefaultSharedPreferences(mContext).getString("units_implement_width", "12")); } private void overrideWithSurfaceMetric() { float width = getWidthPreference(); Resources resources = mContext.getResources(); TypedValue outValue = new TypedValue(); resources.getValue(R.raw.conversion_from_mps_to_hectare_hour, outValue, false); mConversion_from_mps_to_speed = outValue.getFloat() * width; mSpeed_unit = resources.getString(R.string.surface_unitname_metric); } public double conversionFromMeterAndMiliseconds(double meters, long miliseconds) { float seconds = miliseconds / 1000f; return conversionFromMetersPerSecond(meters / seconds); } public double conversionFromMetersPerSecond(double mps) { double speed = mps * mConversion_from_mps_to_speed; if (needsUnitFlip) // Flip from "x per hour" to "minutes per x" { if (speed > 1) // Nearly no speed return 0 as if there is no speed { speed = (1 / speed) * 60.0; } else { speed = 0; } } return speed; } public double conversionFromMeter(double meters) { double value = meters * mConversion_from_meter_to_distance; return value; } public double conversionFromLocalToMeters(double localizedValue) { double meters = localizedValue / mConversion_from_meter_to_distance; return meters; } public double conversionFromMeterToHeight(double meters) { return meters * mConversion_from_meter_to_height; } public String getSpeedUnit() { return mSpeed_unit; } public String getDistanceUnit() { return mDistance_unit; } public String getHeightUnit() { return mHeight_unit; } public boolean isUnitFlipped() { return needsUnitFlip; } public void setUnitsChangeListener(UnitsChangeListener unitsChangeListener) { mListener = unitsChangeListener; if( mListener != null ) { initBasedOnPreferences(PreferenceManager.getDefaultSharedPreferences(mContext)); PreferenceManager.getDefaultSharedPreferences(mContext).registerOnSharedPreferenceChangeListener(mPreferenceListener); } else { PreferenceManager.getDefaultSharedPreferences(mContext).unregisterOnSharedPreferenceChangeListener(mPreferenceListener); } } /** * Interface definition for a callback to be invoked when the preference for * units changed. * * @version $Id$ * @author rene (c) Feb 14, 2010, Sogeti B.V. */ public interface UnitsChangeListener { /** * Called when the unit data has changed. */ void onUnitsChange(); } /** * Format a speed using the current unit and flipping * * @param speed * @param decimals format a bit larger showing decimals or seconds * @return */ public String formatSpeed(double speed, boolean decimals) { String speedText; if(mUnits == Constants.UNITS_METRICPACE || mUnits == Constants.UNITS_IMPERIALPACE) { if( decimals ) { speedText = String.format( "%02d %s", (int)speed, this.getSpeedUnit() ); } else { speedText = String.format( "%02d:%02d %s", (int)speed, (int)((speed-(int)speed)*60), // convert decimal to seconds this.getSpeedUnit() ); } } else { if( decimals ) { speedText = String.format( "%.2f %s", speed, this.getSpeedUnit() ); } else { speedText = String.format( "%.0f %s", speed, this.getSpeedUnit() ); } } return speedText; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/util/UnitsI18n.java
Java
gpl3
11,781
/* * Copyright (C) 2009 The Android Open Source Project * * 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 nl.sogeti.android.gpstracker.util; /** * Container to ease passing around a tuple of two objects. This object provides a sensible * implementation of equals(), returning true if equals() is true on each of the contained * objects. */ public class Pair<F, S> { public final F first; public final S second; private String toStringOverride; /** * Constructor for a Pair. If either are null then equals() and hashCode() will throw * a NullPointerException. * @param first the first object in the Pair * @param second the second object in the pair */ public Pair(F first, S second) { this.first = first; this.second = second; } /** * Checks the two objects for equality by delegating to their respective equals() methods. * @param o the Pair to which this one is to be checked for equality * @return true if the underlying objects of the Pair are both considered equals() */ @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Pair)) return false; final Pair<F, S> other; try { other = (Pair<F, S>) o; } catch (ClassCastException e) { return false; } return first.equals(other.first) && second.equals(other.second); } /** * Compute a hash code using the hash codes of the underlying objects * @return a hashcode of the Pair */ @Override public int hashCode() { int result = 17; result = 31 * result + first.hashCode(); result = 31 * result + second.hashCode(); return result; } /** * Convenience method for creating an appropriately typed pair. * @param a the first object in the Pair * @param b the second object in the pair * @return a Pair that is templatized with the types of a and b */ public static <A, B> Pair <A, B> create(A a, B b) { return new Pair<A, B>(a, b); } public void overrideToString(String toStringOverride) { this.toStringOverride = toStringOverride; } @Override public String toString() { if( toStringOverride == null ) { return super.toString(); } else { return toStringOverride; } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/util/Pair.java
Java
gpl3
2,988
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import java.text.DateFormat; import java.util.Date; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; /** * An implementation for the XML element DateView that alters the textview in the * formating of the text when displaying a date in ms from 1970. * * @version $Id$ * @author rene (c) Jan 22, 2009, Sogeti B.V. */ public class DateView extends TextView { private Date mDate; /** * Constructor: create a new DateView. * @param context */ public DateView(Context context) { super( context ); } /** * Constructor: create a new DateView. * @param context * @param attrs */ public DateView(Context context, AttributeSet attrs) { super( context, attrs ); } /** * Constructor: create a new DateView. * @param context * @param attrs * @param defStyle */ public DateView(Context context, AttributeSet attrs, int defStyle) { super( context, attrs, defStyle ); } /* * (non-Javadoc) * @see android.widget.TextView#setText(java.lang.CharSequence, android.widget.TextView.BufferType) */ @Override public void setText( CharSequence charSeq, BufferType type ) { // Behavior for the graphical editor if( this.isInEditMode() ) { super.setText( charSeq, type ); return; } long longVal; if( charSeq.length() == 0 ) { longVal = 0l ; } else { try { longVal = Long.parseLong(charSeq.toString()) ; } catch(NumberFormatException e) { longVal = 0l; } } this.mDate = new Date( longVal ); DateFormat dateFormat = android.text.format.DateFormat.getLongDateFormat(this.getContext().getApplicationContext()); DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(this.getContext().getApplicationContext()); String text = timeFormat.format(this.mDate) + " " + dateFormat.format(mDate); super.setText( text, type ); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/util/DateView.java
Java
gpl3
3,692
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import nl.sogeti.android.gpstracker.actions.tasks.GpxParser; import nl.sogeti.android.gpstracker.actions.tasks.GpxParser.ProgressAdmin; /** * ???? * * @version $Id$ * @author rene (c) Dec 11, 2010, Sogeti B.V. */ public class ProgressFilterInputStream extends FilterInputStream { GpxParser mAsyncTask; long progress = 0; private ProgressAdmin mProgressAdmin; public ProgressFilterInputStream(InputStream is, ProgressAdmin progressAdmin) { super( is ); mProgressAdmin = progressAdmin; } @Override public int read() throws IOException { int read = super.read(); incrementProgressBy( 1 ); return read; } @Override public int read( byte[] buffer, int offset, int count ) throws IOException { int read = super.read( buffer, offset, count ); incrementProgressBy( read ); return read; } private void incrementProgressBy( int bytes ) { if( bytes > 0 ) { mProgressAdmin.addBytesProgress(bytes); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/util/ProgressFilterInputStream.java
Java
gpl3
2,694
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import nl.sogeti.android.gpstracker.logger.GPSLoggerService; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; public class DockReceiver extends BroadcastReceiver { private final static String TAG = "OGT.DockReceiver"; @Override public void onReceive( Context context, Intent intent ) { String action = intent.getAction(); if( action.equals( Intent.ACTION_DOCK_EVENT ) ) { Bundle extras = intent.getExtras(); boolean start = false; boolean stop = false; if( extras != null && extras.containsKey(Intent.EXTRA_DOCK_STATE ) ) { int dockstate = extras.getInt(Intent.EXTRA_DOCK_STATE, -1); if( dockstate == Intent.EXTRA_DOCK_STATE_CAR ) { start = PreferenceManager.getDefaultSharedPreferences( context ).getBoolean( Constants.LOGATDOCK, false ); } else if( dockstate == Intent.EXTRA_DOCK_STATE_UNDOCKED ) { stop = PreferenceManager.getDefaultSharedPreferences( context ).getBoolean( Constants.STOPATUNDOCK, false ); } } if( start ) { Intent serviceIntent = new Intent( Constants.SERVICENAME ); serviceIntent.putExtra(GPSLoggerService.COMMAND, GPSLoggerService.EXTRA_COMMAND_START); context.startService( serviceIntent ); } else if( stop ) { Intent serviceIntent = new Intent( Constants.SERVICENAME ); serviceIntent.putExtra(GPSLoggerService.COMMAND, GPSLoggerService.EXTRA_COMMAND_STOP); context.startService( serviceIntent ); } } else { Log.w( TAG, "OpenGPSTracker's BootReceiver received " + action + ", but it's only able to respond to " + Intent.ACTION_BOOT_COMPLETED + ". This shouldn't happen !" ); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/util/DockReceiver.java
Java
gpl3
3,584
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import java.io.File; import nl.sogeti.android.gpstracker.db.GPStracking; import android.content.Context; import android.net.Uri; import android.os.Environment; import android.preference.PreferenceManager; /** * Various application wide constants * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class Constants { public static final String DISABLEBLANKING = "disableblanking"; public static final String DISABLEDIMMING = "disabledimming"; public static final String SATELLITE = "SATELLITE"; public static final String TRAFFIC = "TRAFFIC"; public static final String SPEED = "showspeed"; public static final String ALTITUDE = "showaltitude"; public static final String DISTANCE = "showdistance"; public static final String COMPASS = "COMPASS"; public static final String LOCATION = "LOCATION"; public static final String MAPPROVIDER = "mapprovider"; public static final String TRACKCOLORING = "trackcoloring"; public static final String SPEEDSANITYCHECK = "speedsanitycheck"; public static final String PRECISION = "precision"; public static final String LOGATSTARTUP = "logatstartup"; public static final String STARTUPATBOOT = "startupatboot"; public static final String LOGATDOCK = "logatdock"; public static final String STOPATUNDOCK = "stopatundock"; public static final String SERVICENAME = "nl.sogeti.android.gpstracker.intent.action.GPSLoggerService"; public static final String STREAMBROADCAST = "nl.sogeti.android.gpstracker.intent.action.STREAMBROADCAST"; public static final String UNITS = "units"; public static final int UNITS_DEFAULT = 0; public static final int UNITS_IMPERIAL = 1; public static final int UNITS_METRIC = 2; public static final int UNITS_NAUTIC = 3; public static final int UNITS_METRICPACE = 4; public static final int UNITS_IMPERIALPACE = 5; public static final int UNITS_IMPERIALSURFACE = 6; public static final int UNITS_METRICSURFACE = 7; public static final String SDDIR_DIR = "SDDIR_DIR"; public static final String DEFAULT_EXTERNAL_DIR = "/OpenGPSTracker/"; public static final String TMPICTUREFILE_SUBPATH = "media_tmp.tmp"; public static final Uri NAME_URI = Uri.parse( "content://" + GPStracking.AUTHORITY+".string" ); public static final int GOOGLE = 0; public static final int OSM = 1; public static final int MAPQUEST = 2; public static final String JOGRUNNER_AUTH = "JOGRUNNER_AUTH"; public static final String EXPORT_TYPE = "SHARE_TYPE"; public static final String EXPORT_GPXTARGET = "EXPORT_GPXTARGET"; public static final String EXPORT_KMZTARGET = "EXPORT_KMZTARGET"; public static final String EXPORT_TXTTARGET = "EXPORT_TXTTARGET"; public static final double MIN_STATISTICS_SPEED = 1.0d; public static final int OSM_CLOUDMADE = 0; public static final int OSM_MAKNIK = 1; public static final int OSM_CYCLE = 2; public static final String OSMBASEOVERLAY = "OSM_BASE_OVERLAY"; public static final String LOGGING_INTERVAL = "customprecisiontime"; public static final String LOGGING_DISTANCE = "customprecisiondistance"; public static final String STATUS_MONITOR = "gpsstatusmonitor"; public static final String OSM_USERNAME = "OSM_USERNAME"; public static final String OSM_PASSWORD = "OSM_PASSWORD"; public static final String OSM_VISIBILITY = "OSM_VISIBILITY"; public static final String DATASOURCES_KEY = "DATASOURCES"; /** * Broadcast intent action indicating that the logger service state has * changed. Includes the logging state and its precision. * * @see #EXTRA_LOGGING_PRECISION * @see #EXTRA_LOGGING_STATE */ public static final String LOGGING_STATE_CHANGED_ACTION = "nl.sogeti.android.gpstracker.LOGGING_STATE_CHANGED"; /** * The precision the service is logging on. * * @see #LOGGING_FINE * @see #LOGGING_NORMAL * @see #LOGGING_COARSE * @see #LOGGING_GLOBAL * @see #LOGGING_CUSTOM * */ public static final String EXTRA_LOGGING_PRECISION = "nl.sogeti.android.gpstracker.EXTRA_LOGGING_PRECISION"; /** * The state the service is. * * @see #UNKNOWN * @see #LOGGING * @see #PAUSED * @see #STOPPED */ public static final String EXTRA_LOGGING_STATE = "nl.sogeti.android.gpstracker.EXTRA_LOGGING_STATE"; /** * The state of the service is unknown */ public static final int UNKNOWN = -1; /** * The service is actively logging, it has requested location update from the location provider. */ public static final int LOGGING = 1; /** * The service is not active, but can be resumed to become active and store location changes as * part of a new segment of the current track. */ public static final int PAUSED = 2; /** * The service is not active and can not resume a current track but must start a new one when becoming active. */ public static final int STOPPED = 3; /** * The precision of the GPS provider is based on the custom time interval and distance. */ public static final int LOGGING_CUSTOM = 0; /** * The GPS location provider is asked to update every 10 seconds or every 5 meters. */ public static final int LOGGING_FINE = 1; /** * The GPS location provider is asked to update every 15 seconds or every 10 meters. */ public static final int LOGGING_NORMAL = 2; /** * The GPS location provider is asked to update every 30 seconds or every 25 meters. */ public static final int LOGGING_COARSE = 3; /** * The radio location provider is asked to update every 5 minutes or every 500 meters. */ public static final int LOGGING_GLOBAL = 4; public static final String REQUEST_URL = "http://api.gobreadcrumbs.com/oauth/request_token"; public static final String ACCESS_URL = "http://api.gobreadcrumbs.com/oauth/access_token"; public static final String AUTHORIZE_URL = "http://api.gobreadcrumbs.com/oauth/authorize"; public static final String OSM_REQUEST_URL = "http://www.openstreetmap.org/oauth/request_token"; public static final String OSM_ACCESS_URL = "http://www.openstreetmap.org/oauth/access_token"; public static final String OSM_AUTHORIZE_URL = "http://www.openstreetmap.org/oauth/authorize"; public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-opengpstracker"; public static final String OAUTH_CALLBACK_HOST = "callback"; public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST; public static final String NAME = "NAME"; /** * Based on preference return the SD-Card directory in which Open GPS Tracker creates and stores files * shared tracks, * * @param ctx * @return */ public static String getSdCardDirectory( Context ctx ) { // Read preference and ensure start and end with '/' symbol String dir = PreferenceManager.getDefaultSharedPreferences(ctx).getString(SDDIR_DIR, DEFAULT_EXTERNAL_DIR); if( !dir.startsWith("/") ) { dir = "/" + dir; } if( !dir.endsWith("/") ) { dir = dir + "/" ; } dir = Environment.getExternalStorageDirectory().getAbsolutePath() + dir; // If neither exists or can be created fall back to default File dirHandle = new File(dir); if( !dirHandle.exists() && !dirHandle.mkdirs() ) { dir = Environment.getExternalStorageDirectory().getAbsolutePath() + DEFAULT_EXTERNAL_DIR; } return dir; } public static String getSdCardTmpFile( Context ctx ) { String dir = getSdCardDirectory( ctx ) + TMPICTUREFILE_SUBPATH; return dir; } public static final String BREADCRUMBS_CONNECT = "breadcrumbs_connect"; public static final int BREADCRUMBS_CONNECT_ITEM_VIEW_TYPE = 0; public static final int BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE = 2; public static final int BREADCRUMBS_TRACK_ITEM_VIEW_TYPE = 3; public static final int BREADCRUMBS_ACTIVITY_ITEM_VIEW_TYPE = 4; public static final int SECTIONED_HEADER_ITEM_VIEW_TYPE = 0; public static final String BROADCAST_STREAM = "STREAM_ENABLED"; /** * A distance in meters */ public static final String EXTRA_DISTANCE = "nl.sogeti.android.gpstracker.EXTRA_DISTANCE"; /** * A time period in minutes */ public static final String EXTRA_TIME = "nl.sogeti.android.gpstracker.EXTRA_TIME"; /** * The location that pushed beyond the set minimum time or distance */ public static final String EXTRA_LOCATION = "nl.sogeti.android.gpstracker.EXTRA_LOCATION"; /** * The track that is being logged */ public static final String EXTRA_TRACK = "nl.sogeti.android.gpstracker.EXTRA_TRACK"; }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/util/Constants.java
Java
gpl3
10,472
/* * Written by Tom van Braeckel @ http://code.google.com/u/tomvanbraeckel/ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.util; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.preference.PreferenceManager; import android.util.Log; public class BootReceiver extends BroadcastReceiver { private final static String TAG = "OGT.BootReceiver"; @Override public void onReceive( Context context, Intent intent ) { // Log.d( TAG, "BootReceiver.onReceive(), probably ACTION_BOOT_COMPLETED" ); String action = intent.getAction(); // start on BOOT_COMPLETED if( action.equals( Intent.ACTION_BOOT_COMPLETED ) ) { // Log.d( TAG, "BootReceiver received ACTION_BOOT_COMPLETED" ); // check in the settings if we need to auto start boolean startImmidiatly = PreferenceManager.getDefaultSharedPreferences( context ).getBoolean( Constants.STARTUPATBOOT, false ); if( startImmidiatly ) { // Log.d( TAG, "Starting LoggerMap activity..." ); context.startService( new Intent( Constants.SERVICENAME ) ); } else { Log.i( TAG, "Not starting Logger Service. Adjust the settings if you wanted this !" ); } } else { // this shouldn't happen ! Log.w( TAG, "OpenGPSTracker's BootReceiver received " + action + ", but it's only able to respond to " + Intent.ACTION_BOOT_COMPLETED + ". This shouldn't happen !" ); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/util/BootReceiver.java
Java
gpl3
2,288
/* Copyright (c) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.sogeti.android.gpstracker.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PushbackInputStream; import java.io.Reader; public class UnicodeReader extends Reader { private static final int BOM_SIZE = 4; private final InputStreamReader reader; /** * Construct UnicodeReader * * @param in Input stream. * @param defaultEncoding Default encoding to be used if BOM is not found, or <code>null</code> to use system default encoding. * @throws IOException If an I/O error occurs. */ public UnicodeReader(InputStream in, String defaultEncoding) throws IOException { byte bom[] = new byte[BOM_SIZE]; String encoding; int unread; PushbackInputStream pushbackStream = new PushbackInputStream( in, BOM_SIZE ); int n = pushbackStream.read( bom, 0, bom.length ); // Read ahead four bytes and check for BOM marks. if( ( bom[0] == (byte) 0xEF ) && ( bom[1] == (byte) 0xBB ) && ( bom[2] == (byte) 0xBF ) ) { encoding = "UTF-8"; unread = n - 3; } else if( ( bom[0] == (byte) 0xFE ) && ( bom[1] == (byte) 0xFF ) ) { encoding = "UTF-16BE"; unread = n - 2; } else if( ( bom[0] == (byte) 0xFF ) && ( bom[1] == (byte) 0xFE ) ) { encoding = "UTF-16LE"; unread = n - 2; } else if( ( bom[0] == (byte) 0x00 ) && ( bom[1] == (byte) 0x00 ) && ( bom[2] == (byte) 0xFE ) && ( bom[3] == (byte) 0xFF ) ) { encoding = "UTF-32BE"; unread = n - 4; } else if( ( bom[0] == (byte) 0xFF ) && ( bom[1] == (byte) 0xFE ) && ( bom[2] == (byte) 0x00 ) && ( bom[3] == (byte) 0x00 ) ) { encoding = "UTF-32LE"; unread = n - 4; } else { encoding = defaultEncoding; unread = n; } // Unread bytes if necessary and skip BOM marks. if( unread > 0 ) { pushbackStream.unread( bom, ( n - unread ), unread ); } else if( unread < -1 ) { pushbackStream.unread( bom, 0, 0 ); } // Use given encoding. if( encoding == null ) { reader = new InputStreamReader( pushbackStream ); } else { reader = new InputStreamReader( pushbackStream, encoding ); } } public String getEncoding() { return reader.getEncoding(); } @Override public int read( char[] cbuf, int off, int len ) throws IOException { return reader.read( cbuf, off, len ); } @Override public void close() throws IOException { reader.close(); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/util/UnicodeReader.java
Java
gpl3
3,284
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.GpxCreator; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpPost; import org.apache.ogt.http.entity.mime.HttpMultipartMode; import org.apache.ogt.http.entity.mime.MultipartEntity; import org.apache.ogt.http.entity.mime.content.FileBody; import org.apache.ogt.http.entity.mime.content.StringBody; import org.apache.ogt.http.util.EntityUtils; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class UploadBreadcrumbsTrackTask extends GpxCreator { final String TAG = "OGT.UploadBreadcrumbsTrackTask"; private BreadcrumbsService mService; private OAuthConsumer mConsumer; private HttpClient mHttpClient; private String mActivityId; private String mBundleId; private String mDescription; private String mIsPublic; private String mBundleName; private String mBundleDescription; private boolean mIsBundleCreated; private List<File> mPhotoUploadQueue; /** * Constructor: create a new UploadBreadcrumbsTrackTask. * * @param context * @param adapter * @param listener * @param httpclient * @param consumer * @param trackUri * @param name */ public UploadBreadcrumbsTrackTask(Context context, BreadcrumbsService adapter, ProgressListener listener, HttpClient httpclient, OAuthConsumer consumer, Uri trackUri, String name) { super(context, trackUri, name, true, listener); mService = adapter; mHttpClient = httpclient; mConsumer = consumer; mPhotoUploadQueue = new LinkedList<File>(); } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Uri doInBackground(Void... params) { // Leave room in the progressbar for uploading determineProgressGoal(); mProgressAdmin.setUpload(true); // Build GPX file Uri gpxFile = exportGpx(); if (isCancelled()) { String text = mContext.getString(R.string.ticker_failed) + " \"http://api.gobreadcrumbs.com/v1/tracks\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Fail to execute request due to canceling"), text); } // Collect GPX Import option params mActivityId = null; mBundleId = null; mDescription = null; mIsPublic = null; Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); Cursor cursor = null; try { cursor = mContext.getContentResolver().query(metadataUri, new String[] { MetaData.KEY, MetaData.VALUE }, null, null, null); if (cursor.moveToFirst()) { do { String key = cursor.getString(0); if (BreadcrumbsTracks.ACTIVITY_ID.equals(key)) { mActivityId = cursor.getString(1); } else if (BreadcrumbsTracks.BUNDLE_ID.equals(key)) { mBundleId = cursor.getString(1); } else if (BreadcrumbsTracks.DESCRIPTION.equals(key)) { mDescription = cursor.getString(1); } else if (BreadcrumbsTracks.ISPUBLIC.equals(key)) { mIsPublic = cursor.getString(1); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } if ("-1".equals(mActivityId)) { String text = "Unable to upload without a activity id stored in meta-data table"; IllegalStateException e = new IllegalStateException(text); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, text); } int statusCode = 0; String responseText = null; Uri trackUri = null; HttpEntity responseEntity = null; try { if ("-1".equals(mBundleId)) { mBundleDescription = "";//mContext.getString(R.string.breadcrumbs_bundledescription); mBundleName = mContext.getString(R.string.app_name); mBundleId = createOpenGpsTrackerBundle(); } String gpxString = XmlCreator.convertStreamToString(mContext.getContentResolver().openInputStream(gpxFile)); HttpPost method = new HttpPost("http://api.gobreadcrumbs.com:80/v1/tracks"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } // Build the multipart body with the upload data MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("import_type", new StringBody("GPX")); //entity.addPart("gpx", new FileBody(gpxFile)); entity.addPart("gpx", new StringBody(gpxString)); entity.addPart("bundle_id", new StringBody(mBundleId)); entity.addPart("activity_id", new StringBody(mActivityId)); entity.addPart("description", new StringBody(mDescription)); // entity.addPart("difficulty", new StringBody("3")); // entity.addPart("rating", new StringBody("4")); entity.addPart("public", new StringBody(mIsPublic)); method.setEntity(entity); // Execute the POST to OpenStreetMap mConsumer.sign(method); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "HTTP Method "+method.getMethod() ); Log.d( TAG, "URI scheme "+method.getURI().getScheme() ); Log.d( TAG, "Host name "+method.getURI().getHost() ); Log.d( TAG, "Port "+method.getURI().getPort() ); Log.d( TAG, "Request path "+method.getURI().getPath()); Log.d( TAG, "Consumer Key: "+mConsumer.getConsumerKey()); Log.d( TAG, "Consumer Secret: "+mConsumer.getConsumerSecret()); Log.d( TAG, "Token: "+mConsumer.getToken()); Log.d( TAG, "Token Secret: "+mConsumer.getTokenSecret()); Log.d( TAG, "Execute request: "+method.getURI() ); for( Header header : method.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpClient.execute(method); mProgressAdmin.addUploadProgress(); statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); responseText = XmlCreator.convertStreamToString(stream); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Upload Response: "+responseText); } Pattern p = Pattern.compile(">([0-9]+)</id>"); Matcher m = p.matcher(responseText); if (m.find()) { Integer trackId = Integer.valueOf(m.group(1)); trackUri = Uri.parse("http://api.gobreadcrumbs.com/v1/tracks/" + trackId + "/placemarks.gpx"); for( File photo :mPhotoUploadQueue ) { uploadPhoto(photo, trackId); } } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "A problem during communication"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } if (statusCode == 200 || statusCode == 201) { if (trackUri == null) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Unable to retrieve URI from response"), responseText); } } else { //mAdapter.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Status code: " + statusCode), responseText); } return trackUri; } private String createOpenGpsTrackerBundle() throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException { HttpPost method = new HttpPost("http://api.gobreadcrumbs.com/v1/bundles.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("name", new StringBody(mBundleName)); entity.addPart("activity_id", new StringBody(mActivityId)); entity.addPart("description", new StringBody(mBundleDescription)); method.setEntity(entity); mConsumer.sign(method); HttpResponse response = mHttpClient.execute(method); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); String responseText = XmlCreator.convertStreamToString(stream); Pattern p = Pattern.compile(">([0-9]+)</id>"); Matcher m = p.matcher(responseText); String bundleId = null; if (m.find()) { bundleId = m.group(1); ContentValues values = new ContentValues(); values.put(MetaData.KEY, BreadcrumbsTracks.BUNDLE_ID); values.put(MetaData.VALUE, bundleId); Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); mContext.getContentResolver().insert(metadataUri, values); mIsBundleCreated = true; } else { String text = "Unable to upload (yet) without a bunld id stored in meta-data table"; IllegalStateException e = new IllegalStateException(text); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, text); } return bundleId; } /** * Queue's media * * @param inputFilePath * @return file path relative to the export dir * @throws IOException */ @Override protected String includeMediaFile(String inputFilePath) throws IOException { File source = new File(inputFilePath); if (source.exists()) { mProgressAdmin.setPhotoUpload(source.length()); mPhotoUploadQueue.add(source); } return source.getName(); } private void uploadPhoto(File photo, Integer trackId) throws IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException { HttpPost request = new HttpPost("http://api.gobreadcrumbs.com/v1/photos.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("name", new StringBody(photo.getName())); entity.addPart("track_id", new StringBody(Integer.toString(trackId))); //entity.addPart("description", new StringBody("")); entity.addPart("file", new FileBody(photo)); request.setEntity(entity); mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpClient.execute(request); HttpEntity responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); String responseText = XmlCreator.convertStreamToString(stream); mProgressAdmin.addPhotoUploadProgress(photo.length()); Log.i( TAG, "Uploaded photo "+responseText); } @Override protected void onPostExecute(Uri result) { BreadcrumbsTracks tracks = mService.getBreadcrumbsTracks(); Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); List<String> segments = result.getPathSegments(); Integer bcTrackId = Integer.valueOf(segments.get(segments.size() - 2)); ArrayList<ContentValues> metaValues = new ArrayList<ContentValues>(); metaValues.add(buildContentValues(BreadcrumbsTracks.TRACK_ID, Long.toString(bcTrackId))); if (mDescription != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.DESCRIPTION, mDescription)); } if (mIsPublic != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.ISPUBLIC, mIsPublic)); } metaValues.add(buildContentValues(BreadcrumbsTracks.BUNDLE_ID, mBundleId)); metaValues.add(buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, mActivityId)); // Store in OGT provider ContentResolver resolver = mContext.getContentResolver(); resolver.bulkInsert(metadataUri, metaValues.toArray(new ContentValues[1])); // Store in Breadcrumbs adapter tracks.addSyncedTrack(Long.valueOf(mTrackUri.getLastPathSegment()), bcTrackId); if( mIsBundleCreated ) { mService.getBreadcrumbsTracks().addBundle(Integer.parseInt(mBundleId), mBundleName, mBundleDescription); } //"http://api.gobreadcrumbs.com/v1/tracks/" + trackId + "/placemarks.gpx" mService.getBreadcrumbsTracks().addTrack(bcTrackId, mName, Integer.valueOf(mBundleId), mDescription, null, null, null, mIsPublic, null, null, null, null, null); super.onPostExecute(result); } private ContentValues buildContentValues(String key, String value) { ContentValues contentValues = new ContentValues(); contentValues.put(MetaData.KEY, key); contentValues.put(MetaData.VALUE, value); return contentValues; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/UploadBreadcrumbsTrackTask.java
Java
gpl3
17,596
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.GpxParser; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.util.Pair; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class DownloadBreadcrumbsTrackTask extends GpxParser { final String TAG = "OGT.GetBreadcrumbsTracksTask"; private BreadcrumbsService mAdapter; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpclient; private Pair<Integer, Integer> mTrack; /** * * Constructor: create a new DownloadBreadcrumbsTrackTask. * @param context * @param progressListener * @param adapter * @param httpclient * @param consumer * @param track */ public DownloadBreadcrumbsTrackTask(Context context, ProgressListener progressListener, BreadcrumbsService adapter, DefaultHttpClient httpclient, OAuthConsumer consumer, Pair<Integer, Integer> track) { super(context, progressListener); mAdapter = adapter; mHttpclient = httpclient; mConsumer = consumer; mTrack = track; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Uri doInBackground(Uri... params) { determineProgressGoal(null); Uri trackUri = null; String trackName = mAdapter.getBreadcrumbsTracks().getValueForItem(mTrack, BreadcrumbsTracks.NAME); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/tracks/" + mTrack.second + "/placemarks.gpx"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } trackUri = importTrack(stream, trackName); } catch (OAuthMessageSignerException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (OAuthExpectationFailedException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (OAuthCommunicationException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } catch (IOException e) { handleError(e, mContext.getString(R.string.error_importgpx_xml)); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e( TAG, "Failed to close the content stream", e); } } } return trackUri; } @Override protected void onPostExecute(Uri result) { super.onPostExecute(result); long ogtTrackId = Long.parseLong(result.getLastPathSegment()); Uri metadataUri = Uri.withAppendedPath(ContentUris.withAppendedId(Tracks.CONTENT_URI, ogtTrackId), "metadata"); BreadcrumbsTracks tracks = mAdapter.getBreadcrumbsTracks(); Integer bcTrackId = mTrack.second; Integer bcBundleId = tracks.getBundleIdForTrackId(bcTrackId); //TODO Integer bcActivityId = tracks.getActivityIdForBundleId(bcBundleId); String bcDifficulty = tracks.getValueForItem(mTrack, BreadcrumbsTracks.DIFFICULTY); String bcRating = tracks.getValueForItem(mTrack, BreadcrumbsTracks.RATING); String bcPublic = tracks.getValueForItem(mTrack, BreadcrumbsTracks.ISPUBLIC); String bcDescription = tracks.getValueForItem(mTrack, BreadcrumbsTracks.DESCRIPTION); ArrayList<ContentValues> metaValues = new ArrayList<ContentValues>(); if (bcTrackId != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.TRACK_ID, Long.toString(bcTrackId))); } if (bcDescription != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.DESCRIPTION, bcDescription)); } if (bcDifficulty != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.DIFFICULTY, bcDifficulty)); } if (bcRating != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.RATING, bcRating)); } if (bcPublic != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.ISPUBLIC, bcPublic)); } if (bcBundleId != null) { metaValues.add(buildContentValues(BreadcrumbsTracks.BUNDLE_ID, Integer.toString(bcBundleId))); } // if (bcActivityId != null) // { // metaValues.add(buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, Integer.toString(bcActivityId))); // } ContentResolver resolver = mContext.getContentResolver(); resolver.bulkInsert(metadataUri, metaValues.toArray(new ContentValues[1])); tracks.addSyncedTrack(ogtTrackId, mTrack.second); } private ContentValues buildContentValues(String key, String value) { ContentValues contentValues = new ContentValues(); contentValues.put(MetaData.KEY, key); contentValues.put(MetaData.VALUE, value); return contentValues; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/DownloadBreadcrumbsTrackTask.java
Java
gpl3
8,737
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.util.Pair; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.Context; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class GetBreadcrumbsActivitiesTask extends BreadcrumbsTask { private LinkedList<Pair<Integer, String>> mActivities; final String TAG = "OGT.GetBreadcrumbsActivitiesTask"; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpClient; /** * We pass the OAuth consumer and provider. * * @param mContext Required to be able to start the intent to launch the * browser. * @param httpclient * @param provider The OAuthProvider object * @param mConsumer The OAuthConsumer object */ public GetBreadcrumbsActivitiesTask(Context context, BreadcrumbsService adapter, ProgressListener listener, DefaultHttpClient httpclient, OAuthConsumer consumer) { super(context, adapter, listener); mHttpClient = httpclient; mConsumer = consumer; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Void doInBackground(Void... params) { mActivities = new LinkedList<Pair<Integer,String>>(); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/activities.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpClient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String activityName = null; Integer activityId = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("activity".equals(xpp.getName()) && activityId != null && activityName != null) { mActivities.add(new Pair<Integer, String>(activityId, activityName)); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("id".equals(tagName)) { activityId = Integer.parseInt(xpp.getText()); } else if ("name".equals(tagName)) { activityName = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "A problem while reading the XML data"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } return null; } @Override protected void updateTracksData( BreadcrumbsTracks tracks ) { for( Pair<Integer, String> activity : mActivities ) { tracks.addActivity(activity.first, activity.second); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/GetBreadcrumbsActivitiesTask.java
Java
gpl3
7,926
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) May 29, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.util.concurrent.Executor; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import android.annotation.TargetApi; import android.content.Context; import android.os.AsyncTask; import android.os.Build; import android.util.Log; /** * ???? * * @version $Id:$ * @author rene (c) May 29, 2011, Sogeti B.V. */ public abstract class BreadcrumbsTask extends AsyncTask<Void, Void, Void> { private static final String TAG = "OGT.BreadcrumbsTask"; private ProgressListener mListener; private String mErrorText; private Exception mException; protected BreadcrumbsService mService; private String mTask; protected Context mContext; public BreadcrumbsTask(Context context, BreadcrumbsService adapter, ProgressListener listener) { mContext = context; mListener = listener; mService = adapter; } @TargetApi(11) public void executeOn(Executor executor) { if (Build.VERSION.SDK_INT >= 11) { executeOnExecutor(executor); } else { execute(); } } protected void handleError(String task, Exception e, String text) { Log.e(TAG, "Received error will cancel background task " + this.getClass().getName(), e); mService.removeAuthentication(); mTask = task; mException = e; mErrorText = text; cancel(true); } @Override protected void onPreExecute() { if (mListener != null) { mListener.setIndeterminate(true); mListener.started(); } } @Override protected void onPostExecute(Void result) { this.updateTracksData(mService.getBreadcrumbsTracks()); if (mListener != null) { mListener.finished(null); } } protected abstract void updateTracksData(BreadcrumbsTracks tracks); @Override protected void onCancelled() { if (mListener != null) { mListener.finished(null); } if (mListener != null && mErrorText != null && mException != null) { mListener.showError(mTask, mErrorText, mException); } else if (mException != null) { Log.e(TAG, "Incomplete error after cancellation:" + mErrorText, mException); } else { Log.e(TAG, "Incomplete error after cancellation:" + mErrorText); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/BreadcrumbsTask.java
Java
gpl3
3,932
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OptionalDataException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Set; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.util.Log; /** * Model containing agregrated data retrieved from the GoBreadcrumbs.com API * * @version $Id:$ * @author rene (c) May 9, 2011, Sogeti B.V. */ public class BreadcrumbsTracks extends Observable { public static final String DESCRIPTION = "DESCRIPTION"; public static final String NAME = "NAME"; public static final String ENDTIME = "ENDTIME"; public static final String TRACK_ID = "BREADCRUMBS_TRACK_ID"; public static final String BUNDLE_ID = "BREADCRUMBS_BUNDLE_ID"; public static final String ACTIVITY_ID = "BREADCRUMBS_ACTIVITY_ID"; public static final String DIFFICULTY = "DIFFICULTY"; public static final String STARTTIME = "STARTTIME"; public static final String ISPUBLIC = "ISPUBLIC"; public static final String RATING = "RATING"; public static final String LATITUDE = "LATITUDE"; public static final String LONGITUDE = "LONGITUDE"; public static final String TOTALDISTANCE = "TOTALDISTANCE"; public static final String TOTALTIME = "TOTALTIME"; private static final String TAG = "OGT.BreadcrumbsTracks"; private static final Integer CACHE_VERSION = Integer.valueOf(3); private static final String BREADCRUMSB_BUNDLES_CACHE_FILE = "breadcrumbs_bundles_cache.data"; private static final String BREADCRUMSB_ACTIVITY_CACHE_FILE = "breadcrumbs_activity_cache.data"; /** * Time in milliseconds that a persisted breadcrumbs cache is used without a refresh */ private static final long CACHE_TIMEOUT = 1000 * 60;//1000*60*10 ; /** * Mapping from bundleId to a list of trackIds */ private static Map<Integer, List<Integer>> sBundlesWithTracks; /** * Map from activityId to a dictionary containing keys like NAME */ private static Map<Integer, Map<String, String>> sActivityMappings; /** * Map from bundleId to a dictionary containing keys like NAME and DESCRIPTION */ private static Map<Integer, Map<String, String>> sBundleMappings; /** * Map from trackId to a dictionary containing keys like NAME, ISPUBLIC, DESCRIPTION and more */ private static Map<Integer, Map<String, String>> sTrackMappings; /** * Cache of OGT Tracks that have a Breadcrumbs track id stored in the meta-data table */ private Map<Long, Integer> mSyncedTracks = null; private static Set<Pair<Integer, Integer>> sScheduledTracksLoading; static { BreadcrumbsTracks.initCacheVariables(); } private static void initCacheVariables() { sBundlesWithTracks = new LinkedHashMap<Integer, List<Integer>>(); sActivityMappings = new HashMap<Integer, Map<String, String>>(); sBundleMappings = new HashMap<Integer, Map<String, String>>(); sTrackMappings = new HashMap<Integer, Map<String, String>>(); sScheduledTracksLoading = new HashSet<Pair<Integer, Integer>>(); } private ContentResolver mResolver; /** * Constructor: create a new BreadcrumbsTracks. * * @param resolver Content resolver to obtain local Breadcrumbs references */ public BreadcrumbsTracks(ContentResolver resolver) { mResolver = resolver; } public void addActivity(Integer activityId, String activityName) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addActivity(Integer " + activityId + " String " + activityName + ")"); } if (!sActivityMappings.containsKey(activityId)) { sActivityMappings.put(activityId, new HashMap<String, String>()); } sActivityMappings.get(activityId).put(NAME, activityName); setChanged(); notifyObservers(); } /** * Add bundle to the track list * * @param activityId * @param bundleId * @param bundleName * @param bundleDescription */ public void addBundle(Integer bundleId, String bundleName, String bundleDescription) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addBundle(Integer " + bundleId + ", String " + bundleName + ", String " + bundleDescription + ")"); } if (!sBundleMappings.containsKey(bundleId)) { sBundleMappings.put(bundleId, new HashMap<String, String>()); } if (!sBundlesWithTracks.containsKey(bundleId)) { sBundlesWithTracks.put(bundleId, new ArrayList<Integer>()); } sBundleMappings.get(bundleId).put(NAME, bundleName); sBundleMappings.get(bundleId).put(DESCRIPTION, bundleDescription); setChanged(); notifyObservers(); } /** * Add track to tracklist * * @param trackId * @param trackName * @param bundleId * @param trackDescription * @param difficulty * @param startTime * @param endTime * @param isPublic * @param lat * @param lng * @param totalDistance * @param totalTime * @param trackRating */ public void addTrack(Integer trackId, String trackName, Integer bundleId, String trackDescription, String difficulty, String startTime, String endTime, String isPublic, Float lat, Float lng, Float totalDistance, Integer totalTime, String trackRating) { if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "addTrack(Integer " + trackId + ", String " + trackName + ", Integer " + bundleId + "..."); } if (!sBundlesWithTracks.containsKey(bundleId)) { sBundlesWithTracks.put(bundleId, new ArrayList<Integer>()); } if (!sBundlesWithTracks.get(bundleId).contains(trackId)) { sBundlesWithTracks.get(bundleId).add(trackId); sScheduledTracksLoading.remove(Pair.create(Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE, trackId)); } if (!sTrackMappings.containsKey(trackId)) { sTrackMappings.put(trackId, new HashMap<String, String>()); } putForTrack(trackId, NAME, trackName); putForTrack(trackId, ISPUBLIC, isPublic); putForTrack(trackId, STARTTIME, startTime); putForTrack(trackId, ENDTIME, endTime); putForTrack(trackId, DESCRIPTION, trackDescription); putForTrack(trackId, DIFFICULTY, difficulty); putForTrack(trackId, RATING, trackRating); putForTrack(trackId, LATITUDE, lat); putForTrack(trackId, LONGITUDE, lng); putForTrack(trackId, TOTALDISTANCE, totalDistance); putForTrack(trackId, TOTALTIME, totalTime); notifyObservers(); } public void addSyncedTrack(Long trackId, Integer bcTrackId) { if (mSyncedTracks == null) { isLocalTrackOnline(-1l); } mSyncedTracks.put(trackId, bcTrackId); setChanged(); notifyObservers(); } public void addTracksLoadingScheduled(Pair<Integer, Integer> item) { sScheduledTracksLoading.add(item); setChanged(); notifyObservers(); } /** * Cleans old bundles based a set of all bundles * * @param mBundleIds */ public void setAllBundleIds(Set<Integer> mBundleIds) { for (Integer oldBundleId : getAllBundleIds()) { if (!mBundleIds.contains(oldBundleId)) { removeBundle(oldBundleId); } } } public void setAllTracksForBundleId(Integer mBundleId, Set<Integer> updatedbcTracksIdList) { List<Integer> trackIdList = sBundlesWithTracks.get(mBundleId); for (int location = 0; location < trackIdList.size(); location++) { Integer oldTrackId = trackIdList.get(location); if (!updatedbcTracksIdList.contains(oldTrackId)) { removeTrack(mBundleId, oldTrackId); } } setChanged(); notifyObservers(); } private void putForTrack(Integer trackId, String key, Object value) { if (value != null) { sTrackMappings.get(trackId).put(key, value.toString()); } setChanged(); notifyObservers(); } /** * Remove a bundle * * @param deletedId */ public void removeBundle(Integer deletedId) { sBundleMappings.remove(deletedId); sBundlesWithTracks.remove(deletedId); setChanged(); notifyObservers(); } /** * Remove a track * * @param deletedId */ public void removeTrack(Integer bundleId, Integer trackId) { sTrackMappings.remove(trackId); if (sBundlesWithTracks.containsKey(bundleId)) { sBundlesWithTracks.get(bundleId).remove(trackId); } setChanged(); notifyObservers(); mResolver.delete(MetaData.CONTENT_URI, MetaData.TRACK + " = ? AND " + MetaData.KEY + " = ? ", new String[] { trackId.toString(), TRACK_ID }); if (mSyncedTracks != null && mSyncedTracks.containsKey(trackId)) { mSyncedTracks.remove(trackId); } } public int positions() { int size = 0; for (Integer bundleId : sBundlesWithTracks.keySet()) { // One row for the Bundle header size += 1; int bundleSize = sBundlesWithTracks.get(bundleId) != null ? sBundlesWithTracks.get(bundleId).size() : 0; // One row per track in each bundle size += bundleSize; } return size; } public Integer getBundleIdForTrackId(Integer trackId) { for (Integer bundlId : sBundlesWithTracks.keySet()) { List<Integer> trackIds = sBundlesWithTracks.get(bundlId); if (trackIds.contains(trackId)) { return bundlId; } } return null; } public Integer[] getAllActivityIds() { return sActivityMappings.keySet().toArray(new Integer[sActivityMappings.keySet().size()]); } /** * Get all bundles * * @return */ public Integer[] getAllBundleIds() { return sBundlesWithTracks.keySet().toArray(new Integer[sBundlesWithTracks.keySet().size()]); } /** * @param position list postition 0...n * @return a pair of a TYPE and an ID */ public List<Pair<Integer, Integer>> getAllItems() { List<Pair<Integer, Integer>> items = new LinkedList<Pair<Integer, Integer>>(); for (Integer bundleId : sBundlesWithTracks.keySet()) { items.add(Pair.create(Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE, bundleId)); for(Integer trackId : sBundlesWithTracks.get(bundleId)) { items.add(Pair.create(Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE, trackId)); } } return items; } public List<Pair<Integer, Integer>> getActivityList() { List<Pair<Integer, Integer>> items = new LinkedList<Pair<Integer, Integer>>(); for (Integer activityId : sActivityMappings.keySet()) { Pair<Integer, Integer> pair = Pair.create(Constants.BREADCRUMBS_ACTIVITY_ITEM_VIEW_TYPE, activityId); pair.overrideToString(getValueForItem(pair, NAME)); items.add(pair); } return items; } public List<Pair<Integer, Integer>> getBundleList() { List<Pair<Integer, Integer>> items = new LinkedList<Pair<Integer, Integer>>(); for (Integer bundleId : sBundleMappings.keySet()) { Pair<Integer, Integer> pair = Pair.create(Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE, bundleId); pair.overrideToString(getValueForItem(pair, NAME)); items.add(pair); } return items; } public String getValueForItem(Pair<Integer, Integer> item, String key) { String value = null; switch (item.first) { case Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE: value = sBundleMappings.get(item.second).get(key); break; case Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE: value = sTrackMappings.get(item.second).get(key); break; case Constants.BREADCRUMBS_ACTIVITY_ITEM_VIEW_TYPE: value = sActivityMappings.get(item.second).get(key); break; default: value = null; break; } return value; } private boolean isLocalTrackOnline(Long qtrackId) { if (mSyncedTracks == null) { mSyncedTracks = new HashMap<Long, Integer>(); Cursor cursor = null; try { cursor = mResolver.query(MetaData.CONTENT_URI, new String[] { MetaData.TRACK, MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { TRACK_ID }, null); if (cursor.moveToFirst()) { do { Long trackId = cursor.getLong(0); try { Integer bcTrackId = Integer.valueOf(cursor.getString(1)); mSyncedTracks.put(trackId, bcTrackId); } catch (NumberFormatException e) { Log.w(TAG, "Illigal value stored as track id", e); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } setChanged(); notifyObservers(); } boolean synced = mSyncedTracks.containsKey(qtrackId); return synced; } public boolean isLocalTrackSynced(Long qtrackId) { boolean uploaded = isLocalTrackOnline(qtrackId); boolean synced = sTrackMappings.containsKey(mSyncedTracks.get(qtrackId)); return uploaded && synced; } public boolean areTracksLoaded(Pair<Integer, Integer> item) { return sBundlesWithTracks.containsKey(item.second) && item.first == Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE; } public boolean areTracksLoadingScheduled(Pair<Integer, Integer> item) { return sScheduledTracksLoading.contains(item); } /** * Read the static breadcrumbs data from private file * * @param ctx * @return is refresh is needed */ @SuppressWarnings("unchecked") public boolean readCache(Context ctx) { FileInputStream fis = null; ObjectInputStream ois = null; Date bundlesPersisted = null, activitiesPersisted = null; Object[] cache; synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { try { fis = ctx.openFileInput(BREADCRUMSB_BUNDLES_CACHE_FILE); ois = new ObjectInputStream(fis); cache = (Object[]) ois.readObject(); // new Object[] { CACHE_VERSION, new Date(), sActivitiesWithBundles, sBundlesWithTracks, sBundleMappings, sTrackMappings }; if (cache[0] instanceof Integer && CACHE_VERSION.equals(cache[0])) { bundlesPersisted = (Date) cache[1]; Map<Integer, List<Integer>> bundles = (Map<Integer, List<Integer>>) cache[2]; Map<Integer, Map<String, String>> bundlemappings = (Map<Integer, Map<String, String>>) cache[3]; Map<Integer, Map<String, String>> trackmappings = (Map<Integer, Map<String, String>>) cache[4]; sBundlesWithTracks = bundles != null ? bundles : sBundlesWithTracks; sBundleMappings = bundlemappings != null ? bundlemappings : sBundleMappings; sTrackMappings = trackmappings != null ? trackmappings : sTrackMappings; } else { clearPersistentCache(ctx); } fis = ctx.openFileInput(BREADCRUMSB_ACTIVITY_CACHE_FILE); ois = new ObjectInputStream(fis); cache = (Object[]) ois.readObject(); // new Object[] { CACHE_VERSION, new Date(), sActivityMappings }; if (cache[0] instanceof Integer && CACHE_VERSION.equals(cache[0])) { activitiesPersisted = (Date) cache[1]; Map<Integer, Map<String, String>> activitymappings = (Map<Integer, Map<String, String>>) cache[2]; sActivityMappings = activitymappings != null ? activitymappings : sActivityMappings; } else { clearPersistentCache(ctx); } } catch (OptionalDataException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ClassNotFoundException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (IOException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ClassCastException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } catch (ArrayIndexOutOfBoundsException e) { clearPersistentCache(ctx); Log.w(TAG, "Unable to read persisted breadcrumbs cache", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { Log.w(TAG, "Error closing file stream after reading cache", e); } } if (ois != null) { try { ois.close(); } catch (IOException e) { Log.w(TAG, "Error closing object stream after reading cache", e); } } } } setChanged(); notifyObservers(); boolean refreshNeeded = false; refreshNeeded = refreshNeeded || bundlesPersisted == null || activitiesPersisted == null; refreshNeeded = refreshNeeded || (activitiesPersisted.getTime() < new Date().getTime() - CACHE_TIMEOUT * 10); refreshNeeded = refreshNeeded || (bundlesPersisted.getTime() < new Date().getTime() - CACHE_TIMEOUT); return refreshNeeded; } public void persistCache(Context ctx) { FileOutputStream fos = null; ObjectOutputStream oos = null; Object[] cache; synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { try { fos = ctx.openFileOutput(BREADCRUMSB_BUNDLES_CACHE_FILE, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); cache = new Object[] { CACHE_VERSION, new Date(), sBundlesWithTracks, sBundleMappings, sTrackMappings }; oos.writeObject(cache); fos = ctx.openFileOutput(BREADCRUMSB_ACTIVITY_CACHE_FILE, Context.MODE_PRIVATE); oos = new ObjectOutputStream(fos); cache = new Object[] { CACHE_VERSION, new Date(), sActivityMappings }; oos.writeObject(cache); } catch (FileNotFoundException e) { Log.e(TAG, "Error in file stream during persist cache", e); } catch (IOException e) { Log.e(TAG, "Error in object stream during persist cache", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { Log.w(TAG, "Error closing file stream after writing cache", e); } } if (oos != null) { try { oos.close(); } catch (IOException e) { Log.w(TAG, "Error closing object stream after writing cache", e); } } } } } public void clearAllCache(Context ctx) { BreadcrumbsTracks.initCacheVariables(); setChanged(); clearPersistentCache(ctx); notifyObservers(); } public void clearPersistentCache(Context ctx) { Log.w(TAG, "Deleting old Breadcrumbs cache files"); synchronized (BREADCRUMSB_BUNDLES_CACHE_FILE) { ctx.deleteFile(BREADCRUMSB_ACTIVITY_CACHE_FILE); ctx.deleteFile(BREADCRUMSB_BUNDLES_CACHE_FILE); } } @Override public String toString() { return "BreadcrumbsTracks [mActivityMappings=" + sActivityMappings + ", mBundleMappings=" + sBundleMappings + ", mTrackMappings=" + sTrackMappings + ", mActivities=" + sActivityMappings + ", mBundles=" + sBundlesWithTracks + "]"; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/BreadcrumbsTracks.java
Java
gpl3
22,876
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.Context; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class GetBreadcrumbsBundlesTask extends BreadcrumbsTask { final String TAG = "OGT.GetBreadcrumbsBundlesTask"; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpclient; private Set<Integer> mBundleIds; private LinkedList<Object[]> mBundles; /** * We pass the OAuth consumer and provider. * * @param mContext Required to be able to start the intent to launch the * browser. * @param httpclient * @param listener * @param provider The OAuthProvider object * @param mConsumer The OAuthConsumer object */ public GetBreadcrumbsBundlesTask(Context context, BreadcrumbsService adapter, ProgressListener listener, DefaultHttpClient httpclient, OAuthConsumer consumer) { super(context, adapter, listener); mHttpclient = httpclient; mConsumer = consumer; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Void doInBackground(Void... params) { HttpEntity responseEntity = null; mBundleIds = new HashSet<Integer>(); mBundles = new LinkedList<Object[]>(); try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/bundles.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String bundleName = null, bundleDescription = null; Integer bundleId = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("bundle".equals(xpp.getName()) && bundleId != null) { mBundles.add( new Object[]{bundleId, bundleName, bundleDescription} ); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("description".equals(tagName)) { bundleDescription = xpp.getText(); } else if ("id".equals(tagName)) { bundleId = Integer.parseInt(xpp.getText()); mBundleIds.add(bundleId); } else if ("name".equals(tagName)) { bundleName = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem while reading the XML data"); } catch (IllegalStateException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.w(TAG, "Failed closing inputstream"); } } } return null; } @Override protected void updateTracksData(BreadcrumbsTracks tracks) { tracks.setAllBundleIds( mBundleIds ); for( Object[] bundle : mBundles ) { Integer bundleId = (Integer) bundle[0]; String bundleName = (String) bundle[1]; String bundleDescription = (String) bundle[2]; tracks.addBundle(bundleId, bundleName, bundleDescription); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/GetBreadcrumbsBundlesTask.java
Java
gpl3
8,517
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.tasks.XmlCreator; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import oauth.signpost.OAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.Context; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class GetBreadcrumbsTracksTask extends BreadcrumbsTask { final String TAG = "OGT.GetBreadcrumbsTracksTask"; private OAuthConsumer mConsumer; private DefaultHttpClient mHttpclient; private Integer mBundleId; private LinkedList<Object[]> mTracks; /** * We pass the OAuth consumer and provider. * * @param mContext Required to be able to start the intent to launch the * browser. * @param httpclient * @param provider The OAuthProvider object * @param mConsumer The OAuthConsumer object */ public GetBreadcrumbsTracksTask(Context context, BreadcrumbsService adapter, ProgressListener listener, DefaultHttpClient httpclient, OAuthConsumer consumer, Integer bundleId) { super(context, adapter, listener); mHttpclient = httpclient; mConsumer = consumer; mBundleId = bundleId; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Void doInBackground(Void... params) { mTracks = new LinkedList<Object[]>(); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/bundles/"+mBundleId+"/tracks.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if( BreadcrumbsAdapter.DEBUG ) { Log.d( TAG, "Execute request: "+request.getURI() ); for( Header header : request.getAllHeaders() ) { Log.d( TAG, " with header: "+header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if( BreadcrumbsAdapter.DEBUG ) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String trackName = null, description = null, difficulty = null, startTime = null, endTime = null, trackRating = null, isPublic = null; Integer trackId = null, bundleId = null, totalTime = null; Float lat = null, lng = null, totalDistance = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("track".equals(xpp.getName()) && trackId != null && bundleId != null) { mTracks.add(new Object[] { trackId, trackName, bundleId, description, difficulty, startTime, endTime, isPublic, lat, lng, totalDistance, totalTime, trackRating }); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("bundle-id".equals(tagName)) { bundleId = Integer.parseInt(xpp.getText()); } else if ("description".equals(tagName)) { description = xpp.getText(); } else if ("difficulty".equals(tagName)) { difficulty = xpp.getText(); } else if ("start-time".equals(tagName)) { startTime = xpp.getText(); } else if ("end-time".equals(tagName)) { endTime = xpp.getText(); } else if ("id".equals(tagName)) { trackId = Integer.parseInt(xpp.getText()); } else if ("is-public".equals(tagName)) { isPublic = xpp.getText(); } else if ("lat".equals(tagName)) { lat = Float.parseFloat(xpp.getText()); } else if ("lng".equals(tagName)) { lng = Float.parseFloat(xpp.getText()); } else if ("name".equals(tagName)) { trackName = xpp.getText(); } else if ("track-rating".equals(tagName)) { trackRating = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_track), e, "A problem while reading the XML data"); } finally { if (responseEntity != null) { try { EntityUtils.consume(responseEntity); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } return null; } @Override protected void updateTracksData(BreadcrumbsTracks tracks) { Set<Integer> mTracksIds = new HashSet<Integer>() ; for (Object[] track : mTracks) { mTracksIds.add((Integer) track[0]); } tracks.setAllTracksForBundleId( mBundleId, mTracksIds ); for (Object[] track : mTracks) { Integer trackId = (Integer) track[0]; String trackName = (String) track[1]; Integer bundleId = (Integer) track[2]; String description = (String) track[3]; String difficulty = (String) track[4]; String startTime = (String) track[5]; String endTime = (String) track[6]; String isPublic = (String) track[7]; Float lat = (Float) track[8]; Float lng = (Float) track[9]; Float totalDistance = (Float) track[10]; Integer totalTime = (Integer) track[11]; String trackRating = (String) track[12]; tracks.addTrack(trackId, trackName, bundleId, description, difficulty, startTime, endTime, isPublic, lat, lng, totalDistance, totalTime, trackRating); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/GetBreadcrumbsTracksTask.java
Java
gpl3
10,413
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Oct 20, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.breadcrumbs; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.oauth.PrepareRequestTokenActivity; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.scheme.PlainSocketFactory; import org.apache.ogt.http.conn.scheme.Scheme; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.net.Uri; import android.os.AsyncTask; import android.os.Binder; import android.os.Build; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; /** * ???? * * @version $Id:$ * @author rene (c) Oct 20, 2012, Sogeti B.V. */ public class BreadcrumbsService extends Service implements Observer, ProgressListener { public static final String OAUTH_TOKEN = "breadcrumbs_oauth_token"; public static final String OAUTH_TOKEN_SECRET = "breadcrumbs_oauth_secret"; private static final String TAG = "OGT.BreadcrumbsService"; public static final String NOTIFY_DATA_SET_CHANGED = "nl.sogeti.android.gpstracker.intent.action.NOTIFY_DATA_SET_CHANGED"; public static final String NOTIFY_PROGRESS_CHANGED = "nl.sogeti.android.gpstracker.intent.action.NOTIFY_PROGRESS_CHANGED"; public static final String PROGRESS_INDETERMINATE = null; public static final String PROGRESS = null; public static final String PROGRESS_STATE = null; public static final String PROGRESS_RESULT = null; public static final String PROGRESS_TASK = null; public static final String PROGRESS_MESSAGE = null; public static final int PROGRESS_STARTED = 1; public static final int PROGRESS_FINISHED = 2; public static final int PROGRESS_ERROR = 3; private final IBinder mBinder = new LocalBinder(); private BreadcrumbsTracks mTracks; private DefaultHttpClient mHttpClient; private OnSharedPreferenceChangeListener tokenChangedListener; private boolean mFinishing; boolean mAuthorized; ExecutorService mExecutor; @Override public void onCreate() { super.onCreate(); mExecutor = Executors.newFixedThreadPool(1); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ClientConnectionManager cm = new ThreadSafeClientConnManager(schemeRegistry); mHttpClient = new DefaultHttpClient(cm); mTracks = new BreadcrumbsTracks(this.getContentResolver()); mTracks.addObserver(this); connectionSetup(); } @Override public void onDestroy() { if (tokenChangedListener != null) { PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(tokenChangedListener); } mAuthorized = false; mFinishing = true; new AsyncTask<Void, Void, Void>() { public void executeOn(Executor executor) { if (Build.VERSION.SDK_INT >= 11) { executeOnExecutor(executor); } else { execute(); } } @Override protected Void doInBackground(Void... params) { mHttpClient.getConnectionManager().shutdown(); mExecutor.shutdown(); mHttpClient = null; return null; } }.executeOn(mExecutor); mTracks.persistCache(this); super.onDestroy(); } /** * Class used for the client Binder. Because we know this service always runs in the same process as its clients, we don't need to deal with IPC. */ public class LocalBinder extends Binder { public BreadcrumbsService getService() { return BreadcrumbsService.this; } } /** * @see android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent intent) { return mBinder; } private boolean connectionSetup() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String token = prefs.getString(OAUTH_TOKEN, ""); String secret = prefs.getString(OAUTH_TOKEN_SECRET, ""); mAuthorized = !"".equals(token) && !"".equals(secret); if (mAuthorized) { CommonsHttpOAuthConsumer consumer = getOAuthConsumer(); if (mTracks.readCache(this)) { new GetBreadcrumbsActivitiesTask(this, this, this, mHttpClient, consumer).executeOn(mExecutor); new GetBreadcrumbsBundlesTask(this, this, this, mHttpClient, consumer).executeOn(mExecutor); } } return mAuthorized; } public CommonsHttpOAuthConsumer getOAuthConsumer() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String token = prefs.getString(OAUTH_TOKEN, ""); String secret = prefs.getString(OAUTH_TOKEN_SECRET, ""); CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(this.getString(R.string.CONSUMER_KEY), this.getString(R.string.CONSUMER_SECRET)); consumer.setTokenWithSecret(token, secret); return consumer; } public void removeAuthentication() { Log.w(TAG, "Removing Breadcrumbs OAuth tokens"); Editor e = PreferenceManager.getDefaultSharedPreferences(this).edit(); e.remove(OAUTH_TOKEN); e.remove(OAUTH_TOKEN_SECRET); e.commit(); } /** * Use a locally stored token or start the request activity to collect one */ public void collectBreadcrumbsOauthToken() { if (!connectionSetup()) { tokenChangedListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (OAUTH_TOKEN.equals(key)) { PreferenceManager.getDefaultSharedPreferences(BreadcrumbsService.this).unregisterOnSharedPreferenceChangeListener(tokenChangedListener); connectionSetup(); } } }; PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(tokenChangedListener); Intent i = new Intent(this.getApplicationContext(), PrepareRequestTokenActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_PREF, OAUTH_TOKEN); i.putExtra(PrepareRequestTokenActivity.OAUTH_TOKEN_SECRET_PREF, OAUTH_TOKEN_SECRET); i.putExtra(PrepareRequestTokenActivity.CONSUMER_KEY, this.getString(R.string.CONSUMER_KEY)); i.putExtra(PrepareRequestTokenActivity.CONSUMER_SECRET, this.getString(R.string.CONSUMER_SECRET)); i.putExtra(PrepareRequestTokenActivity.REQUEST_URL, Constants.REQUEST_URL); i.putExtra(PrepareRequestTokenActivity.ACCESS_URL, Constants.ACCESS_URL); i.putExtra(PrepareRequestTokenActivity.AUTHORIZE_URL, Constants.AUTHORIZE_URL); this.startActivity(i); } } public void startDownloadTask(Context context, ProgressListener listener, Pair<Integer, Integer> track) { new DownloadBreadcrumbsTrackTask(context, listener, this, mHttpClient, getOAuthConsumer(), track).executeOn(mExecutor); } public void startUploadTask(Context context, ProgressListener listener, Uri trackUri, String name) { new UploadBreadcrumbsTrackTask(context, this, listener, mHttpClient, getOAuthConsumer(), trackUri, name).executeOn(mExecutor); } public boolean isAuthorized() { return mAuthorized; } public void willDisplayItem(Pair<Integer, Integer> item) { if (item.first == Constants.BREADCRUMBS_BUNDLE_ITEM_VIEW_TYPE) { if (!mFinishing && !mTracks.areTracksLoaded(item) && !mTracks.areTracksLoadingScheduled(item)) { new GetBreadcrumbsTracksTask(this, this, this, mHttpClient, getOAuthConsumer(), item.second).executeOn(mExecutor); mTracks.addTracksLoadingScheduled(item); } } } public List<Pair<Integer, Integer>> getAllItems() { List<Pair<Integer, Integer>> items = mTracks.getAllItems(); return items; } public List<Pair<Integer, Integer>> getActivityList() { List<Pair<Integer, Integer>> activities = mTracks.getActivityList(); return activities; } public List<Pair<Integer, Integer>> getBundleList() { List<Pair<Integer, Integer>> bundles = mTracks.getBundleList(); return bundles; } public String getValueForItem(Pair<Integer, Integer> item, String name) { return mTracks.getValueForItem(item, name); } public void clearAllCache() { mTracks.clearAllCache(this); } protected BreadcrumbsTracks getBreadcrumbsTracks() { return mTracks; } public boolean isLocalTrackSynced(long trackId) { return mTracks.isLocalTrackSynced(trackId); } /**** * Observer interface */ @Override public void update(Observable observable, Object data) { Intent broadcast = new Intent(); broadcast.setAction(BreadcrumbsService.NOTIFY_DATA_SET_CHANGED); getApplicationContext().sendBroadcast(broadcast); } /**** * ProgressListener interface */ @Override public void setIndeterminate(boolean indeterminate) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_INDETERMINATE, indeterminate); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void started() { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_STATE, BreadcrumbsService.PROGRESS_STARTED); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void setProgress(int value) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS, value); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void finished(Uri result) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_STATE, BreadcrumbsService.PROGRESS_FINISHED); broadcast.putExtra(BreadcrumbsService.PROGRESS_RESULT, result); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } @Override public void showError(String task, String errorMessage, Exception exception) { Intent broadcast = new Intent(); broadcast.putExtra(BreadcrumbsService.PROGRESS_STATE, BreadcrumbsService.PROGRESS_ERROR); broadcast.putExtra(BreadcrumbsService.PROGRESS_TASK, task); broadcast.putExtra(BreadcrumbsService.PROGRESS_MESSAGE, errorMessage); broadcast.putExtra(BreadcrumbsService.PROGRESS_RESULT, exception); broadcast.setAction(BreadcrumbsService.NOTIFY_PROGRESS_CHANGED); getApplicationContext().sendBroadcast(broadcast); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/breadcrumbs/BreadcrumbsService.java
Java
gpl3
12,931
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.oauth; import nl.sogeti.android.gpstracker.util.Constants; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; /** * An asynchronous task that communicates with Twitter to retrieve a request * token. (OAuthGetRequestToken) After receiving the request token from Twitter, * pop a browser to the user to authorize the Request Token. * (OAuthAuthorizeToken) */ public class OAuthRequestTokenTask extends AsyncTask<Void, Void, Void> { final String TAG = "OGT.OAuthRequestTokenTask"; private Context context; private OAuthProvider provider; private OAuthConsumer consumer; /** * We pass the OAuth consumer and provider. * * @param context Required to be able to start the intent to launch the * browser. * @param provider The OAuthProvider object * @param consumer The OAuthConsumer object */ public OAuthRequestTokenTask(Context context, OAuthConsumer consumer, OAuthProvider provider) { this.context = context; this.consumer = consumer; this.provider = provider; } /** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token. */ @Override protected Void doInBackground(Void... params) { try { final String url = provider.retrieveRequestToken(consumer, Constants.OAUTH_CALLBACK_URL); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND); context.startActivity(intent); } catch (Exception e) { Log.e(TAG, "Failed to start token request ", e); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.OAUTH_CALLBACK_URL)); intent.putExtra("ERROR", e.toString()); context.startActivity(intent); } return null; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/oauth/OAuthRequestTokenTask.java
Java
gpl3
3,633
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.oauth; import oauth.signpost.OAuth; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> { private static final String TAG = "OGT.RetrieveAccessTokenTask"; private OAuthProvider provider; private OAuthConsumer consumer; private SharedPreferences prefs; private String mTokenKey; private String mSecretKey; public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer, OAuthProvider provider, SharedPreferences prefs, String tokenKey, String secretKey) { this.consumer = consumer; this.provider = provider; this.prefs = prefs; mTokenKey = tokenKey; mSecretKey = secretKey; } /** * Retrieve the oauth_verifier, and store the oauth and oauth_token_secret * for future API calls. */ @Override protected Void doInBackground(Uri... params) { final Uri uri = params[0]; final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER); try { provider.retrieveAccessToken(consumer, oauth_verifier); final Editor edit = prefs.edit(); edit.putString(mTokenKey, consumer.getToken()); edit.putString(mSecretKey, consumer.getTokenSecret()); edit.commit(); Log.i(TAG, "OAuth - Access Token Retrieved and stored to "+mTokenKey+" and "+mSecretKey); } catch (Exception e) { Log.e(TAG, "OAuth - Access Token Retrieval Error", e); } return null; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/oauth/RetrieveAccessTokenTask.java
Java
gpl3
3,310
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.oauth; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthProvider; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask.Status; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.widget.TextView; /** * Prepares a OAuthConsumer and OAuthProvider OAuthConsumer is configured with * the consumer key & consumer secret. Both key and secret are retrieved from * the extras in the Intent * * OAuthProvider is configured with the 3 * OAuth endpoints. These are retrieved from the extras in the Intent. * * Execute the OAuthRequestTokenTask to retrieve the request, * and authorize the request. After the request is authorized, a callback is * made here and this activity finishes to return to the last Activity on the * stack. */ public class PrepareRequestTokenActivity extends Activity { /** * Name of the Extra in the intent holding the consumer secret */ public static final String CONSUMER_SECRET = "CONSUMER_SECRET"; /** * Name of the Extra in the intent holding the consumer key */ public static final String CONSUMER_KEY = "CONSUMER_KEY"; /** * Name of the Extra in the intent holding the authorizationWebsiteUrl */ public static final String AUTHORIZE_URL = "AUTHORIZE_URL"; /** * Name of the Extra in the intent holding the accessTokenEndpointUrl */ public static final String ACCESS_URL = "ACCESS_URL"; /** * Name of the Extra in the intent holding the requestTokenEndpointUrl */ public static final String REQUEST_URL = "REQUEST_URL"; /** * String value of the key in the DefaultSharedPreferences * in which to store the permission token */ public static final String OAUTH_TOKEN_PREF = "OAUTH_TOKEN"; /** * String value of the key in the DefaultSharedPreferences * in which to store the permission secret */ public static final String OAUTH_TOKEN_SECRET_PREF = "OAUTH_TOKEN_SECRET"; final String TAG = "OGT.PrepareRequestTokenActivity"; private OAuthConsumer consumer; private OAuthProvider provider; private String mTokenKey; private String mSecretKey; private OAuthRequestTokenTask mTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.oauthentication); String key = getIntent().getStringExtra(CONSUMER_KEY); String secret = getIntent().getStringExtra(CONSUMER_SECRET); String requestUrl = getIntent().getStringExtra(REQUEST_URL); String accessUrl = getIntent().getStringExtra(ACCESS_URL); String authUrl = getIntent().getStringExtra(AUTHORIZE_URL); TextView tv = (TextView) findViewById(R.id.detail); tv.setText(requestUrl); mTokenKey = getIntent().getStringExtra(OAUTH_TOKEN_PREF); mSecretKey = getIntent().getStringExtra(OAUTH_TOKEN_SECRET_PREF); this.consumer = new CommonsHttpOAuthConsumer(key, secret); this.provider = new CommonsHttpOAuthProvider(requestUrl, accessUrl, authUrl); mTask = new OAuthRequestTokenTask(this, consumer, provider); mTask.execute(); } @Override protected void onResume() { super.onResume(); // Will not be called if onNewIntent() was called with callback scheme Status status = mTask.getStatus(); if( status != Status.RUNNING ) { finish(); } } /** * Called when the OAuthRequestTokenTask finishes (user has authorized the * request token). The callback URL will be intercepted here. */ @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final Uri uri = intent.getData(); if (uri != null && uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) { Log.i(TAG, "Callback received : " + uri); Log.i(TAG, "Retrieving Access Token"); new RetrieveAccessTokenTask(this, consumer, provider, prefs, mTokenKey, mSecretKey).execute(uri); finish(); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/oauth/PrepareRequestTokenActivity.java
Java
gpl3
6,091
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.widget; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ControlTracking; import nl.sogeti.android.gpstracker.actions.InsertNote; import nl.sogeti.android.gpstracker.util.Constants; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import android.view.View; import android.widget.RemoteViews; /** * An App Widget for on the home screen to control logging with a start, pause, * resume and stop * * @version $Id$ * @author grootren (c) Mar 8, 2011, Sogeti B.V. */ public class ControlWidgetProvider extends AppWidgetProvider { private static final int BUTTON_TRACKINGCONTROL = 2; private static final int BUTTON_INSERTNOTE = 3; private static final String TAG = "OGT.ControlWidgetProvider"; static final ComponentName THIS_APPWIDGET = new ComponentName("nl.sogeti.android.gpstracker", "nl.sogeti.android.gpstracker.widget.ControlWidgetProvider"); private static int mState; public ControlWidgetProvider() { super(); } @Override public void onEnabled(Context context) { // Log.d(TAG, "onEnabled() "); super.onEnabled(context); context.startService(new Intent(Constants.SERVICENAME)); } @Override public void onDisabled(Context context) { // Log.d(TAG, "onDisabled() "); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Log.d(TAG, "onDisabled() "); // Update each requested appWidgetId RemoteViews view = buildUpdate(context, -1); for (int i = 0; i < appWidgetIds.length; i++) { appWidgetManager.updateAppWidget(appWidgetIds[i], view); } } /** * Load image for given widget and build {@link RemoteViews} for it. */ static RemoteViews buildUpdate(Context context, int appWidgetId) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.control_appwidget); views.setOnClickPendingIntent(R.id.widget_insertnote_enabled, getLaunchPendingIntent(context, appWidgetId, BUTTON_INSERTNOTE)); views.setOnClickPendingIntent(R.id.widget_trackingcontrol, getLaunchPendingIntent(context, appWidgetId, BUTTON_TRACKINGCONTROL)); updateButtons(views, context); return views; } /** * Load image for given widget and build {@link RemoteViews} for it. */ private static void updateButtons(RemoteViews views, Context context) { // Log.d(TAG, "Updated the remote views to state " + mState); switch (mState) { case Constants.LOGGING: setEnableInsertNote(views, true); break; case Constants.PAUSED: setEnableInsertNote(views, false); break; case Constants.STOPPED: setEnableInsertNote(views, false); break; case Constants.UNKNOWN: setEnableInsertNote(views, false); break; default: Log.w(TAG, "Unknown logging state for widget: " + mState); break; } } private static void setEnableInsertNote( RemoteViews views, boolean enabled ) { if( enabled ) { views.setViewVisibility(R.id.widget_insertnote_enabled, View.VISIBLE); views.setViewVisibility(R.id.widget_insertnote_disabled, View.GONE); } else { views.setViewVisibility(R.id.widget_insertnote_enabled, View.GONE); views.setViewVisibility(R.id.widget_insertnote_disabled, View.VISIBLE); } } /** * Creates PendingIntent to notify the widget of a button click. * * @param context * @param appWidgetId * @return */ private static PendingIntent getLaunchPendingIntent(Context context, int appWidgetId, int buttonId) { Intent launchIntent = new Intent(); launchIntent.setClass(context, ControlWidgetProvider.class); launchIntent.addCategory(Intent.CATEGORY_ALTERNATIVE); launchIntent.setData(Uri.parse("custom:" + buttonId)); PendingIntent pi = PendingIntent.getBroadcast(context, 0 /* no requestCode */, launchIntent, 0 /* * no * flags */); return pi; } /** * Receives and processes a button pressed intent or state change. * * @param context * @param intent Indicates the pressed button. */ @Override public void onReceive(Context context, Intent intent) { // Log.d(TAG, "Did recieve intent with action: " + intent.getAction()); super.onReceive(context, intent); String action = intent.getAction(); if (Constants.LOGGING_STATE_CHANGED_ACTION.equals(action)) { mState = intent.getIntExtra(Constants.EXTRA_LOGGING_STATE, Constants.UNKNOWN); updateWidget(context); } else if (intent.hasCategory(Intent.CATEGORY_ALTERNATIVE)) { Uri data = intent.getData(); int buttonId = Integer.parseInt(data.getSchemeSpecificPart()); if (buttonId == BUTTON_TRACKINGCONTROL) { Intent controlIntent = new Intent( context, ControlTracking.class ); controlIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(controlIntent); } else if (buttonId == BUTTON_INSERTNOTE) { Intent noteIntent = new Intent( context, InsertNote.class ); noteIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity( noteIntent ); } } else { // Don't fall-through to updating the widget. The Intent // was something unrelated or that our super class took // care of. return; } // State changes fall through updateWidget(context); } /** * Updates the widget when something changes, or when a button is pushed. * * @param context */ public static void updateWidget(Context context) { RemoteViews views = buildUpdate(context, -1); // Update specific list of appWidgetIds if given, otherwise default to all final AppWidgetManager gm = AppWidgetManager.getInstance(context); gm.updateAppWidget(THIS_APPWIDGET, views); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/widget/ControlWidgetProvider.java
Java
gpl3
8,262
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Feb 26, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.viewer.map; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.SlidingIndicatorView; import nl.sogeti.android.gpstracker.viewer.map.overlay.OverlayProvider; import org.osmdroid.api.IGeoPoint; import org.osmdroid.tileprovider.tilesource.TileSourceFactory; import org.osmdroid.tileprovider.util.CloudmadeUtil; import org.osmdroid.views.MapView; import org.osmdroid.views.MapView.Projection; import org.osmdroid.views.overlay.MyLocationOverlay; import org.osmdroid.views.overlay.Overlay; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Point; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.BaseAdapter; import android.widget.TextView; import com.google.android.maps.GeoPoint; /** * ???? * * @version $Id:$ * @author rene (c) Feb 26, 2012, Sogeti B.V. */ public class OsmLoggerMap extends Activity implements LoggerMap { protected static final String TAG = "OsmLoggerMap"; LoggerMapHelper mHelper; private MapView mMapView; private TextView[] mSpeedtexts; private TextView mLastGPSSpeedView; private TextView mLastGPSAltitudeView; private TextView mDistanceView; private MyLocationOverlay mMylocation; private Projection mProjecton; /** * Called when the activity is first created. */ @Override protected void onCreate(Bundle load) { super.onCreate(load); setContentView(R.layout.map_osm); mMapView = (MapView) findViewById(R.id.myMapView); TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04), (TextView) findViewById(R.id.speedview03), (TextView) findViewById(R.id.speedview02), (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) }; mSpeedtexts = speeds; mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed); mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude); mDistanceView = (TextView) findViewById(R.id.currentDistance); mHelper = new LoggerMapHelper(this); mMapView.setBuiltInZoomControls(true); mProjecton = mMapView.getProjection(); mHelper.onCreate(load); mMylocation = new MyLocationOverlay(this, mMapView); mMapView.getOverlays().add( new Overlay(this) { @Override protected void draw(Canvas arg0, MapView map, boolean arg2) { Projection projecton = map.getProjection(); mProjecton = projecton; IGeoPoint gepoint = map.getMapCenter(); Point point = projecton.toPixels(gepoint, null); Log.d(TAG, "Found center ("+gepoint.getLatitudeE6()+","+gepoint.getLongitudeE6()+") matching screen point ("+point.x+","+point.y+") "); } } ); } @Override protected void onResume() { super.onResume(); mHelper.onResume(); } @Override protected void onPause() { mHelper.onPause(); super.onPause(); } @Override protected void onDestroy() { mHelper.onDestroy(); super.onDestroy(); } @Override public void onNewIntent(Intent newIntent) { mHelper.onNewIntent(newIntent); } @Override protected void onRestoreInstanceState(Bundle load) { if (load != null) { super.onRestoreInstanceState(load); } mHelper.onRestoreInstanceState(load); } @Override protected void onSaveInstanceState(Bundle save) { super.onSaveInstanceState(save); mHelper.onSaveInstanceState(save); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); mHelper.onCreateOptionsMenu(menu); return result; } @Override public boolean onPrepareOptionsMenu(Menu menu) { mHelper.onPrepareOptionsMenu(menu); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = mHelper.onOptionsItemSelected(item); if( !handled ) { handled = super.onOptionsItemSelected(item); } return handled; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); mHelper.onActivityResult(requestCode, resultCode, intent); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean propagate = true; switch (keyCode) { default: propagate = mHelper.onKeyDown(keyCode, event); if( propagate ) { propagate = super.onKeyDown(keyCode, event); } break; } return propagate; } @Override protected Dialog onCreateDialog(int id) { Dialog dialog = mHelper.onCreateDialog(id); if( dialog == null ) { dialog = super.onCreateDialog(id); } return dialog; } @Override protected void onPrepareDialog(int id, Dialog dialog) { mHelper.onPrepareDialog(id, dialog); super.onPrepareDialog(id, dialog); } /******************************/ /** Own methods **/ /******************************/ private void setTrafficOverlay(boolean b) { SharedPreferences sharedPreferences = mHelper.getPreferences(); Editor editor = sharedPreferences.edit(); editor.putBoolean(Constants.TRAFFIC, b); editor.commit(); } private void setSatelliteOverlay(boolean b) { SharedPreferences sharedPreferences = mHelper.getPreferences(); Editor editor = sharedPreferences.edit(); editor.putBoolean(Constants.SATELLITE, b); editor.commit(); } /******************************/ /** Loggermap methods **/ /******************************/ @Override public void updateOverlays() { SharedPreferences sharedPreferences = mHelper.getPreferences(); int renderer = sharedPreferences.getInt(Constants.OSMBASEOVERLAY, 0); switch( renderer ) { case Constants.OSM_CLOUDMADE: CloudmadeUtil.retrieveCloudmadeKey(this.getApplicationContext()); mMapView.setTileSource(TileSourceFactory.CLOUDMADESTANDARDTILES); break; case Constants.OSM_MAKNIK: mMapView.setTileSource(TileSourceFactory.MAPNIK); break; case Constants.OSM_CYCLE: mMapView.setTileSource(TileSourceFactory.CYCLEMAP); break; default: break; } } @Override public void setDrawingCacheEnabled(boolean b) { findViewById(R.id.mapScreen).setDrawingCacheEnabled(true); } @Override public Activity getActivity() { return this; } @Override public void onLayerCheckedChanged(int checkedId, boolean isChecked) { switch (checkedId) { case R.id.layer_google_satellite: setSatelliteOverlay(true); break; case R.id.layer_google_regular: setSatelliteOverlay(false); break; case R.id.layer_traffic: setTrafficOverlay(isChecked); break; default: break; } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.TRAFFIC)) { updateOverlays(); } else if (key.equals(Constants.SATELLITE)) { updateOverlays(); } } @Override public Bitmap getDrawingCache() { return findViewById(R.id.mapScreen).getDrawingCache(); } @Override public void showMediaDialog(BaseAdapter mediaAdapter) { mHelper.showMediaDialog(mediaAdapter); } public void onDateOverlayChanged() { mMapView.postInvalidate(); } @Override public String getDataSourceId() { return LoggerMapHelper.GOOGLE_PROVIDER; } @Override public boolean isOutsideScreen(GeoPoint lastPoint) { Point out = new Point(); mProjecton.toMapPixels(convertGeoPoint(lastPoint), out); int height = this.mMapView.getHeight(); int width = this.mMapView.getWidth(); return (out.x < 0 || out.y < 0 || out.y > height || out.x > width); } @Override public boolean isNearScreenEdge(GeoPoint lastPoint) { Point out = new Point(); mProjecton.toMapPixels(convertGeoPoint(lastPoint), out); int height = this.mMapView.getHeight(); int width = this.mMapView.getWidth(); return (out.x < width / 4 || out.y < height / 4 || out.x > (width / 4) * 3 || out.y > (height / 4) * 3); } @Override public void executePostponedActions() { // NOOP for Google Maps } @Override public void enableCompass() { mMylocation.enableCompass(); } @Override public void enableMyLocation() { mMylocation.enableMyLocation(); } @Override public void disableMyLocation() { mMylocation.disableMyLocation(); } @Override public void disableCompass() { mMylocation.disableCompass(); } @Override public void setZoom(int zoom) { mMapView.getController().setZoom(zoom); } @Override public void animateTo(GeoPoint storedPoint) { mMapView.getController().animateTo(convertGeoPoint(storedPoint)); } @Override public int getZoomLevel() { return mMapView.getZoomLevel(); } @Override public GeoPoint getMapCenter() { return convertOSMGeoPoint(mMapView.getMapCenter()); } @Override public boolean zoomOut() { return mMapView.getController().zoomOut(); } @Override public boolean zoomIn() { return mMapView.getController().zoomIn(); } @Override public void postInvalidate() { mMapView.postInvalidate(); } @Override public void addOverlay(OverlayProvider overlay) { mMapView.getOverlays().add(overlay.getOSMOverlay()); } @Override public void clearAnimation() { mMapView.clearAnimation(); } @Override public void setCenter(GeoPoint lastPoint) { mMapView.getController().setCenter( convertGeoPoint(lastPoint)); } @Override public int getMaxZoomLevel() { return mMapView.getMaxZoomLevel(); } @Override public GeoPoint fromPixels(int x, int y) { IGeoPoint osmGeopoint = mProjecton.fromPixels(x, y); GeoPoint geopoint = convertOSMGeoPoint(osmGeopoint); return geopoint; } @Override public void toPixels(GeoPoint geoPoint, Point screenPoint) { org.osmdroid.util.GeoPoint localGeopoint = convertGeoPoint(geoPoint); mProjecton.toMapPixels( localGeopoint, screenPoint); } @Override public boolean hasProjection() { return mProjecton != null; } @Override public float metersToEquatorPixels(float float1) { return mProjecton.metersToEquatorPixels(float1); } @Override public TextView[] getSpeedTextViews() { return mSpeedtexts; } @Override public TextView getAltitideTextView() { return mLastGPSAltitudeView; } @Override public TextView getSpeedTextView() { return mLastGPSSpeedView; } @Override public TextView getDistanceTextView() { return mDistanceView; } static org.osmdroid.util.GeoPoint convertGeoPoint( GeoPoint point ) { org.osmdroid.util.GeoPoint geopoint = new org.osmdroid.util.GeoPoint(point.getLatitudeE6(), point.getLongitudeE6()); return geopoint; } static GeoPoint convertOSMGeoPoint( IGeoPoint point ) { return new GeoPoint(point.getLatitudeE6(), point.getLongitudeE6() ); } @Override public void clearOverlays() { mMapView.getOverlayManager().clear(); } @Override public SlidingIndicatorView getScaleIndicatorView() { return (SlidingIndicatorView) findViewById(R.id.scaleindicator); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/map/OsmLoggerMap.java
Java
gpl3
13,328
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Feb 26, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.viewer.map; import nl.sogeti.android.gpstracker.util.Constants; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; /** * ???? * * @version $Id:$ * @author rene (c) Feb 26, 2012, Sogeti B.V. */ public class CommonLoggerMap extends Activity { private static final String TAG = "OGT.CommonLoggerMap"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent myIntent = getIntent(); Intent realIntent; Class<?> mapClass = GoogleLoggerMap.class; int provider = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.MAPPROVIDER, "" + Constants.GOOGLE)).intValue(); switch (provider) { case Constants.GOOGLE: mapClass = GoogleLoggerMap.class; break; case Constants.OSM: mapClass = OsmLoggerMap.class; break; case Constants.MAPQUEST: mapClass = MapQuestLoggerMap.class; break; default: mapClass = GoogleLoggerMap.class; Log.e(TAG, "Fault in value " + provider + " as MapProvider, defaulting to Google Maps."); break; } if( myIntent != null ) { realIntent = new Intent(myIntent.getAction(), myIntent.getData(), this, mapClass); realIntent.putExtras(myIntent); } else { realIntent = new Intent(this, mapClass); realIntent.putExtras(myIntent); } startActivity(realIntent); finish(); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/map/CommonLoggerMap.java
Java
gpl3
2,490
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Feb 26, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.viewer.map; import java.util.concurrent.Semaphore; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.ControlTracking; import nl.sogeti.android.gpstracker.actions.InsertNote; import nl.sogeti.android.gpstracker.actions.ShareTrack; import nl.sogeti.android.gpstracker.actions.Statistics; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.Segments; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.SlidingIndicatorView; import nl.sogeti.android.gpstracker.util.UnitsI18n; import nl.sogeti.android.gpstracker.viewer.About; import nl.sogeti.android.gpstracker.viewer.ApplicationPreferenceActivity; import nl.sogeti.android.gpstracker.viewer.TrackList; import nl.sogeti.android.gpstracker.viewer.map.overlay.BitmapSegmentsOverlay; import nl.sogeti.android.gpstracker.viewer.map.overlay.SegmentRendering; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Bitmap; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.Gallery; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.google.android.maps.GeoPoint; /** * ???? * * @version $Id:$ * @author rene (c) Feb 26, 2012, Sogeti B.V. */ public class LoggerMapHelper { public static final String OSM_PROVIDER = "OSM"; public static final String GOOGLE_PROVIDER = "GOOGLE"; public static final String MAPQUEST_PROVIDER = "MAPQUEST"; private static final String INSTANCE_E6LONG = "e6long"; private static final String INSTANCE_E6LAT = "e6lat"; private static final String INSTANCE_ZOOM = "zoom"; private static final String INSTANCE_AVGSPEED = "averagespeed"; private static final String INSTANCE_HEIGHT = "averageheight"; private static final String INSTANCE_TRACK = "track"; private static final String INSTANCE_SPEED = "speed"; private static final String INSTANCE_ALTITUDE = "altitude"; private static final String INSTANCE_DISTANCE = "distance"; private static final int ZOOM_LEVEL = 16; // MENU'S private static final int MENU_SETTINGS = 1; private static final int MENU_TRACKING = 2; private static final int MENU_TRACKLIST = 3; private static final int MENU_STATS = 4; private static final int MENU_ABOUT = 5; private static final int MENU_LAYERS = 6; private static final int MENU_NOTE = 7; private static final int MENU_SHARE = 13; private static final int MENU_CONTRIB = 14; private static final int DIALOG_NOTRACK = 24; private static final int DIALOG_LAYERS = 31; private static final int DIALOG_URIS = 34; private static final int DIALOG_CONTRIB = 35; private static final String TAG = "OGT.LoggerMap"; private double mAverageSpeed = 33.33d / 3d; private double mAverageHeight = 33.33d / 3d; private long mTrackId = -1; private long mLastSegment = -1; private UnitsI18n mUnits; private WakeLock mWakeLock = null; private SharedPreferences mSharedPreferences; private GPSLoggerServiceManager mLoggerServiceManager; private SegmentRendering mLastSegmentOverlay; private BaseAdapter mMediaAdapter; private Handler mHandler; private ContentObserver mTrackSegmentsObserver; private ContentObserver mSegmentWaypointsObserver; private ContentObserver mTrackMediasObserver; private DialogInterface.OnClickListener mNoTrackDialogListener; private OnItemSelectedListener mGalerySelectListener; private Uri mSelected; private OnClickListener mNoteSelectDialogListener; private OnCheckedChangeListener mCheckedChangeListener; private android.widget.RadioGroup.OnCheckedChangeListener mGroupCheckedChangeListener; private OnSharedPreferenceChangeListener mSharedPreferenceChangeListener; private UnitsI18n.UnitsChangeListener mUnitsChangeListener; /** * Run after the ServiceManager completes the binding to the remote service */ private Runnable mServiceConnected; private Runnable speedCalculator; private Runnable heightCalculator; private LoggerMap mLoggerMap; private BitmapSegmentsOverlay mBitmapSegmentsOverlay; private float mSpeed; private double mAltitude; private float mDistance; public LoggerMapHelper(LoggerMap loggerMap) { mLoggerMap = loggerMap; } /** * Called when the activity is first created. */ protected void onCreate(Bundle load) { mLoggerMap.setDrawingCacheEnabled(true); mUnits = new UnitsI18n(mLoggerMap.getActivity()); mLoggerServiceManager = new GPSLoggerServiceManager(mLoggerMap.getActivity()); final Semaphore calulatorSemaphore = new Semaphore(0); Thread calulator = new Thread("OverlayCalculator") { @Override public void run() { Looper.prepare(); mHandler = new Handler(); calulatorSemaphore.release(); Looper.loop(); } }; calulator.start(); try { calulatorSemaphore.acquire(); } catch (InterruptedException e) { Log.e(TAG, "Failed waiting for a semaphore", e); } mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mLoggerMap.getActivity()); mBitmapSegmentsOverlay = new BitmapSegmentsOverlay(mLoggerMap, mHandler); createListeners(); onRestoreInstanceState(load); mLoggerMap.updateOverlays(); } protected void onResume() { updateMapProvider(); mLoggerServiceManager.startup(mLoggerMap.getActivity(), mServiceConnected); mSharedPreferences.registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener); mUnits.setUnitsChangeListener(mUnitsChangeListener); updateTitleBar(); updateBlankingBehavior(); if (mTrackId >= 0) { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Uri trackUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments"); Uri lastSegmentUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mLastSegment + "/waypoints"); Uri mediaUri = ContentUris.withAppendedId(Media.CONTENT_URI, mTrackId); resolver.unregisterContentObserver(this.mTrackSegmentsObserver); resolver.unregisterContentObserver(this.mSegmentWaypointsObserver); resolver.unregisterContentObserver(this.mTrackMediasObserver); resolver.registerContentObserver(trackUri, false, this.mTrackSegmentsObserver); resolver.registerContentObserver(lastSegmentUri, true, this.mSegmentWaypointsObserver); resolver.registerContentObserver(mediaUri, true, this.mTrackMediasObserver); } updateDataOverlays(); updateSpeedColoring(); updateSpeedDisplayVisibility(); updateAltitudeDisplayVisibility(); updateDistanceDisplayVisibility(); updateCompassDisplayVisibility(); updateLocationDisplayVisibility(); updateTrackNumbers(); mLoggerMap.executePostponedActions(); } protected void onPause() { if (this.mWakeLock != null && this.mWakeLock.isHeld()) { this.mWakeLock.release(); Log.w(TAG, "onPause(): Released lock to keep screen on!"); } mLoggerMap.clearOverlays(); mBitmapSegmentsOverlay.clearSegments(); mLastSegmentOverlay = null; ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); resolver.unregisterContentObserver(this.mTrackSegmentsObserver); resolver.unregisterContentObserver(this.mSegmentWaypointsObserver); resolver.unregisterContentObserver(this.mTrackMediasObserver); mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this.mSharedPreferenceChangeListener); mUnits.setUnitsChangeListener(null); mLoggerMap.disableMyLocation(); mLoggerMap.disableCompass(); this.mLoggerServiceManager.shutdown(mLoggerMap.getActivity()); } protected void onDestroy() { mLoggerMap.clearOverlays(); mHandler.post(new Runnable() { @Override public void run() { Looper.myLooper().quit(); } }); if (mWakeLock != null && mWakeLock.isHeld()) { mWakeLock.release(); Log.w(TAG, "onDestroy(): Released lock to keep screen on!"); } if (mLoggerServiceManager.getLoggingState() == Constants.STOPPED) { mLoggerMap.getActivity().stopService(new Intent(Constants.SERVICENAME)); } mUnits = null; } public void onNewIntent(Intent newIntent) { Uri data = newIntent.getData(); if (data != null) { moveToTrack(Long.parseLong(data.getLastPathSegment()), true); } } protected void onRestoreInstanceState(Bundle load) { Uri data = mLoggerMap.getActivity().getIntent().getData(); if (load != null && load.containsKey(INSTANCE_TRACK)) // 1st method: track from a previous instance of this activity { long loadTrackId = load.getLong(INSTANCE_TRACK); moveToTrack(loadTrackId, false); if (load.containsKey(INSTANCE_AVGSPEED)) { mAverageSpeed = load.getDouble(INSTANCE_AVGSPEED); } if (load.containsKey(INSTANCE_HEIGHT)) { mAverageHeight = load.getDouble(INSTANCE_HEIGHT); } if( load.containsKey(INSTANCE_SPEED)) { mSpeed = load.getFloat(INSTANCE_SPEED); } if( load.containsKey(INSTANCE_ALTITUDE)) { mAltitude = load.getDouble(INSTANCE_HEIGHT); } if( load.containsKey(INSTANCE_DISTANCE)) { mDistance = load.getFloat(INSTANCE_DISTANCE); } } else if (data != null) // 2nd method: track ordered to make { long loadTrackId = Long.parseLong(data.getLastPathSegment()); moveToTrack(loadTrackId, true); } else // 3rd method: just try the last track { moveToLastTrack(); } if (load != null && load.containsKey(INSTANCE_ZOOM)) { mLoggerMap.setZoom(load.getInt(INSTANCE_ZOOM)); } else { mLoggerMap.setZoom(ZOOM_LEVEL); } if (load != null && load.containsKey(INSTANCE_E6LAT) && load.containsKey(INSTANCE_E6LONG)) { GeoPoint storedPoint = new GeoPoint(load.getInt(INSTANCE_E6LAT), load.getInt(INSTANCE_E6LONG)); mLoggerMap.animateTo(storedPoint); } else { GeoPoint lastPoint = getLastTrackPoint(); mLoggerMap.animateTo(lastPoint); } } protected void onSaveInstanceState(Bundle save) { save.putLong(INSTANCE_TRACK, this.mTrackId); save.putDouble(INSTANCE_AVGSPEED, mAverageSpeed); save.putDouble(INSTANCE_HEIGHT, mAverageHeight); save.putInt(INSTANCE_ZOOM, mLoggerMap.getZoomLevel()); save.putFloat(INSTANCE_SPEED, mSpeed); save.putDouble(INSTANCE_ALTITUDE, mAltitude); save.putFloat(INSTANCE_DISTANCE, mDistance); GeoPoint point = mLoggerMap.getMapCenter(); save.putInt(INSTANCE_E6LAT, point.getLatitudeE6()); save.putInt(INSTANCE_E6LONG, point.getLongitudeE6()); } public boolean onKeyDown(int keyCode, KeyEvent event) { boolean propagate = true; switch (keyCode) { case KeyEvent.KEYCODE_T: propagate = mLoggerMap.zoomIn(); propagate = false; break; case KeyEvent.KEYCODE_G: propagate = mLoggerMap.zoomOut(); propagate = false; break; case KeyEvent.KEYCODE_F: moveToTrack(this.mTrackId - 1, true); propagate = false; break; case KeyEvent.KEYCODE_H: moveToTrack(this.mTrackId + 1, true); propagate = false; break; } return propagate; } private void setSpeedOverlay(boolean b) { Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.SPEED, b); editor.commit(); } private void setAltitudeOverlay(boolean b) { Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.ALTITUDE, b); editor.commit(); } private void setDistanceOverlay(boolean b) { Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.DISTANCE, b); editor.commit(); } private void setCompassOverlay(boolean b) { Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.COMPASS, b); editor.commit(); } private void setLocationOverlay(boolean b) { Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.LOCATION, b); editor.commit(); } private void setOsmBaseOverlay(int b) { Editor editor = mSharedPreferences.edit(); editor.putInt(Constants.OSMBASEOVERLAY, b); editor.commit(); } private void createListeners() { /******************************************************* * 8 Runnable listener actions */ speedCalculator = new Runnable() { @Override public void run() { double avgspeed = 0.0; ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Cursor waypointsCursor = null; try { waypointsCursor = resolver.query(Uri.withAppendedPath(Tracks.CONTENT_URI, LoggerMapHelper.this.mTrackId + "/waypoints"), new String[] { "avg(" + Waypoints.SPEED + ")", "max(" + Waypoints.SPEED + ")" }, null, null, null); if (waypointsCursor != null && waypointsCursor.moveToLast()) { double average = waypointsCursor.getDouble(0); double maxBasedAverage = waypointsCursor.getDouble(1) / 2; avgspeed = Math.min(average, maxBasedAverage); } if (avgspeed < 2) { avgspeed = 5.55d / 2; } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } mAverageSpeed = avgspeed; mLoggerMap.getActivity().runOnUiThread(new Runnable() { @Override public void run() { updateSpeedColoring(); } }); } }; heightCalculator = new Runnable() { @Override public void run() { double avgHeight = 0.0; ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Cursor waypointsCursor = null; try { waypointsCursor = resolver.query(Uri.withAppendedPath(Tracks.CONTENT_URI, LoggerMapHelper.this.mTrackId + "/waypoints"), new String[] { "avg(" + Waypoints.ALTITUDE + ")", "max(" + Waypoints.ALTITUDE + ")" }, null, null, null); if (waypointsCursor != null && waypointsCursor.moveToLast()) { double average = waypointsCursor.getDouble(0); double maxBasedAverage = waypointsCursor.getDouble(1) / 2; avgHeight = Math.min(average, maxBasedAverage); } } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } mAverageHeight = avgHeight; mLoggerMap.getActivity().runOnUiThread(new Runnable() { @Override public void run() { updateSpeedColoring(); } }); } }; mServiceConnected = new Runnable() { @Override public void run() { updateBlankingBehavior(); } }; /******************************************************* * 8 Various dialog listeners */ mGalerySelectListener = new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView< ? > parent, View view, int pos, long id) { mSelected = (Uri) parent.getSelectedItem(); } @Override public void onNothingSelected(AdapterView< ? > arg0) { mSelected = null; } }; mNoteSelectDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SegmentRendering.handleMedia(mLoggerMap.getActivity(), mSelected); mSelected = null; } }; mGroupCheckedChangeListener = new android.widget.RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.layer_osm_cloudmade: setOsmBaseOverlay(Constants.OSM_CLOUDMADE); break; case R.id.layer_osm_maknik: setOsmBaseOverlay(Constants.OSM_MAKNIK); break; case R.id.layer_osm_bicycle: setOsmBaseOverlay(Constants.OSM_CYCLE); break; default: mLoggerMap.onLayerCheckedChanged(checkedId, true); break; } } }; mCheckedChangeListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int checkedId; checkedId = buttonView.getId(); switch (checkedId) { case R.id.layer_speed: setSpeedOverlay(isChecked); break; case R.id.layer_altitude: setAltitudeOverlay(isChecked); break; case R.id.layer_distance: setDistanceOverlay(isChecked); break; case R.id.layer_compass: setCompassOverlay(isChecked); break; case R.id.layer_location: setLocationOverlay(isChecked); break; default: mLoggerMap.onLayerCheckedChanged(checkedId, isChecked); break; } } }; mNoTrackDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Log.d( TAG, "mNoTrackDialogListener" + which); Intent tracklistIntent = new Intent(mLoggerMap.getActivity(), TrackList.class); tracklistIntent.putExtra(Tracks._ID, mTrackId); mLoggerMap.getActivity().startActivityForResult(tracklistIntent, MENU_TRACKLIST); } }; /** * Listeners to events outside this mapview */ mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.TRACKCOLORING)) { mAverageSpeed = 0.0; mAverageHeight = 0.0; updateSpeedColoring(); } else if (key.equals(Constants.DISABLEBLANKING) || key.equals(Constants.DISABLEDIMMING)) { updateBlankingBehavior(); } else if (key.equals(Constants.SPEED)) { updateSpeedDisplayVisibility(); } else if (key.equals(Constants.ALTITUDE)) { updateAltitudeDisplayVisibility(); } else if (key.equals(Constants.DISTANCE)) { updateDistanceDisplayVisibility(); } else if (key.equals(Constants.COMPASS)) { updateCompassDisplayVisibility(); } else if (key.equals(Constants.LOCATION)) { updateLocationDisplayVisibility(); } else if (key.equals(Constants.MAPPROVIDER)) { updateMapProvider(); } else if (key.equals(Constants.OSMBASEOVERLAY)) { mLoggerMap.updateOverlays(); } else { mLoggerMap.onSharedPreferenceChanged(sharedPreferences, key); } } }; mTrackMediasObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { if (mLastSegmentOverlay != null) { mLastSegmentOverlay.calculateMedia(); } } else { Log.w(TAG, "mTrackMediasObserver skipping change on " + mLastSegment); } } }; mTrackSegmentsObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { updateDataOverlays(); } else { Log.w(TAG, "mTrackSegmentsObserver skipping change on " + mLastSegment); } } }; mSegmentWaypointsObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { updateTrackNumbers(); if (mLastSegmentOverlay != null) { moveActiveViewWindow(); updateMapProviderAdministration(mLoggerMap.getDataSourceId()); } else { Log.e(TAG, "Error the last segment changed but it is not on screen! " + mLastSegment); } } else { Log.w(TAG, "mSegmentWaypointsObserver skipping change on " + mLastSegment); } } }; mUnitsChangeListener = new UnitsI18n.UnitsChangeListener() { @Override public void onUnitsChange() { mAverageSpeed = 0.0; mAverageHeight = 0.0; updateTrackNumbers(); updateSpeedColoring(); } }; } public void onCreateOptionsMenu(Menu menu) { menu.add(ContextMenu.NONE, MENU_TRACKING, ContextMenu.NONE, R.string.menu_tracking).setIcon(R.drawable.ic_menu_movie).setAlphabeticShortcut('T'); menu.add(ContextMenu.NONE, MENU_LAYERS, ContextMenu.NONE, R.string.menu_showLayers).setIcon(R.drawable.ic_menu_mapmode).setAlphabeticShortcut('L'); menu.add(ContextMenu.NONE, MENU_NOTE, ContextMenu.NONE, R.string.menu_insertnote).setIcon(R.drawable.ic_menu_myplaces); menu.add(ContextMenu.NONE, MENU_STATS, ContextMenu.NONE, R.string.menu_statistics).setIcon(R.drawable.ic_menu_picture).setAlphabeticShortcut('S'); menu.add(ContextMenu.NONE, MENU_SHARE, ContextMenu.NONE, R.string.menu_shareTrack).setIcon(R.drawable.ic_menu_share).setAlphabeticShortcut('I'); // More menu.add(ContextMenu.NONE, MENU_TRACKLIST, ContextMenu.NONE, R.string.menu_tracklist).setIcon(R.drawable.ic_menu_show_list).setAlphabeticShortcut('P'); menu.add(ContextMenu.NONE, MENU_SETTINGS, ContextMenu.NONE, R.string.menu_settings).setIcon(R.drawable.ic_menu_preferences).setAlphabeticShortcut('C'); menu.add(ContextMenu.NONE, MENU_ABOUT, ContextMenu.NONE, R.string.menu_about).setIcon(R.drawable.ic_menu_info_details).setAlphabeticShortcut('A'); menu.add(ContextMenu.NONE, MENU_CONTRIB, ContextMenu.NONE, R.string.menu_contrib).setIcon(R.drawable.ic_menu_allfriends); } public void onPrepareOptionsMenu(Menu menu) { MenuItem noteMenu = menu.findItem(MENU_NOTE); noteMenu.setEnabled(mLoggerServiceManager.isMediaPrepared()); MenuItem shareMenu = menu.findItem(MENU_SHARE); shareMenu.setEnabled(mTrackId >= 0); } public boolean onOptionsItemSelected(MenuItem item) { boolean handled = false; Uri trackUri; Intent intent; switch (item.getItemId()) { case MENU_TRACKING: intent = new Intent(mLoggerMap.getActivity(), ControlTracking.class); mLoggerMap.getActivity().startActivityForResult(intent, MENU_TRACKING); handled = true; break; case MENU_LAYERS: mLoggerMap.getActivity().showDialog(DIALOG_LAYERS); handled = true; break; case MENU_NOTE: intent = new Intent(mLoggerMap.getActivity(), InsertNote.class); mLoggerMap.getActivity().startActivityForResult(intent, MENU_NOTE); handled = true; break; case MENU_SETTINGS: intent = new Intent(mLoggerMap.getActivity(), ApplicationPreferenceActivity.class); mLoggerMap.getActivity().startActivity(intent); handled = true; break; case MENU_TRACKLIST: intent = new Intent(mLoggerMap.getActivity(), TrackList.class); intent.putExtra(Tracks._ID, this.mTrackId); mLoggerMap.getActivity().startActivityForResult(intent, MENU_TRACKLIST); handled = true; break; case MENU_STATS: if (this.mTrackId >= 0) { intent = new Intent(mLoggerMap.getActivity(), Statistics.class); trackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId); intent.setData(trackUri); mLoggerMap.getActivity().startActivity(intent); break; } else { mLoggerMap.getActivity().showDialog(DIALOG_NOTRACK); } handled = true; break; case MENU_ABOUT: intent = new Intent(mLoggerMap.getActivity(), About.class); mLoggerMap.getActivity().startActivity(intent); break; case MENU_SHARE: intent = new Intent(Intent.ACTION_RUN); trackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId); intent.setDataAndType(trackUri, Tracks.CONTENT_ITEM_TYPE); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Bitmap bm = mLoggerMap.getDrawingCache(); Uri screenStreamUri = ShareTrack.storeScreenBitmap(bm); intent.putExtra(Intent.EXTRA_STREAM, screenStreamUri); mLoggerMap.getActivity().startActivityForResult(Intent.createChooser(intent, mLoggerMap.getActivity().getString(R.string.share_track)), MENU_SHARE); handled = true; break; case MENU_CONTRIB: mLoggerMap.getActivity().showDialog(DIALOG_CONTRIB); default: handled = false; break; } return handled; } protected Dialog onCreateDialog(int id) { Dialog dialog = null; LayoutInflater factory = null; View view = null; Builder builder = null; switch (id) { case DIALOG_LAYERS: builder = new AlertDialog.Builder(mLoggerMap.getActivity()); factory = LayoutInflater.from(mLoggerMap.getActivity()); view = factory.inflate(R.layout.layerdialog, null); CheckBox traffic = (CheckBox) view.findViewById(R.id.layer_traffic); CheckBox speed = (CheckBox) view.findViewById(R.id.layer_speed); CheckBox altitude = (CheckBox) view.findViewById(R.id.layer_altitude); CheckBox distance = (CheckBox) view.findViewById(R.id.layer_distance); CheckBox compass = (CheckBox) view.findViewById(R.id.layer_compass); CheckBox location = (CheckBox) view.findViewById(R.id.layer_location); ((RadioGroup) view.findViewById(R.id.google_backgrounds)).setOnCheckedChangeListener(mGroupCheckedChangeListener); ((RadioGroup) view.findViewById(R.id.osm_backgrounds)).setOnCheckedChangeListener(mGroupCheckedChangeListener); traffic.setOnCheckedChangeListener(mCheckedChangeListener); speed.setOnCheckedChangeListener(mCheckedChangeListener); altitude.setOnCheckedChangeListener(mCheckedChangeListener); distance.setOnCheckedChangeListener(mCheckedChangeListener); compass.setOnCheckedChangeListener(mCheckedChangeListener); location.setOnCheckedChangeListener(mCheckedChangeListener); builder.setTitle(R.string.dialog_layer_title).setIcon(android.R.drawable.ic_dialog_map).setPositiveButton(R.string.btn_okay, null).setView(view); dialog = builder.create(); return dialog; case DIALOG_NOTRACK: builder = new AlertDialog.Builder(mLoggerMap.getActivity()); builder.setTitle(R.string.dialog_notrack_title).setMessage(R.string.dialog_notrack_message).setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_selecttrack, mNoTrackDialogListener).setNegativeButton(R.string.btn_cancel, null); dialog = builder.create(); return dialog; case DIALOG_URIS: builder = new AlertDialog.Builder(mLoggerMap.getActivity()); factory = LayoutInflater.from(mLoggerMap.getActivity()); view = factory.inflate(R.layout.mediachooser, null); builder.setTitle(R.string.dialog_select_media_title).setMessage(R.string.dialog_select_media_message).setIcon(android.R.drawable.ic_dialog_alert) .setNegativeButton(R.string.btn_cancel, null).setPositiveButton(R.string.btn_okay, mNoteSelectDialogListener).setView(view); dialog = builder.create(); return dialog; case DIALOG_CONTRIB: builder = new AlertDialog.Builder(mLoggerMap.getActivity()); factory = LayoutInflater.from(mLoggerMap.getActivity()); view = factory.inflate(R.layout.contrib, null); TextView contribView = (TextView) view.findViewById(R.id.contrib_view); contribView.setText(R.string.dialog_contrib_message); builder.setTitle(R.string.dialog_contrib_title).setView(view).setIcon(android.R.drawable.ic_dialog_email) .setPositiveButton(R.string.btn_okay, null); dialog = builder.create(); return dialog; default: return null; } } protected void onPrepareDialog(int id, Dialog dialog) { RadioButton satellite; RadioButton regular; RadioButton cloudmade; RadioButton mapnik; RadioButton cycle; switch (id) { case DIALOG_LAYERS: satellite = (RadioButton) dialog.findViewById(R.id.layer_google_satellite); regular = (RadioButton) dialog.findViewById(R.id.layer_google_regular); satellite.setChecked(mSharedPreferences.getBoolean(Constants.SATELLITE, false)); regular.setChecked(!mSharedPreferences.getBoolean(Constants.SATELLITE, false)); int osmbase = mSharedPreferences.getInt(Constants.OSMBASEOVERLAY, 0); cloudmade = (RadioButton) dialog.findViewById(R.id.layer_osm_cloudmade); mapnik = (RadioButton) dialog.findViewById(R.id.layer_osm_maknik); cycle = (RadioButton) dialog.findViewById(R.id.layer_osm_bicycle); cloudmade.setChecked(osmbase == Constants.OSM_CLOUDMADE); mapnik.setChecked(osmbase == Constants.OSM_MAKNIK); cycle.setChecked(osmbase == Constants.OSM_CYCLE); ((CheckBox) dialog.findViewById(R.id.layer_traffic)).setChecked(mSharedPreferences.getBoolean(Constants.TRAFFIC, false)); ((CheckBox) dialog.findViewById(R.id.layer_speed)).setChecked(mSharedPreferences.getBoolean(Constants.SPEED, false)); ((CheckBox) dialog.findViewById(R.id.layer_altitude)).setChecked(mSharedPreferences.getBoolean(Constants.ALTITUDE, false)); ((CheckBox) dialog.findViewById(R.id.layer_distance)).setChecked(mSharedPreferences.getBoolean(Constants.DISTANCE, false)); ((CheckBox) dialog.findViewById(R.id.layer_compass)).setChecked(mSharedPreferences.getBoolean(Constants.COMPASS, false)); ((CheckBox) dialog.findViewById(R.id.layer_location)).setChecked(mSharedPreferences.getBoolean(Constants.LOCATION, false)); int provider = Integer.valueOf(mSharedPreferences.getString(Constants.MAPPROVIDER, "" + Constants.GOOGLE)).intValue(); switch (provider) { case Constants.GOOGLE: dialog.findViewById(R.id.google_backgrounds).setVisibility(View.VISIBLE); dialog.findViewById(R.id.osm_backgrounds).setVisibility(View.GONE); dialog.findViewById(R.id.shared_layers).setVisibility(View.VISIBLE); dialog.findViewById(R.id.google_overlays).setVisibility(View.VISIBLE); break; case Constants.OSM: dialog.findViewById(R.id.osm_backgrounds).setVisibility(View.VISIBLE); dialog.findViewById(R.id.google_backgrounds).setVisibility(View.GONE); dialog.findViewById(R.id.shared_layers).setVisibility(View.VISIBLE); dialog.findViewById(R.id.google_overlays).setVisibility(View.GONE); break; default: dialog.findViewById(R.id.osm_backgrounds).setVisibility(View.GONE); dialog.findViewById(R.id.google_backgrounds).setVisibility(View.GONE); dialog.findViewById(R.id.shared_layers).setVisibility(View.VISIBLE); dialog.findViewById(R.id.google_overlays).setVisibility(View.GONE); break; } break; case DIALOG_URIS: Gallery gallery = (Gallery) dialog.findViewById(R.id.gallery); gallery.setAdapter(mMediaAdapter); gallery.setOnItemSelectedListener(mGalerySelectListener); default: break; } } protected void onActivityResult(int requestCode, int resultCode, Intent intent) { Uri trackUri; long trackId; switch (requestCode) { case MENU_TRACKLIST: if (resultCode == Activity.RESULT_OK) { trackUri = intent.getData(); trackId = Long.parseLong(trackUri.getLastPathSegment()); moveToTrack(trackId, true); } break; case MENU_TRACKING: if (resultCode == Activity.RESULT_OK) { trackUri = intent.getData(); if (trackUri != null) { trackId = Long.parseLong(trackUri.getLastPathSegment()); moveToTrack(trackId, true); } } break; case MENU_SHARE: ShareTrack.clearScreenBitmap(); break; default: Log.e(TAG, "Returned form unknow activity: " + requestCode); break; } } private void updateTitleBar() { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Cursor trackCursor = null; try { trackCursor = resolver.query(ContentUris.withAppendedId(Tracks.CONTENT_URI, this.mTrackId), new String[] { Tracks.NAME }, null, null, null); if (trackCursor != null && trackCursor.moveToLast()) { String trackName = trackCursor.getString(0); mLoggerMap.getActivity().setTitle(mLoggerMap.getActivity().getString(R.string.app_name) + ": " + trackName); } } finally { if (trackCursor != null) { trackCursor.close(); } } } private void updateMapProvider() { Class< ? > mapClass = null; int provider = Integer.valueOf(mSharedPreferences.getString(Constants.MAPPROVIDER, "" + Constants.GOOGLE)).intValue(); switch (provider) { case Constants.GOOGLE: mapClass = GoogleLoggerMap.class; break; case Constants.OSM: mapClass = OsmLoggerMap.class; break; case Constants.MAPQUEST: mapClass = MapQuestLoggerMap.class; break; default: mapClass = GoogleLoggerMap.class; Log.e(TAG, "Fault in value " + provider + " as MapProvider, defaulting to Google Maps."); break; } if (mapClass != mLoggerMap.getActivity().getClass()) { Intent myIntent = mLoggerMap.getActivity().getIntent(); Intent realIntent; if (myIntent != null) { realIntent = new Intent(myIntent.getAction(), myIntent.getData(), mLoggerMap.getActivity(), mapClass); realIntent.putExtras(myIntent); } else { realIntent = new Intent(mLoggerMap.getActivity(), mapClass); realIntent.putExtras(myIntent); } mLoggerMap.getActivity().startActivity(realIntent); mLoggerMap.getActivity().finish(); } } protected void updateMapProviderAdministration(String provider) { mLoggerServiceManager.storeDerivedDataSource(provider); } private void updateBlankingBehavior() { boolean disableblanking = mSharedPreferences.getBoolean(Constants.DISABLEBLANKING, false); boolean disabledimming = mSharedPreferences.getBoolean(Constants.DISABLEDIMMING, false); if (disableblanking) { if (mWakeLock == null) { PowerManager pm = (PowerManager) mLoggerMap.getActivity().getSystemService(Context.POWER_SERVICE); if (disabledimming) { mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG); } else { mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG); } } if (mLoggerServiceManager.getLoggingState() == Constants.LOGGING && !mWakeLock.isHeld()) { mWakeLock.acquire(); Log.w(TAG, "Acquired lock to keep screen on!"); } } } private void updateSpeedColoring() { int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "3")).intValue(); View speedbar = mLoggerMap.getActivity().findViewById(R.id.speedbar); SlidingIndicatorView scaleIndicator = mLoggerMap.getScaleIndicatorView(); TextView[] speedtexts = mLoggerMap.getSpeedTextViews(); switch (trackColoringMethod) { case SegmentRendering.DRAW_MEASURED: case SegmentRendering.DRAW_CALCULATED: // mAverageSpeed is set to 0 if unknown or to trigger an recalculation here if (mAverageSpeed == 0.0) { mHandler.removeCallbacks(speedCalculator); mHandler.post(speedCalculator); } else { drawSpeedTexts(); speedtexts = mLoggerMap.getSpeedTextViews(); speedbar.setVisibility(View.VISIBLE); scaleIndicator.setVisibility(View.VISIBLE); for (int i = 0; i < speedtexts.length; i++) { speedtexts[i].setVisibility(View.VISIBLE); } } break; case SegmentRendering.DRAW_DOTS: case SegmentRendering.DRAW_GREEN: case SegmentRendering.DRAW_RED: speedbar.setVisibility(View.INVISIBLE); scaleIndicator.setVisibility(View.INVISIBLE); for (int i = 0; i < speedtexts.length; i++) { speedtexts[i].setVisibility(View.INVISIBLE); } break; case SegmentRendering.DRAW_HEIGHT: if (mAverageHeight == 0.0) { mHandler.removeCallbacks(heightCalculator); mHandler.post(heightCalculator); } else { drawHeightTexts(); speedtexts = mLoggerMap.getSpeedTextViews(); speedbar.setVisibility(View.VISIBLE); scaleIndicator.setVisibility(View.VISIBLE); for (int i = 0; i < speedtexts.length; i++) { speedtexts[i].setVisibility(View.VISIBLE); } } break; default: break; } mBitmapSegmentsOverlay.setTrackColoringMethod(trackColoringMethod, mAverageSpeed, mAverageHeight); } private void updateSpeedDisplayVisibility() { boolean showspeed = mSharedPreferences.getBoolean(Constants.SPEED, false); TextView lastGPSSpeedView = mLoggerMap.getSpeedTextView(); if (showspeed) { lastGPSSpeedView.setVisibility(View.VISIBLE); } else { lastGPSSpeedView.setVisibility(View.GONE); } updateScaleDisplayVisibility(); } private void updateAltitudeDisplayVisibility() { boolean showaltitude = mSharedPreferences.getBoolean(Constants.ALTITUDE, false); TextView lastGPSAltitudeView = mLoggerMap.getAltitideTextView(); if (showaltitude) { lastGPSAltitudeView.setVisibility(View.VISIBLE); } else { lastGPSAltitudeView.setVisibility(View.GONE); } updateScaleDisplayVisibility(); } private void updateScaleDisplayVisibility() { SlidingIndicatorView scaleIndicator = mLoggerMap.getScaleIndicatorView(); boolean showspeed = mSharedPreferences.getBoolean(Constants.SPEED, false); boolean showaltitude = mSharedPreferences.getBoolean(Constants.ALTITUDE, false); int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "3")).intValue(); switch (trackColoringMethod) { case SegmentRendering.DRAW_MEASURED: case SegmentRendering.DRAW_CALCULATED: if( showspeed ) { scaleIndicator.setVisibility(View.VISIBLE); } else { scaleIndicator.setVisibility(View.GONE); } break; case SegmentRendering.DRAW_HEIGHT: default: if( showaltitude ) { scaleIndicator.setVisibility(View.VISIBLE); } else { scaleIndicator.setVisibility(View.GONE); } break; } } private void updateDistanceDisplayVisibility() { boolean showdistance = mSharedPreferences.getBoolean(Constants.DISTANCE, false); TextView distanceView = mLoggerMap.getDistanceTextView(); if (showdistance) { distanceView.setVisibility(View.VISIBLE); } else { distanceView.setVisibility(View.GONE); } } private void updateCompassDisplayVisibility() { boolean compass = mSharedPreferences.getBoolean(Constants.COMPASS, false); if (compass) { mLoggerMap.enableCompass(); } else { mLoggerMap.disableCompass(); } } private void updateLocationDisplayVisibility() { boolean location = mSharedPreferences.getBoolean(Constants.LOCATION, false); if (location) { mLoggerMap.enableMyLocation(); } else { mLoggerMap.disableMyLocation(); } } /** * Retrieves the numbers of the measured speed and altitude from the most * recent waypoint and updates UI components with this latest bit of * information. */ private void updateTrackNumbers() { Location lastWaypoint = mLoggerServiceManager.getLastWaypoint(); UnitsI18n units = mUnits; if (lastWaypoint != null && units != null) { // Speed number mSpeed = lastWaypoint.getSpeed(); mAltitude = lastWaypoint.getAltitude(); mDistance = mLoggerServiceManager.getTrackedDistance(); } //Distance number double distance = units.conversionFromMeter(mDistance); String distanceText = String.format("%.2f %s", distance, units.getDistanceUnit()); TextView mDistanceView = mLoggerMap.getDistanceTextView(); mDistanceView.setText(distanceText); //Speed number double speed = units.conversionFromMetersPerSecond(mSpeed); String speedText = units.formatSpeed(speed, false); TextView lastGPSSpeedView = mLoggerMap.getSpeedTextView(); lastGPSSpeedView.setText(speedText); //Altitude number double altitude = units.conversionFromMeterToHeight(mAltitude); String altitudeText = String.format("%.0f %s", altitude, units.getHeightUnit()); TextView mLastGPSAltitudeView = mLoggerMap.getAltitideTextView(); mLastGPSAltitudeView.setText(altitudeText); // Slider indicator SlidingIndicatorView currentScaleIndicator = mLoggerMap.getScaleIndicatorView(); int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "3")).intValue(); if( trackColoringMethod == SegmentRendering.DRAW_MEASURED || trackColoringMethod == SegmentRendering.DRAW_CALCULATED) { currentScaleIndicator.setValue((float) speed); // Speed color bar and reference numbers if (speed > 2 * mAverageSpeed ) { mAverageSpeed = 0.0; updateSpeedColoring(); mBitmapSegmentsOverlay.scheduleRecalculation(); } } else if(trackColoringMethod == SegmentRendering.DRAW_HEIGHT) { currentScaleIndicator.setValue((float) altitude); // Speed color bar and reference numbers if (altitude > 2 * mAverageHeight ) { mAverageHeight = 0.0; updateSpeedColoring(); mLoggerMap.postInvalidate(); } } } /** * For the current track identifier the route of that track is drawn by * adding a OverLay for each segments in the track * * @param trackId * @see SegmentRendering */ private void createDataOverlays() { mLastSegmentOverlay = null; mBitmapSegmentsOverlay.clearSegments(); mLoggerMap.clearOverlays(); mLoggerMap.addOverlay(mBitmapSegmentsOverlay); ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Cursor segments = null; int trackColoringMethod = Integer.valueOf(mSharedPreferences.getString(Constants.TRACKCOLORING, "2")).intValue(); try { Uri segmentsUri = Uri.withAppendedPath(Tracks.CONTENT_URI, this.mTrackId + "/segments"); segments = resolver.query(segmentsUri, new String[] { Segments._ID }, null, null, null); if (segments != null && segments.moveToFirst()) { do { long segmentsId = segments.getLong(0); Uri segmentUri = ContentUris.withAppendedId(segmentsUri, segmentsId); SegmentRendering segmentOverlay = new SegmentRendering(mLoggerMap, segmentUri, trackColoringMethod, mAverageSpeed, mAverageHeight, mHandler); mBitmapSegmentsOverlay.addSegment(segmentOverlay); mLastSegmentOverlay = segmentOverlay; if (segments.isFirst()) { segmentOverlay.addPlacement(SegmentRendering.FIRST_SEGMENT); } if (segments.isLast()) { segmentOverlay.addPlacement(SegmentRendering.LAST_SEGMENT); } mLastSegment = segmentsId; } while (segments.moveToNext()); } } finally { if (segments != null) { segments.close(); } } Uri lastSegmentUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mLastSegment + "/waypoints"); resolver.unregisterContentObserver(this.mSegmentWaypointsObserver); resolver.registerContentObserver(lastSegmentUri, false, this.mSegmentWaypointsObserver); } private void updateDataOverlays() { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Uri segmentsUri = Uri.withAppendedPath(Tracks.CONTENT_URI, this.mTrackId + "/segments"); Cursor segmentsCursor = null; int segmentOverlaysCount = mBitmapSegmentsOverlay.size(); try { segmentsCursor = resolver.query(segmentsUri, new String[] { Segments._ID }, null, null, null); if (segmentsCursor != null && segmentsCursor.getCount() == segmentOverlaysCount) { // Log.d( TAG, "Alignment of segments" ); } else { createDataOverlays(); } } finally { if (segmentsCursor != null) { segmentsCursor.close(); } } } /** * Call when an overlay has recalulated and has new information to be redrawn */ private void moveActiveViewWindow() { GeoPoint lastPoint = getLastTrackPoint(); if (lastPoint != null && mLoggerServiceManager.getLoggingState() == Constants.LOGGING) { if (mLoggerMap.isOutsideScreen(lastPoint)) { mLoggerMap.clearAnimation(); mLoggerMap.setCenter(lastPoint); } else if (mLoggerMap.isNearScreenEdge(lastPoint)) { mLoggerMap.clearAnimation(); mLoggerMap.animateTo(lastPoint); } } } /** * Updates the labels next to the color bar with speeds */ private void drawSpeedTexts() { UnitsI18n units = mUnits; if (units != null) { double avgSpeed = units.conversionFromMetersPerSecond(mAverageSpeed); TextView[] mSpeedtexts = mLoggerMap.getSpeedTextViews(); SlidingIndicatorView currentScaleIndicator = mLoggerMap.getScaleIndicatorView(); for (int i = 0; i < mSpeedtexts.length; i++) { mSpeedtexts[i].setVisibility(View.VISIBLE); double speed; if (mUnits.isUnitFlipped()) { speed = ((avgSpeed * 2d) / 5d) * (mSpeedtexts.length - i - 1); } else { speed = ((avgSpeed * 2d) / 5d) * i; } if( i == 0 ) { currentScaleIndicator.setMin((float) speed); } else { currentScaleIndicator.setMax((float) speed); } String speedText = units.formatSpeed(speed, false); mSpeedtexts[i].setText(speedText); } } } /** * Updates the labels next to the color bar with heights */ private void drawHeightTexts() { UnitsI18n units = mUnits; if (units != null) { double avgHeight = units.conversionFromMeterToHeight(mAverageHeight); TextView[] mSpeedtexts = mLoggerMap.getSpeedTextViews(); SlidingIndicatorView currentScaleIndicator = mLoggerMap.getScaleIndicatorView(); for (int i = 0; i < mSpeedtexts.length; i++) { mSpeedtexts[i].setVisibility(View.VISIBLE); double height = ((avgHeight * 2d) / 5d) * i; String heightText = String.format( "%d %s", (int)height, units.getHeightUnit() ); mSpeedtexts[i].setText(heightText); if( i == 0 ) { currentScaleIndicator.setMin((float) height); } else { currentScaleIndicator.setMax((float) height); } } } } /** * Alter this to set a new track as current. * * @param trackId * @param center center on the end of the track */ private void moveToTrack(long trackId, boolean center) { if( trackId == mTrackId ) { return; } Cursor track = null; try { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); Uri trackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, trackId); track = resolver.query(trackUri, new String[] { Tracks.NAME }, null, null, null); if (track != null && track.moveToFirst()) { this.mTrackId = trackId; mLastSegment = -1; resolver.unregisterContentObserver(this.mTrackSegmentsObserver); resolver.unregisterContentObserver(this.mTrackMediasObserver); Uri tracksegmentsUri = Uri.withAppendedPath(Tracks.CONTENT_URI, trackId + "/segments"); resolver.registerContentObserver(tracksegmentsUri, false, this.mTrackSegmentsObserver); resolver.registerContentObserver(Media.CONTENT_URI, true, this.mTrackMediasObserver); mLoggerMap.clearOverlays(); mBitmapSegmentsOverlay.clearSegments(); mAverageSpeed = 0.0; mAverageHeight = 0.0; updateTitleBar(); updateDataOverlays(); updateSpeedColoring(); if (center) { GeoPoint lastPoint = getLastTrackPoint(); mLoggerMap.animateTo(lastPoint); } } } finally { if (track != null) { track.close(); } } } /** * Get the last know position from the GPS provider and return that * information wrapped in a GeoPoint to which the Map can navigate. * * @see GeoPoint * @return */ private GeoPoint getLastKnowGeopointLocation() { int microLatitude = 0; int microLongitude = 0; LocationManager locationManager = (LocationManager) mLoggerMap.getActivity().getApplication().getSystemService(Context.LOCATION_SERVICE); Location locationFine = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (locationFine != null) { microLatitude = (int) (locationFine.getLatitude() * 1E6d); microLongitude = (int) (locationFine.getLongitude() * 1E6d); } if (locationFine == null || microLatitude == 0 || microLongitude == 0) { Location locationCoarse = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (locationCoarse != null) { microLatitude = (int) (locationCoarse.getLatitude() * 1E6d); microLongitude = (int) (locationCoarse.getLongitude() * 1E6d); } if (locationCoarse == null || microLatitude == 0 || microLongitude == 0) { microLatitude = 51985105; microLongitude = 5106132; } } GeoPoint geoPoint = new GeoPoint(microLatitude, microLongitude); return geoPoint; } /** * Retrieve the last point of the current track * * @param context */ private GeoPoint getLastTrackPoint() { Cursor waypoint = null; GeoPoint lastPoint = null; // First try the service which might have a cached version Location lastLoc = mLoggerServiceManager.getLastWaypoint(); if (lastLoc != null) { int microLatitude = (int) (lastLoc.getLatitude() * 1E6d); int microLongitude = (int) (lastLoc.getLongitude() * 1E6d); lastPoint = new GeoPoint(microLatitude, microLongitude); } // If nothing yet, try the content resolver and query the track if (lastPoint == null || lastPoint.getLatitudeE6() == 0 || lastPoint.getLongitudeE6() == 0) { try { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); waypoint = resolver.query(Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/waypoints"), new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE, "max(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null); if (waypoint != null && waypoint.moveToLast()) { int microLatitude = (int) (waypoint.getDouble(0) * 1E6d); int microLongitude = (int) (waypoint.getDouble(1) * 1E6d); lastPoint = new GeoPoint(microLatitude, microLongitude); } } finally { if (waypoint != null) { waypoint.close(); } } } // If nothing yet, try the last generally known location if (lastPoint == null || lastPoint.getLatitudeE6() == 0 || lastPoint.getLongitudeE6() == 0) { lastPoint = getLastKnowGeopointLocation(); } return lastPoint; } private void moveToLastTrack() { int trackId = -1; Cursor track = null; try { ContentResolver resolver = mLoggerMap.getActivity().getContentResolver(); track = resolver.query(Tracks.CONTENT_URI, new String[] { "max(" + Tracks._ID + ")", Tracks.NAME, }, null, null, null); if (track != null && track.moveToLast()) { trackId = track.getInt(0); moveToTrack(trackId, false); } } finally { if (track != null) { track.close(); } } } /** * Enables a SegmentOverlay to call back to the MapActivity to show a dialog * with choices of media * * @param mediaAdapter */ public void showMediaDialog(BaseAdapter mediaAdapter) { mMediaAdapter = mediaAdapter; mLoggerMap.getActivity().showDialog(DIALOG_URIS); } public SharedPreferences getPreferences() { return mSharedPreferences; } public boolean isLogging() { return mLoggerServiceManager.getLoggingState() == Constants.LOGGING; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/map/LoggerMapHelper.java
Java
gpl3
60,903
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Mar 3, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.viewer.map; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.SlidingIndicatorView; import nl.sogeti.android.gpstracker.viewer.map.overlay.OverlayProvider; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Point; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.BaseAdapter; import android.widget.TextView; import com.google.android.maps.GeoPoint; import com.mapquest.android.maps.MapActivity; import com.mapquest.android.maps.MapView; import com.mapquest.android.maps.MyLocationOverlay; /** * ???? * * @version $Id:$ * @author rene (c) Mar 3, 2012, Sogeti B.V. */ public class MapQuestLoggerMap extends MapActivity implements LoggerMap { LoggerMapHelper mHelper; private MapView mMapView; private TextView[] mSpeedtexts; private TextView mLastGPSSpeedView; private TextView mLastGPSAltitudeView; private TextView mDistanceView; private MyLocationOverlay mMylocation; /** * Called when the activity is first created. */ @Override protected void onCreate(Bundle load) { super.onCreate(load); setContentView(R.layout.map_mapquest); mMapView = (MapView) findViewById(R.id.myMapView); mHelper = new LoggerMapHelper(this); mMapView = (MapView) findViewById(R.id.myMapView); mMylocation = new MyLocationOverlay(this, mMapView); mMapView.setBuiltInZoomControls(true); TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04), (TextView) findViewById(R.id.speedview03), (TextView) findViewById(R.id.speedview02), (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) }; mSpeedtexts = speeds; mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed); mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude); mDistanceView = (TextView) findViewById(R.id.currentDistance); mHelper.onCreate(load); } @Override protected void onResume() { super.onResume(); mHelper.onResume(); } @Override protected void onPause() { mHelper.onPause(); super.onPause(); } @Override protected void onDestroy() { mHelper.onDestroy(); super.onDestroy(); } @Override public void onNewIntent(Intent newIntent) { mHelper.onNewIntent(newIntent); } @Override protected void onRestoreInstanceState(Bundle load) { if (load != null) { super.onRestoreInstanceState(load); } mHelper.onRestoreInstanceState(load); } @Override protected void onSaveInstanceState(Bundle save) { super.onSaveInstanceState(save); mHelper.onSaveInstanceState(save); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); mHelper.onCreateOptionsMenu(menu); return result; } @Override public boolean onPrepareOptionsMenu(Menu menu) { mHelper.onPrepareOptionsMenu(menu); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = mHelper.onOptionsItemSelected(item); if( !handled ) { handled = super.onOptionsItemSelected(item); } return handled; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); mHelper.onActivityResult(requestCode, resultCode, intent); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean propagate = true; switch (keyCode) { default: propagate = mHelper.onKeyDown(keyCode, event); if( propagate ) { propagate = super.onKeyDown(keyCode, event); } break; } return propagate; } @Override protected Dialog onCreateDialog(int id) { Dialog dialog = mHelper.onCreateDialog(id); if( dialog == null ) { dialog = super.onCreateDialog(id); } return dialog; } @Override protected void onPrepareDialog(int id, Dialog dialog) { mHelper.onPrepareDialog(id, dialog); super.onPrepareDialog(id, dialog); } /******************************/ /** Loggermap methods **/ /******************************/ @Override public void updateOverlays() { } @Override public void setDrawingCacheEnabled(boolean b) { findViewById(R.id.mapScreen).setDrawingCacheEnabled(true); } @Override public Activity getActivity() { return this; } @Override public void onLayerCheckedChanged(int checkedId, boolean isChecked) { } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { } @Override public Bitmap getDrawingCache() { return findViewById(R.id.mapScreen).getDrawingCache(); } @Override public void showMediaDialog(BaseAdapter mediaAdapter) { mHelper.showMediaDialog(mediaAdapter); } public void onDateOverlayChanged() { mMapView.postInvalidate(); } @Override public String getDataSourceId() { return LoggerMapHelper.MAPQUEST_PROVIDER; } @Override public boolean isOutsideScreen(GeoPoint lastPoint) { Point out = new Point(); this.mMapView.getProjection().toPixels(MapQuestLoggerMap.convertGeoPoint(lastPoint), out); int height = this.mMapView.getHeight(); int width = this.mMapView.getWidth(); return (out.x < 0 || out.y < 0 || out.y > height || out.x > width); } @Override public boolean isNearScreenEdge(GeoPoint lastPoint) { Point out = new Point(); this.mMapView.getProjection().toPixels(MapQuestLoggerMap.convertGeoPoint(lastPoint), out); int height = this.mMapView.getHeight(); int width = this.mMapView.getWidth(); return (out.x < width / 4 || out.y < height / 4 || out.x > (width / 4) * 3 || out.y > (height / 4) * 3); } @Override public void executePostponedActions() { } @Override public void enableCompass() { mMylocation.enableCompass(); } @Override public void enableMyLocation() { mMylocation.enableMyLocation(); } @Override public void disableMyLocation() { mMylocation.disableMyLocation(); } @Override public void disableCompass() { mMylocation.disableCompass(); } @Override public void setZoom(int zoom) { mMapView.getController().setZoom(zoom); } @Override public void animateTo(GeoPoint storedPoint) { mMapView.getController().animateTo(MapQuestLoggerMap.convertGeoPoint(storedPoint)); } @Override public int getZoomLevel() { return mMapView.getZoomLevel(); } @Override public GeoPoint getMapCenter() { return MapQuestLoggerMap.convertMapQuestGeoPoint(mMapView.getMapCenter()); } @Override public boolean zoomOut() { return mMapView.getController().zoomOut(); } @Override public boolean zoomIn() { return mMapView.getController().zoomIn(); } @Override public void postInvalidate() { mMapView.postInvalidate(); } @Override public void addOverlay(OverlayProvider overlay) { mMapView.getOverlays().add(overlay.getMapQuestOverlay()); } @Override public void clearAnimation() { mMapView.clearAnimation(); } @Override public void setCenter(GeoPoint lastPoint) { mMapView.getController().setCenter( MapQuestLoggerMap.convertGeoPoint(lastPoint)); } @Override public int getMaxZoomLevel() { return mMapView.getMaxZoomLevel(); } @Override public GeoPoint fromPixels(int x, int y) { com.mapquest.android.maps.GeoPoint mqGeopoint = mMapView.getProjection().fromPixels(x, y); return convertMapQuestGeoPoint(mqGeopoint); } @Override public boolean hasProjection() { return mMapView.getProjection() != null; } @Override public float metersToEquatorPixels(float float1) { return mMapView.getProjection().metersToEquatorPixels(float1); } @Override public void toPixels(GeoPoint geoPoint, Point screenPoint) { com.mapquest.android.maps.GeoPoint mqGeopoint = MapQuestLoggerMap.convertGeoPoint(geoPoint); mMapView.getProjection().toPixels( mqGeopoint, screenPoint); } @Override public TextView[] getSpeedTextViews() { return mSpeedtexts; } @Override public TextView getAltitideTextView() { return mLastGPSAltitudeView; } @Override public TextView getSpeedTextView() { return mLastGPSSpeedView; } @Override public TextView getDistanceTextView() { return mDistanceView; } static com.mapquest.android.maps.GeoPoint convertGeoPoint( GeoPoint point ) { return new com.mapquest.android.maps.GeoPoint(point.getLatitudeE6(), point.getLongitudeE6() ); } static GeoPoint convertMapQuestGeoPoint( com.mapquest.android.maps.GeoPoint mqPoint ) { return new GeoPoint(mqPoint.getLatitudeE6(), mqPoint.getLongitudeE6() ); } @Override public void clearOverlays() { mMapView.getOverlays().clear(); } @Override public SlidingIndicatorView getScaleIndicatorView() { return (SlidingIndicatorView) findViewById(R.id.scaleindicator); } /******************************/ /** Own methods **/ /******************************/ @Override public boolean isRouteDisplayed() { return true; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/map/MapQuestLoggerMap.java
Java
gpl3
10,898
package nl.sogeti.android.gpstracker.viewer.map.overlay; import nl.sogeti.android.gpstracker.viewer.map.LoggerMap; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; public abstract class AsyncOverlay extends Overlay implements OverlayProvider { private static final int OFFSET = 20; private static final String TAG = "GG.AsyncOverlay"; /** * Handler provided by the MapActivity to recalculate graphics */ private Handler mHandler; private GeoPoint mGeoTopLeft; private GeoPoint mGeoBottumRight; private int mWidth; private int mHeight; private Bitmap mActiveBitmap; private GeoPoint mActiveTopLeft; private Point mActivePointTopLeft; private Bitmap mCalculationBitmap; private Paint mPaint; private LoggerMap mLoggerMap; SegmentOsmOverlay mOsmOverlay; private SegmentMapQuestOverlay mMapQuestOverlay; private int mActiveZoomLevel; private Runnable mBitmapUpdater = new Runnable() { @Override public void run() { postedBitmapUpdater = false; mCalculationBitmap.eraseColor(Color.TRANSPARENT); mGeoTopLeft = mLoggerMap.fromPixels(0, 0); mGeoBottumRight = mLoggerMap.fromPixels(mWidth, mHeight); Canvas calculationCanvas = new Canvas(mCalculationBitmap); redrawOffscreen(calculationCanvas, mLoggerMap); synchronized (mActiveBitmap) { Bitmap oldActiveBitmap = mActiveBitmap; mActiveBitmap = mCalculationBitmap; mActiveTopLeft = mGeoTopLeft; mCalculationBitmap = oldActiveBitmap; } mLoggerMap.postInvalidate(); } }; private boolean postedBitmapUpdater; AsyncOverlay(LoggerMap loggermap, Handler handler) { mLoggerMap = loggermap; mHandler = handler; mWidth = 1; mHeight = 1; mPaint = new Paint(); mActiveZoomLevel = -1; mActiveBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); mActiveTopLeft = new GeoPoint(0, 0); mActivePointTopLeft = new Point(); mCalculationBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); mOsmOverlay = new SegmentOsmOverlay(mLoggerMap.getActivity(), mLoggerMap, this); mMapQuestOverlay = new SegmentMapQuestOverlay(this); } protected void reset() { synchronized (mActiveBitmap) { mCalculationBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); mActiveBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); } } protected void considerRedrawOffscreen() { int oldZoomLevel = mActiveZoomLevel; mActiveZoomLevel = mLoggerMap.getZoomLevel(); boolean needNewCalculation = false; if (mCalculationBitmap.getWidth() != mWidth || mCalculationBitmap.getHeight() != mHeight) { mCalculationBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); needNewCalculation = true; } boolean unaligned = isOutAlignment(); if (needNewCalculation || mActiveZoomLevel != oldZoomLevel || unaligned) { scheduleRecalculation(); } } private boolean isOutAlignment() { Point screenPoint = new Point(0, 0); if (mGeoTopLeft != null) { mLoggerMap.toPixels(mGeoTopLeft, screenPoint); } return mGeoTopLeft == null || mGeoBottumRight == null || screenPoint.x > OFFSET || screenPoint.y > OFFSET || screenPoint.x < -OFFSET || screenPoint.y < -OFFSET; } public void onDateOverlayChanged() { if (!postedBitmapUpdater) { postedBitmapUpdater = true; mHandler.post(mBitmapUpdater); } } protected abstract void redrawOffscreen(Canvas asyncBuffer, LoggerMap loggermap); protected abstract void scheduleRecalculation(); /** * {@inheritDoc} */ @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { if (!shadow) { draw(canvas); } } private void draw(Canvas canvas) { mWidth = canvas.getWidth(); mHeight = canvas.getHeight(); considerRedrawOffscreen(); if (mActiveBitmap.getWidth() > 1) { synchronized (mActiveBitmap) { mLoggerMap.toPixels(mActiveTopLeft, mActivePointTopLeft); canvas.drawBitmap(mActiveBitmap, mActivePointTopLeft.x, mActivePointTopLeft.y, mPaint); } } } protected boolean isPointOnScreen(Point point) { return point.x < 0 || point.y < 0 || point.x > mWidth || point.y > mHeight; } @Override public boolean onTap(GeoPoint tappedGeoPoint, MapView mapview) { return commonOnTap(tappedGeoPoint); } /**************************************/ /** Multi map support **/ /**************************************/ @Override public Overlay getGoogleOverlay() { return this; } @Override public org.osmdroid.views.overlay.Overlay getOSMOverlay() { return mOsmOverlay; } @Override public com.mapquest.android.maps.Overlay getMapQuestOverlay() { return mMapQuestOverlay; } protected abstract boolean commonOnTap(GeoPoint tappedGeoPoint); static class SegmentOsmOverlay extends org.osmdroid.views.overlay.Overlay { AsyncOverlay mSegmentOverlay; LoggerMap mLoggerMap; public SegmentOsmOverlay(Context ctx, LoggerMap map, AsyncOverlay segmentOverlay) { super(ctx); mLoggerMap = map; mSegmentOverlay = segmentOverlay; } public AsyncOverlay getSegmentOverlay() { return mSegmentOverlay; } @Override public boolean onSingleTapUp(MotionEvent e, org.osmdroid.views.MapView openStreetMapView) { int x = (int) e.getX(); int y = (int) e.getY(); GeoPoint tappedGeoPoint = mLoggerMap.fromPixels(x, y); return mSegmentOverlay.commonOnTap(tappedGeoPoint); } @Override protected void draw(Canvas canvas, org.osmdroid.views.MapView view, boolean shadow) { if (!shadow) { mSegmentOverlay.draw(canvas); } } } static class SegmentMapQuestOverlay extends com.mapquest.android.maps.Overlay { AsyncOverlay mSegmentOverlay; public SegmentMapQuestOverlay(AsyncOverlay segmentOverlay) { super(); mSegmentOverlay = segmentOverlay; } public AsyncOverlay getSegmentOverlay() { return mSegmentOverlay; } @Override public boolean onTap(com.mapquest.android.maps.GeoPoint p, com.mapquest.android.maps.MapView mapView) { GeoPoint tappedGeoPoint = new GeoPoint(p.getLatitudeE6(), p.getLongitudeE6()); return mSegmentOverlay.commonOnTap(tappedGeoPoint); } @Override public void draw(Canvas canvas, com.mapquest.android.maps.MapView mapView, boolean shadow) { if (!shadow) { mSegmentOverlay.draw(canvas); } } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/map/overlay/AsyncOverlay.java
Java
gpl3
7,453
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.viewer.map.overlay; import java.text.DateFormat; import java.util.Date; import java.util.List; import java.util.Vector; import nl.sogeti.android.gpstracker.BuildConfig; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.util.UnitsI18n; import nl.sogeti.android.gpstracker.viewer.map.LoggerMap; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ComposeShader; import android.graphics.CornerPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.PorterDuff.Mode; import android.graphics.RadialGradient; import android.graphics.Shader; import android.graphics.Shader.TileMode; import android.location.Location; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; /** * Creates an overlay that can draw a single segment of connected waypoints * * @version $Id$ * @author rene (c) Jan 11, 2009, Sogeti B.V. */ public class SegmentRendering { public static final int MIDDLE_SEGMENT = 0; public static final int FIRST_SEGMENT = 1; public static final int LAST_SEGMENT = 2; public static final int DRAW_GREEN = 0; public static final int DRAW_RED = 1; public static final int DRAW_MEASURED = 2; public static final int DRAW_CALCULATED = 3; public static final int DRAW_DOTS = 4; public static final int DRAW_HEIGHT = 5; private static final String TAG = "OGT.SegmentRendering"; private static final float MINIMUM_PX_DISTANCE = 15; private static SparseArray<Bitmap> sBitmapCache = new SparseArray<Bitmap>();; private int mTrackColoringMethod = DRAW_CALCULATED; private ContentResolver mResolver; private LoggerMap mLoggerMap; private int mPlacement = SegmentRendering.MIDDLE_SEGMENT; private Uri mWaypointsUri; private Uri mMediaUri; private double mAvgSpeed; private double mAvgHeight; private GeoPoint mGeoTopLeft; private GeoPoint mGeoBottumRight; private Vector<DotVO> mDotPath; private Vector<DotVO> mDotPathCalculation; private Path mCalculatedPath; private Point mCalculatedStart; private Point mCalculatedStop; private Path mPathCalculation; private Shader mShader; private Vector<MediaVO> mMediaPath; private Vector<MediaVO> mMediaPathCalculation; private GeoPoint mStartPoint; private GeoPoint mEndPoint; private Point mPrevDrawnScreenPoint; private Point mScreenPointBackup; private Point mScreenPoint; private Point mMediaScreenPoint; private int mStepSize = -1; private Location mLocation; private Location mPrevLocation; private Cursor mWaypointsCursor; private Cursor mMediaCursor; private Uri mSegmentUri; private int mWaypointCount = -1; private int mWidth; private int mHeight; private GeoPoint mPrevGeoPoint; private int mCurrentColor; private Paint dotpaint; private Paint radiusPaint; private Paint routePaint; private Paint defaultPaint; private boolean mRequeryFlag; private Handler mHandler; private static Bitmap sStartBitmap; private static Bitmap sStopBitmap; private AsyncOverlay mAsyncOverlay; private ContentObserver mTrackSegmentsObserver; private final Runnable mMediaCalculator = new Runnable() { @Override public void run() { SegmentRendering.this.calculateMediaAsync(); } }; private final Runnable mTrackCalculator = new Runnable() { @Override public void run() { SegmentRendering.this.calculateTrackAsync(); } }; /** * Constructor: create a new TrackingOverlay. * * @param loggermap * @param segmentUri * @param color * @param avgSpeed * @param handler */ public SegmentRendering(LoggerMap loggermap, Uri segmentUri, int color, double avgSpeed, double avgHeight, Handler handler) { super(); mHandler = handler; mLoggerMap = loggermap; mTrackColoringMethod = color; mAvgSpeed = avgSpeed; mAvgHeight = avgHeight; mSegmentUri = segmentUri; mMediaUri = Uri.withAppendedPath(mSegmentUri, "media"); mWaypointsUri = Uri.withAppendedPath(mSegmentUri, "waypoints"); mResolver = mLoggerMap.getActivity().getContentResolver(); mRequeryFlag = true; mCurrentColor = Color.rgb(255, 0, 0); dotpaint = new Paint(); radiusPaint = new Paint(); radiusPaint.setColor(Color.YELLOW); radiusPaint.setAlpha(100); routePaint = new Paint(); routePaint.setStyle(Paint.Style.STROKE); routePaint.setStrokeWidth(6); routePaint.setAntiAlias(true); routePaint.setPathEffect(new CornerPathEffect(10)); defaultPaint = new Paint(); mScreenPoint = new Point(); mMediaScreenPoint = new Point(); mScreenPointBackup = new Point(); mPrevDrawnScreenPoint = new Point(); mDotPath = new Vector<DotVO>(); mDotPathCalculation = new Vector<DotVO>(); mCalculatedPath = new Path(); mPathCalculation = new Path(); mMediaPath = new Vector<MediaVO>(); mMediaPathCalculation = new Vector<MediaVO>(); mTrackSegmentsObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (!selfUpdate) { mRequeryFlag = true; } else { Log.w(TAG, "mTrackSegmentsObserver skipping change on " + mSegmentUri); } } }; openResources(); } public void closeResources() { mResolver.unregisterContentObserver(mTrackSegmentsObserver); mHandler.removeCallbacks(mMediaCalculator); mHandler.removeCallbacks(mTrackCalculator); mHandler.postAtFrontOfQueue(new Runnable() { @Override public void run() { if (mWaypointsCursor != null) { mWaypointsCursor.close(); mWaypointsCursor = null; } if (mMediaCursor != null) { mMediaCursor.close(); mMediaCursor = null; } } }); SegmentRendering.sStopBitmap = null; SegmentRendering.sStartBitmap = null; } public void openResources() { mResolver.registerContentObserver(mWaypointsUri, false, mTrackSegmentsObserver); } /** * Private draw method called by both the draw from Google Overlay and the * OSM Overlay * * @param canvas */ public void draw(Canvas canvas) { switch (mTrackColoringMethod) { case DRAW_HEIGHT: case DRAW_CALCULATED: case DRAW_MEASURED: case DRAW_RED: case DRAW_GREEN: drawPath(canvas); break; case DRAW_DOTS: drawDots(canvas); break; } drawStartStopCircles(canvas); drawMedia(canvas); mWidth = canvas.getWidth(); mHeight = canvas.getHeight(); } public void calculateTrack() { mHandler.removeCallbacks(mTrackCalculator); mHandler.post(mTrackCalculator); } /** * Either the Path or the Dots are calculated based on he current track * coloring method */ private synchronized void calculateTrackAsync() { mGeoTopLeft = mLoggerMap.fromPixels(0, 0); mGeoBottumRight = mLoggerMap.fromPixels(mWidth, mHeight); calculateStepSize(); mScreenPoint.x = -1; mScreenPoint.y = -1; this.mPrevDrawnScreenPoint.x = -1; this.mPrevDrawnScreenPoint.y = -1; switch (mTrackColoringMethod) { case DRAW_HEIGHT: case DRAW_CALCULATED: case DRAW_MEASURED: case DRAW_RED: case DRAW_GREEN: calculatePath(); synchronized (mCalculatedPath) // Switch the fresh path with the old Path object { Path oldPath = mCalculatedPath; mCalculatedPath = mPathCalculation; mPathCalculation = oldPath; } break; case DRAW_DOTS: calculateDots(); synchronized (mDotPath) // Switch the fresh path with the old Path object { Vector<DotVO> oldDotPath = mDotPath; mDotPath = mDotPathCalculation; mDotPathCalculation = oldDotPath; } break; } calculateStartStopCircles(); mAsyncOverlay.onDateOverlayChanged(); } /** * Calculated the new contents of segment in the mDotPathCalculation */ private void calculatePath() { mDotPathCalculation.clear(); this.mPathCalculation.rewind(); this.mShader = null; GeoPoint geoPoint; this.mPrevLocation = null; if (mWaypointsCursor == null) { mWaypointsCursor = this.mResolver.query(this.mWaypointsUri, new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE, Waypoints.SPEED, Waypoints.TIME, Waypoints.ACCURACY, Waypoints.ALTITUDE }, null, null, null); mRequeryFlag = false; } if (mRequeryFlag) { mWaypointsCursor.requery(); mRequeryFlag = false; } if (mLoggerMap.hasProjection() && mWaypointsCursor.moveToFirst()) { // Start point of the segments, possible a dot this.mStartPoint = extractGeoPoint(); mPrevGeoPoint = mStartPoint; this.mLocation = new Location(this.getClass().getName()); this.mLocation.setLatitude(mWaypointsCursor.getDouble(0)); this.mLocation.setLongitude(mWaypointsCursor.getDouble(1)); this.mLocation.setTime(mWaypointsCursor.getLong(3)); moveToGeoPoint(this.mStartPoint); do { geoPoint = extractGeoPoint(); // Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop if (geoPoint.getLatitudeE6() == 0 || geoPoint.getLongitudeE6() == 0) { continue; } double speed = -1d; switch (mTrackColoringMethod) { case DRAW_GREEN: case DRAW_RED: plainLineToGeoPoint(geoPoint); break; case DRAW_MEASURED: speedLineToGeoPoint(geoPoint, mWaypointsCursor.getDouble(2)); break; case DRAW_CALCULATED: this.mPrevLocation = this.mLocation; this.mLocation = new Location(this.getClass().getName()); this.mLocation.setLatitude(mWaypointsCursor.getDouble(0)); this.mLocation.setLongitude(mWaypointsCursor.getDouble(1)); this.mLocation.setTime(mWaypointsCursor.getLong(3)); speed = calculateSpeedBetweenLocations(this.mPrevLocation, this.mLocation); speedLineToGeoPoint(geoPoint, speed); break; case DRAW_HEIGHT: heightLineToGeoPoint(geoPoint, mWaypointsCursor.getDouble(5)); break; default: Log.w(TAG, "Unknown coloring method"); break; } } while (moveToNextWayPoint()); this.mEndPoint = extractGeoPoint(); // End point of the segments, possible a dot } // Log.d( TAG, "transformSegmentToPath stop: points "+mCalculatedPoints+" from "+moves+" moves" ); } /** * @param canvas * @param mapView * @param shadow * @see SegmentRendering#draw(Canvas, MapView, boolean) */ private void calculateDots() { mPathCalculation.reset(); mDotPathCalculation.clear(); if (mWaypointsCursor == null) { mWaypointsCursor = this.mResolver.query(this.mWaypointsUri, new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE, Waypoints.SPEED, Waypoints.TIME, Waypoints.ACCURACY }, null, null, null); } if (mRequeryFlag) { mWaypointsCursor.requery(); mRequeryFlag = false; } if (mLoggerMap.hasProjection() && mWaypointsCursor.moveToFirst()) { GeoPoint geoPoint; mStartPoint = extractGeoPoint(); mPrevGeoPoint = mStartPoint; do { geoPoint = extractGeoPoint(); // Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop if (geoPoint.getLatitudeE6() == 0 || geoPoint.getLongitudeE6() == 0) { continue; } setScreenPoint(geoPoint); float distance = (float) distanceInPoints(this.mPrevDrawnScreenPoint, this.mScreenPoint); if (distance > MINIMUM_PX_DISTANCE) { DotVO dotVO = new DotVO(); dotVO.x = this.mScreenPoint.x; dotVO.y = this.mScreenPoint.y; dotVO.speed = mWaypointsCursor.getLong(2); dotVO.time = mWaypointsCursor.getLong(3); dotVO.radius = mLoggerMap.metersToEquatorPixels(mWaypointsCursor.getFloat(4)); mDotPathCalculation.add(dotVO); this.mPrevDrawnScreenPoint.x = this.mScreenPoint.x; this.mPrevDrawnScreenPoint.y = this.mScreenPoint.y; } } while (moveToNextWayPoint()); this.mEndPoint = extractGeoPoint(); DotVO pointVO = new DotVO(); pointVO.x = this.mScreenPoint.x; pointVO.y = this.mScreenPoint.y; pointVO.speed = mWaypointsCursor.getLong(2); pointVO.time = mWaypointsCursor.getLong(3); pointVO.radius = mLoggerMap.metersToEquatorPixels(mWaypointsCursor.getFloat(4)); mDotPathCalculation.add(pointVO); } } public void calculateMedia() { mHandler.removeCallbacks(mMediaCalculator); mHandler.post(mMediaCalculator); } public synchronized void calculateMediaAsync() { mMediaPathCalculation.clear(); if (mMediaCursor == null) { mMediaCursor = this.mResolver.query(this.mMediaUri, new String[] { Media.WAYPOINT, Media.URI }, null, null, null); } else { mMediaCursor.requery(); } if (mLoggerMap.hasProjection() && mMediaCursor.moveToFirst()) { GeoPoint lastPoint = null; int wiggle = 0; do { MediaVO mediaVO = new MediaVO(); mediaVO.waypointId = mMediaCursor.getLong(0); mediaVO.uri = Uri.parse(mMediaCursor.getString(1)); Uri mediaWaypoint = ContentUris.withAppendedId(mWaypointsUri, mediaVO.waypointId); Cursor waypointCursor = null; try { waypointCursor = this.mResolver.query(mediaWaypoint, new String[] { Waypoints.LATITUDE, Waypoints.LONGITUDE }, null, null, null); if (waypointCursor != null && waypointCursor.moveToFirst()) { int microLatitude = (int) (waypointCursor.getDouble(0) * 1E6d); int microLongitude = (int) (waypointCursor.getDouble(1) * 1E6d); mediaVO.geopoint = new GeoPoint(microLatitude, microLongitude); } } finally { if (waypointCursor != null) { waypointCursor.close(); } } if (isGeoPointOnScreen(mediaVO.geopoint)) { mLoggerMap.toPixels(mediaVO.geopoint, this.mMediaScreenPoint); if (mediaVO.geopoint.equals(lastPoint)) { wiggle += 4; } else { wiggle = 0; } mediaVO.bitmapKey = getResourceForMedia(mLoggerMap.getActivity().getResources(), mediaVO.uri); mediaVO.w = sBitmapCache.get(mediaVO.bitmapKey).getWidth(); mediaVO.h = sBitmapCache.get(mediaVO.bitmapKey).getHeight(); int left = (mediaVO.w * 3) / 7 + wiggle; int up = (mediaVO.h * 6) / 7 - wiggle; mediaVO.x = mMediaScreenPoint.x - left; mediaVO.y = mMediaScreenPoint.y - up; lastPoint = mediaVO.geopoint; } mMediaPathCalculation.add(mediaVO); } while (mMediaCursor.moveToNext()); } synchronized (mMediaPath) // Switch the fresh path with the old Path object { Vector<MediaVO> oldmMediaPath = mMediaPath; mMediaPath = mMediaPathCalculation; mMediaPathCalculation = oldmMediaPath; } if (mMediaPathCalculation.size() != mMediaPath.size()) { mAsyncOverlay.onDateOverlayChanged(); } } private void calculateStartStopCircles() { if ((this.mPlacement == FIRST_SEGMENT || this.mPlacement == FIRST_SEGMENT + LAST_SEGMENT) && this.mStartPoint != null) { if (sStartBitmap == null) { sStartBitmap = BitmapFactory.decodeResource(this.mLoggerMap.getActivity().getResources(), R.drawable.stip); } if (mCalculatedStart == null) { mCalculatedStart = new Point(); } mLoggerMap.toPixels(this.mStartPoint, mCalculatedStart); } if ((this.mPlacement == LAST_SEGMENT || this.mPlacement == FIRST_SEGMENT + LAST_SEGMENT) && this.mEndPoint != null) { if (sStopBitmap == null) { sStopBitmap = BitmapFactory.decodeResource(this.mLoggerMap.getActivity().getResources(), R.drawable.stip2); } if (mCalculatedStop == null) { mCalculatedStop = new Point(); } mLoggerMap.toPixels(this.mEndPoint, mCalculatedStop); } } /** * @param canvas * @see SegmentRendering#draw(Canvas, MapView, boolean) */ private void drawPath(Canvas canvas) { switch (mTrackColoringMethod) { case DRAW_HEIGHT: case DRAW_CALCULATED: case DRAW_MEASURED: routePaint.setShader(this.mShader); break; case DRAW_RED: routePaint.setShader(null); routePaint.setColor(Color.RED); break; case DRAW_GREEN: routePaint.setShader(null); routePaint.setColor(Color.GREEN); break; default: routePaint.setShader(null); routePaint.setColor(Color.YELLOW); break; } synchronized (mCalculatedPath) { canvas.drawPath(mCalculatedPath, routePaint); } } private void drawDots(Canvas canvas) { synchronized (mDotPath) { if (sStopBitmap == null) { sStopBitmap = BitmapFactory.decodeResource(this.mLoggerMap.getActivity().getResources(), R.drawable.stip2); } for (DotVO dotVO : mDotPath) { canvas.drawBitmap(sStopBitmap, dotVO.x - 8, dotVO.y - 8, dotpaint); if (dotVO.radius > 8f) { canvas.drawCircle(dotVO.x, dotVO.y, dotVO.radius, radiusPaint); } } } } private void drawMedia(Canvas canvas) { synchronized (mMediaPath) { for (MediaVO mediaVO : mMediaPath) { if (mediaVO.bitmapKey != null) { Log.d(TAG, "Draw bitmap at (" + mediaVO.x + ", " + mediaVO.y + ") on " + canvas); canvas.drawBitmap(sBitmapCache.get(mediaVO.bitmapKey), mediaVO.x, mediaVO.y, defaultPaint); } } } } private void drawStartStopCircles(Canvas canvas) { if (mCalculatedStart != null) { canvas.drawBitmap(sStartBitmap, mCalculatedStart.x - 8, mCalculatedStart.y - 8, defaultPaint); } if (mCalculatedStop != null) { canvas.drawBitmap(sStopBitmap, mCalculatedStop.x - 5, mCalculatedStop.y - 5, defaultPaint); } } private Integer getResourceForMedia(Resources resources, Uri uri) { int drawable = 0; if (uri.getScheme().equals("file")) { if (uri.getLastPathSegment().endsWith("3gp")) { drawable = R.drawable.media_film; } else if (uri.getLastPathSegment().endsWith("jpg")) { drawable = R.drawable.media_camera; } else if (uri.getLastPathSegment().endsWith("txt")) { drawable = R.drawable.media_notepad; } } else if (uri.getScheme().equals("content")) { if (uri.getAuthority().equals(GPStracking.AUTHORITY + ".string")) { drawable = R.drawable.media_mark; } else if (uri.getAuthority().equals("media")) { drawable = R.drawable.media_speech; } } Bitmap bitmap = null; int bitmapKey = drawable; synchronized (sBitmapCache) { if (sBitmapCache.get(bitmapKey) == null) { bitmap = BitmapFactory.decodeResource(resources, drawable); sBitmapCache.put(bitmapKey, bitmap); } bitmap = sBitmapCache.get(bitmapKey); } return bitmapKey; } /** * Set the mPlace to the specified value. * * @see SegmentRendering.FIRST * @see SegmentRendering.MIDDLE * @see SegmentRendering.LAST * @param place The placement of this segment in the line. */ public void addPlacement(int place) { this.mPlacement += place; } public boolean isLast() { return (mPlacement >= LAST_SEGMENT); } public long getSegmentId() { return Long.parseLong(mSegmentUri.getLastPathSegment()); } /** * Set the beginnging to the next contour of the line to the give GeoPoint * * @param geoPoint */ private void moveToGeoPoint(GeoPoint geoPoint) { setScreenPoint(geoPoint); if (this.mPathCalculation != null) { this.mPathCalculation.moveTo(this.mScreenPoint.x, this.mScreenPoint.y); this.mPrevDrawnScreenPoint.x = this.mScreenPoint.x; this.mPrevDrawnScreenPoint.y = this.mScreenPoint.y; } } /** * Line to point without shaders * * @param geoPoint */ private void plainLineToGeoPoint(GeoPoint geoPoint) { shaderLineToGeoPoint(geoPoint, 0, 0); } /** * Line to point with speed * * @param geoPoint * @param height */ private void heightLineToGeoPoint(GeoPoint geoPoint, double height) { shaderLineToGeoPoint(geoPoint, height, mAvgHeight); } /** * Line to point with speed * * @param geoPoint * @param speed */ private void speedLineToGeoPoint(GeoPoint geoPoint, double speed) { shaderLineToGeoPoint(geoPoint, speed, mAvgSpeed); } private void shaderLineToGeoPoint(GeoPoint geoPoint, double value, double average) { setScreenPoint(geoPoint); // Log.d( TAG, "Draw line to " + geoPoint+" with speed "+speed ); if (value > 0) { int greenfactor = (int) Math.min((127 * value) / average, 255); int redfactor = 255 - greenfactor; mCurrentColor = Color.rgb(redfactor, greenfactor, 0); } else { int greenfactor = Color.green(mCurrentColor); int redfactor = Color.red(mCurrentColor); mCurrentColor = Color.argb(128, redfactor, greenfactor, 0); } float distance = (float) distanceInPoints(this.mPrevDrawnScreenPoint, this.mScreenPoint); if (distance > MINIMUM_PX_DISTANCE) { // Log.d( TAG, "Circle between " + mPrevDrawnScreenPoint+" and "+mScreenPoint ); int x_circle = (this.mPrevDrawnScreenPoint.x + this.mScreenPoint.x) / 2; int y_circle = (this.mPrevDrawnScreenPoint.y + this.mScreenPoint.y) / 2; float radius_factor = 0.4f; Shader lastShader = new RadialGradient(x_circle, y_circle, distance, new int[] { mCurrentColor, mCurrentColor, Color.TRANSPARENT }, new float[] { 0, radius_factor, 0.6f }, TileMode.CLAMP); // Paint debug = new Paint(); // debug.setStyle( Paint.Style.FILL_AND_STROKE ); // this.mDebugCanvas.drawCircle( // x_circle, // y_circle, // distance*radius_factor/2, // debug ); // this.mDebugCanvas.drawCircle( // x_circle, // y_circle, // distance*radius_factor, // debug ); // if( distance > 100 ) // { // Log.d( TAG, "Created shader for speed " + speed + " on " + x_circle + "," + y_circle ); // } if (this.mShader != null) { this.mShader = new ComposeShader(this.mShader, lastShader, Mode.DST_OVER); } else { this.mShader = lastShader; } this.mPrevDrawnScreenPoint.x = this.mScreenPoint.x; this.mPrevDrawnScreenPoint.y = this.mScreenPoint.y; } this.mPathCalculation.lineTo(this.mScreenPoint.x, this.mScreenPoint.y); } /** * Use to update location/point state when calculating the line * * @param geoPoint */ private void setScreenPoint(GeoPoint geoPoint) { mScreenPointBackup.x = this.mScreenPoint.x; mScreenPointBackup.y = this.mScreenPoint.x; mLoggerMap.toPixels(geoPoint, this.mScreenPoint); } /** * Move to a next waypoint, for on screen this are the points with mStepSize * % position == 0 to avoid jittering in the rendering or the points on the * either side of the screen edge. * * @return if a next waypoint is pointed to with the mWaypointsCursor */ private boolean moveToNextWayPoint() { boolean cursorReady = true; boolean onscreen = isGeoPointOnScreen(extractGeoPoint()); if (mWaypointsCursor.isLast()) // End of the line, cant move onward { cursorReady = false; } else if (onscreen) // Are on screen { cursorReady = moveOnScreenWaypoint(); } else // Are off screen => accelerate { int acceleratedStepsize = mStepSize * (mWaypointCount / 1000 + 6); cursorReady = moveOffscreenWaypoint(acceleratedStepsize); } return cursorReady; } /** * Move the cursor to the next waypoint modulo of the step size or less if * the screen edge is reached * * @param trackCursor * @return */ private boolean moveOnScreenWaypoint() { int nextPosition = mStepSize * (mWaypointsCursor.getPosition() / mStepSize) + mStepSize; if (mWaypointsCursor.moveToPosition(nextPosition)) { if (isGeoPointOnScreen(extractGeoPoint())) // Remained on screen { return true; // Cursor is pointing to somewhere } else { mWaypointsCursor.move(-1 * mStepSize); // Step back boolean nowOnScreen = true; // onto the screen while (nowOnScreen) // while on the screen { mWaypointsCursor.moveToNext(); // inch forward to the edge nowOnScreen = isGeoPointOnScreen(extractGeoPoint()); } return true; // with a cursor point to somewhere } } else { return mWaypointsCursor.moveToLast(); // No full step can be taken, move to last } } /** * Previous path GeoPoint was off screen and the next one will be to or the * first on screen when the path reaches the projection. * * @return */ private boolean moveOffscreenWaypoint(int flexStepsize) { while (mWaypointsCursor.move(flexStepsize)) { if (mWaypointsCursor.isLast()) { return true; } GeoPoint evalPoint = extractGeoPoint(); // Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop if (evalPoint.getLatitudeE6() == 0 || evalPoint.getLongitudeE6() == 0) { continue; } // Log.d( TAG, String.format( "Evaluate point number %d ", mWaypointsCursor.getPosition() ) ); if (possibleScreenPass(mPrevGeoPoint, evalPoint)) { mPrevGeoPoint = evalPoint; if (flexStepsize == 1) // Just stumbled over a border { return true; } else { mWaypointsCursor.move(-1 * flexStepsize); // Take 1 step back return moveOffscreenWaypoint(flexStepsize / 2); // Continue at halve accelerated speed } } else { moveToGeoPoint(evalPoint); mPrevGeoPoint = evalPoint; } } return mWaypointsCursor.moveToLast(); } /** * If a segment contains more then 500 waypoints and is zoomed out more then * twice then some waypoints will not be used to render the line, this * speeding things along. */ private void calculateStepSize() { Cursor waypointsCursor = null; if (mRequeryFlag || mStepSize < 1 || mWaypointCount < 0) { try { waypointsCursor = this.mResolver.query(this.mWaypointsUri, new String[] { Waypoints._ID }, null, null, null); mWaypointCount = waypointsCursor.getCount(); } finally { if (waypointsCursor != null) { waypointsCursor.close(); } } } if (mWaypointCount < 250) { mStepSize = 1; } else { int zoomLevel = mLoggerMap.getZoomLevel(); int maxZoomLevel = mLoggerMap.getMaxZoomLevel(); if (zoomLevel >= maxZoomLevel - 2) { mStepSize = 1; } else { mStepSize = maxZoomLevel - zoomLevel; } } } /** * Is a given GeoPoint in the current projection of the map. * * @param eval * @return */ protected boolean isGeoPointOnScreen(GeoPoint geopoint) { boolean onscreen = geopoint != null; if (geopoint != null && mGeoTopLeft != null && mGeoBottumRight != null) { onscreen = onscreen && mGeoTopLeft.getLatitudeE6() > geopoint.getLatitudeE6(); onscreen = onscreen && mGeoBottumRight.getLatitudeE6() < geopoint.getLatitudeE6(); if (mGeoTopLeft.getLongitudeE6() < mGeoBottumRight.getLongitudeE6()) { onscreen = onscreen && mGeoTopLeft.getLongitudeE6() < geopoint.getLongitudeE6(); onscreen = onscreen && mGeoBottumRight.getLongitudeE6() > geopoint.getLongitudeE6(); } else { onscreen = onscreen && (mGeoTopLeft.getLongitudeE6() < geopoint.getLongitudeE6() || mGeoBottumRight.getLongitudeE6() > geopoint.getLongitudeE6()); } } return onscreen; } /** * Is a given coordinates are on the screen * * @param eval * @return */ protected boolean isOnScreen(int x, int y) { boolean onscreen = x > 0 && y > 0 && x < mWidth && y < mHeight; return onscreen; } /** * Calculates in which segment opposited to the projecting a geo point * resides * * @param p1 * @return */ private int toSegment(GeoPoint p1) { // Log.d( TAG, String.format( "Comparing %s to points TL %s and BR %s", p1, mTopLeft, mBottumRight )); int nr; if (p1.getLongitudeE6() < mGeoTopLeft.getLongitudeE6()) // left { nr = 1; } else if (p1.getLongitudeE6() > mGeoBottumRight.getLongitudeE6()) // right { nr = 3; } else // middle { nr = 2; } if (p1.getLatitudeE6() > mGeoTopLeft.getLatitudeE6()) // top { nr = nr + 0; } else if (p1.getLatitudeE6() < mGeoBottumRight.getLatitudeE6()) // bottom { nr = nr + 6; } else // middle { nr = nr + 3; } return nr; } private boolean possibleScreenPass(GeoPoint fromGeo, GeoPoint toGeo) { boolean safe = true; if (fromGeo != null && toGeo != null) { int from = toSegment(fromGeo); int to = toSegment(toGeo); switch (from) { case 1: safe = to == 1 || to == 2 || to == 3 || to == 4 || to == 7; break; case 2: safe = to == 1 || to == 2 || to == 3; break; case 3: safe = to == 1 || to == 2 || to == 3 || to == 6 || to == 9; break; case 4: safe = to == 1 || to == 4 || to == 7; break; case 5: safe = false; break; case 6: safe = to == 3 || to == 6 || to == 9; break; case 7: safe = to == 1 || to == 4 || to == 7 || to == 8 || to == 9; break; case 8: safe = to == 7 || to == 8 || to == 9; break; case 9: safe = to == 3 || to == 6 || to == 7 || to == 8 || to == 9; break; default: safe = false; break; } // Log.d( TAG, String.format( "From %d to %d is safe: %s", from, to, safe ) ); } return !safe; } public void setTrackColoringMethod(int coloring, double avgspeed, double avgHeight) { if (mTrackColoringMethod != coloring) { mTrackColoringMethod = coloring; calculateTrack(); } mAvgSpeed = avgspeed; mAvgHeight = avgHeight; } /** * For the current waypoint cursor returns the GeoPoint * * @return */ private GeoPoint extractGeoPoint() { int microLatitude = (int) (mWaypointsCursor.getDouble(0) * 1E6d); int microLongitude = (int) (mWaypointsCursor.getDouble(1) * 1E6d); return new GeoPoint(microLatitude, microLongitude); } /** * @param startLocation * @param endLocation * @return speed in m/s between 2 locations */ private static double calculateSpeedBetweenLocations(Location startLocation, Location endLocation) { double speed = -1d; if (startLocation != null && endLocation != null) { float distance = startLocation.distanceTo(endLocation); float seconds = (endLocation.getTime() - startLocation.getTime()) / 1000f; speed = distance / seconds; // Log.d( TAG, "Found a speed of "+speed+ " over a distance of "+ distance+" in a time of "+seconds); } if (speed > 0) { return speed; } else { return -1d; } } public static int extendPoint(int x1, int x2) { int diff = x2 - x1; int next = x2 + diff; return next; } private static double distanceInPoints(Point start, Point end) { int x = Math.abs(end.x - start.x); int y = Math.abs(end.y - start.y); return (double) Math.sqrt(x * x + y * y); } private boolean handleMediaTapList(List<Uri> tappedUri) { if (tappedUri.size() == 1) { return handleMedia(mLoggerMap.getActivity(), tappedUri.get(0)); } else { BaseAdapter adapter = new MediaAdapter(mLoggerMap.getActivity(), tappedUri); mLoggerMap.showMediaDialog(adapter); return true; } } public static boolean handleMedia(Context ctx, Uri mediaUri) { if (mediaUri.getScheme().equals("file")) { Intent intent = new Intent(android.content.Intent.ACTION_VIEW); if (mediaUri.getLastPathSegment().endsWith("3gp")) { intent.setDataAndType(mediaUri, "video/3gpp"); ctx.startActivity(intent); return true; } else if (mediaUri.getLastPathSegment().endsWith("jpg")) { //<scheme>://<authority><absolute path> Uri.Builder builder = new Uri.Builder(); mediaUri = builder.scheme(mediaUri.getScheme()).authority(mediaUri.getAuthority()).path(mediaUri.getPath()).build(); intent.setDataAndType(mediaUri, "image/jpeg"); ctx.startActivity(intent); return true; } else if (mediaUri.getLastPathSegment().endsWith("txt")) { intent.setDataAndType(mediaUri, "text/plain"); ctx.startActivity(intent); return true; } } else if (mediaUri.getScheme().equals("content")) { if (mediaUri.getAuthority().equals(GPStracking.AUTHORITY + ".string")) { String text = mediaUri.getLastPathSegment(); Toast toast = Toast.makeText(ctx, text, Toast.LENGTH_LONG); toast.show(); return true; } else if (mediaUri.getAuthority().equals("media")) { ctx.startActivity(new Intent(Intent.ACTION_VIEW, mediaUri)); return true; } } return false; } public boolean commonOnTap(GeoPoint tappedGeoPoint) { List<Uri> tappedUri = new Vector<Uri>(); Point tappedPoint = new Point(); mLoggerMap.toPixels(tappedGeoPoint, tappedPoint); for (MediaVO media : mMediaPath) { if (media.x < tappedPoint.x && tappedPoint.x < media.x + media.w && media.y < tappedPoint.y && tappedPoint.y < media.y + media.h) { tappedUri.add(media.uri); } } if (tappedUri.size() > 0) { return handleMediaTapList(tappedUri); } else { if (mTrackColoringMethod == DRAW_DOTS) { DotVO tapped = null; synchronized (mDotPath) // Switch the fresh path with the old Path object { int w = 25; for (DotVO dot : mDotPath) { // Log.d( TAG, "Compare ("+dot.x+","+dot.y+") with tap ("+tappedPoint.x+","+tappedPoint.y+")" ); if (dot.x - w < tappedPoint.x && tappedPoint.x < dot.x + w && dot.y - w < tappedPoint.y && tappedPoint.y < dot.y + w) { if (tapped == null) { tapped = dot; } else { tapped = dot.distanceTo(tappedPoint) < tapped.distanceTo(tappedPoint) ? dot : tapped; } } } } if (tapped != null) { DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(mLoggerMap.getActivity().getApplicationContext()); String timetxt = timeFormat.format(new Date(tapped.time)); UnitsI18n units = new UnitsI18n(mLoggerMap.getActivity(), null); double speed = units.conversionFromMetersPerSecond(tapped.speed); String speedtxt = String.format("%.1f %s", speed, units.getSpeedUnit()); String text = mLoggerMap.getActivity().getString(R.string.time_and_speed, timetxt, speedtxt); Toast toast = Toast.makeText(mLoggerMap.getActivity(), text, Toast.LENGTH_SHORT); toast.show(); } } return false; } } private static class MediaVO { @Override public String toString() { return "MediaVO [bitmapKey=" + bitmapKey + ", uri=" + uri + ", geopoint=" + geopoint + ", x=" + x + ", y=" + y + ", w=" + w + ", h=" + h + ", waypointId=" + waypointId + "]"; } public Integer bitmapKey; public Uri uri; public GeoPoint geopoint; public int x; public int y; public int w; public int h; public long waypointId; } private static class DotVO { public long time; public long speed; public int x; public int y; public float radius; public int distanceTo(Point tappedPoint) { return Math.abs(tappedPoint.x - this.x) + Math.abs(tappedPoint.y - this.y); } } private class MediaAdapter extends BaseAdapter { private Context mContext; private List<Uri> mTappedUri; private int itemBackground; public MediaAdapter(Context ctx, List<Uri> tappedUri) { mContext = ctx; mTappedUri = tappedUri; TypedArray a = mContext.obtainStyledAttributes(R.styleable.gallery); itemBackground = a.getResourceId(R.styleable.gallery_android_galleryItemBackground, 0); a.recycle(); } @Override public int getCount() { return mTappedUri.size(); } @Override public Object getItem(int position) { return mTappedUri.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(mContext); imageView.setImageBitmap(sBitmapCache.get(getResourceForMedia(mLoggerMap.getActivity().getResources(), mTappedUri.get(position)))); imageView.setScaleType(ImageView.ScaleType.FIT_XY); imageView.setBackgroundResource(itemBackground); return imageView; } } public void setBitmapHolder(AsyncOverlay bitmapOverlay) { mAsyncOverlay = bitmapOverlay; } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/map/overlay/SegmentRendering.java
Java
gpl3
44,404
package nl.sogeti.android.gpstracker.viewer.map.overlay; import java.util.LinkedList; import java.util.List; import nl.sogeti.android.gpstracker.viewer.map.LoggerMap; import android.graphics.Canvas; import android.os.Handler; import android.util.Log; import com.google.android.maps.GeoPoint; public class BitmapSegmentsOverlay extends AsyncOverlay { private static final String TAG = "GG.BitmapSegmentsOverlay"; List<SegmentRendering> mOverlays; Handler mOverlayHandler; public BitmapSegmentsOverlay(LoggerMap loggermap, Handler handler) { super(loggermap, handler); mOverlays = new LinkedList<SegmentRendering>(); mOverlayHandler = handler; } @Override synchronized protected void redrawOffscreen(Canvas asyncBuffer, LoggerMap loggermap) { for (SegmentRendering segment : mOverlays) { segment.draw(asyncBuffer); } } @Override public synchronized void scheduleRecalculation() { for (SegmentRendering segment : mOverlays) { segment.calculateMedia(); segment.calculateTrack(); } } @Override synchronized protected boolean commonOnTap(GeoPoint tappedGeoPoint) { boolean handled = false; for (SegmentRendering segment : mOverlays) { if (!handled) { handled = segment.commonOnTap(tappedGeoPoint); } } return handled; } synchronized public void addSegment(SegmentRendering segment) { segment.setBitmapHolder(this); mOverlays.add(segment); } synchronized public void clearSegments() { for (SegmentRendering segment : mOverlays) { segment.closeResources(); } mOverlays.clear(); reset(); } synchronized public void setTrackColoringMethod(int color, double speed, double height) { for (SegmentRendering segment : mOverlays) { segment.setTrackColoringMethod(color, speed, height); } scheduleRecalculation(); } public int size() { return mOverlays.size(); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/map/overlay/BitmapSegmentsOverlay.java
Java
gpl3
2,092
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.viewer.map.overlay; import com.mapquest.android.maps.Overlay; public interface OverlayProvider { public com.google.android.maps.Overlay getGoogleOverlay(); public org.osmdroid.views.overlay.Overlay getOSMOverlay(); public Overlay getMapQuestOverlay(); }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/map/overlay/OverlayProvider.java
Java
gpl3
1,824
/* * Written by Pieter @ android-developers on groups.google.com * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.viewer.map.overlay; import nl.sogeti.android.gpstracker.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.location.Location; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Projection; /** * Fix for a ClassCastException found on some Google Maps API's implementations. * @see <a href="http://www.spectrekking.com/download/FixedMyLocationOverlay.java">www.spectrekking.com</a> * @version $Id$ */ public class FixedMyLocationOverlay extends MyLocationOverlay { private boolean bugged = false; private Paint accuracyPaint; private Point center; private Point left; private Drawable drawable; private int width; private int height; public FixedMyLocationOverlay(Context context, MapView mapView) { super(context, mapView); } @Override protected void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLoc, long when) { if (!bugged) { try { super.drawMyLocation(canvas, mapView, lastFix, myLoc, when); } catch (Exception e) { bugged = true; } } if (bugged) { if (drawable == null) { if( accuracyPaint == null ) { accuracyPaint = new Paint(); accuracyPaint.setAntiAlias(true); accuracyPaint.setStrokeWidth(2.0f); } drawable = mapView.getContext().getResources().getDrawable(R.drawable.mylocation); width = drawable.getIntrinsicWidth(); height = drawable.getIntrinsicHeight(); center = new Point(); left = new Point(); } Projection projection = mapView.getProjection(); double latitude = lastFix.getLatitude(); double longitude = lastFix.getLongitude(); float accuracy = lastFix.getAccuracy(); float[] result = new float[1]; Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result); float longitudeLineDistance = result[0]; GeoPoint leftGeo = new GeoPoint((int)(latitude*1e6), (int)((longitude-accuracy/longitudeLineDistance)*1e6)); projection.toPixels(leftGeo, left); projection.toPixels(myLoc, center); int radius = center.x - left.x; accuracyPaint.setColor(0xff6666ff); accuracyPaint.setStyle(Style.STROKE); canvas.drawCircle(center.x, center.y, radius, accuracyPaint); accuracyPaint.setColor(0x186666ff); accuracyPaint.setStyle(Style.FILL); canvas.drawCircle(center.x, center.y, radius, accuracyPaint); drawable.setBounds(center.x - width / 2, center.y - height / 2, center.x + width / 2, center.y + height / 2); drawable.draw(canvas); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/map/overlay/FixedMyLocationOverlay.java
Java
gpl3
3,919
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.viewer.map; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.SlidingIndicatorView; import nl.sogeti.android.gpstracker.viewer.map.overlay.FixedMyLocationOverlay; import nl.sogeti.android.gpstracker.viewer.map.overlay.OverlayProvider; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap; import android.graphics.Point; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.BaseAdapter; import android.widget.TextView; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; /** * Main activity showing a track and allowing logging control * * @version $Id$ * @author rene (c) Jan 18, 2009, Sogeti B.V. */ public class GoogleLoggerMap extends MapActivity implements LoggerMap { LoggerMapHelper mHelper; private MapView mMapView; private TextView[] mSpeedtexts; private TextView mLastGPSSpeedView; private TextView mLastGPSAltitudeView; private TextView mDistanceView; private FixedMyLocationOverlay mMylocation; /** * Called when the activity is first created. */ @Override protected void onCreate(Bundle load) { super.onCreate(load); setContentView(R.layout.map_google); mHelper = new LoggerMapHelper(this); mMapView = (MapView) findViewById(R.id.myMapView); mMylocation = new FixedMyLocationOverlay(this, mMapView); mMapView.setBuiltInZoomControls(true); TextView[] speeds = { (TextView) findViewById(R.id.speedview05), (TextView) findViewById(R.id.speedview04), (TextView) findViewById(R.id.speedview03), (TextView) findViewById(R.id.speedview02), (TextView) findViewById(R.id.speedview01), (TextView) findViewById(R.id.speedview00) }; mSpeedtexts = speeds; mLastGPSSpeedView = (TextView) findViewById(R.id.currentSpeed); mLastGPSAltitudeView = (TextView) findViewById(R.id.currentAltitude); mDistanceView = (TextView) findViewById(R.id.currentDistance); mHelper.onCreate(load); } @Override protected void onResume() { super.onResume(); mHelper.onResume(); } @Override protected void onPause() { mHelper.onPause(); super.onPause(); } @Override protected void onDestroy() { mHelper.onDestroy(); super.onDestroy(); } @Override public void onNewIntent(Intent newIntent) { mHelper.onNewIntent(newIntent); } @Override protected void onRestoreInstanceState(Bundle load) { if (load != null) { super.onRestoreInstanceState(load); } mHelper.onRestoreInstanceState(load); } @Override protected void onSaveInstanceState(Bundle save) { super.onSaveInstanceState(save); mHelper.onSaveInstanceState(save); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); mHelper.onCreateOptionsMenu(menu); return result; } @Override public boolean onPrepareOptionsMenu(Menu menu) { mHelper.onPrepareOptionsMenu(menu); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = mHelper.onOptionsItemSelected(item); if( !handled ) { handled = super.onOptionsItemSelected(item); } return handled; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); mHelper.onActivityResult(requestCode, resultCode, intent); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean propagate = true; switch (keyCode) { case KeyEvent.KEYCODE_S: setSatelliteOverlay(!this.mMapView.isSatellite()); propagate = false; break; case KeyEvent.KEYCODE_A: setTrafficOverlay(!this.mMapView.isTraffic()); propagate = false; break; default: propagate = mHelper.onKeyDown(keyCode, event); if( propagate ) { propagate = super.onKeyDown(keyCode, event); } break; } return propagate; } @Override protected Dialog onCreateDialog(int id) { Dialog dialog = mHelper.onCreateDialog(id); if( dialog == null ) { dialog = super.onCreateDialog(id); } return dialog; } @Override protected void onPrepareDialog(int id, Dialog dialog) { mHelper.onPrepareDialog(id, dialog); super.onPrepareDialog(id, dialog); } /******************************/ /** Own methods **/ /******************************/ private void setTrafficOverlay(boolean b) { SharedPreferences sharedPreferences = mHelper.getPreferences(); Editor editor = sharedPreferences.edit(); editor.putBoolean(Constants.TRAFFIC, b); editor.commit(); } private void setSatelliteOverlay(boolean b) { SharedPreferences sharedPreferences = mHelper.getPreferences(); Editor editor = sharedPreferences.edit(); editor.putBoolean(Constants.SATELLITE, b); editor.commit(); } @Override protected boolean isRouteDisplayed() { return true; } @Override protected boolean isLocationDisplayed() { SharedPreferences sharedPreferences = mHelper.getPreferences(); return sharedPreferences.getBoolean(Constants.LOCATION, false) || mHelper.isLogging(); } /******************************/ /** Loggermap methods **/ /******************************/ @Override public void updateOverlays() { SharedPreferences sharedPreferences = mHelper.getPreferences(); GoogleLoggerMap.this.mMapView.setSatellite(sharedPreferences.getBoolean(Constants.SATELLITE, false)); GoogleLoggerMap.this.mMapView.setTraffic(sharedPreferences.getBoolean(Constants.TRAFFIC, false)); } @Override public void setDrawingCacheEnabled(boolean b) { findViewById(R.id.mapScreen).setDrawingCacheEnabled(true); } @Override public Activity getActivity() { return this; } @Override public void onLayerCheckedChanged(int checkedId, boolean isChecked) { switch (checkedId) { case R.id.layer_google_satellite: setSatelliteOverlay(true); break; case R.id.layer_google_regular: setSatelliteOverlay(false); break; case R.id.layer_traffic: setTrafficOverlay(isChecked); break; default: break; } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.TRAFFIC)) { updateOverlays(); } else if (key.equals(Constants.SATELLITE)) { updateOverlays(); } } @Override public Bitmap getDrawingCache() { return findViewById(R.id.mapScreen).getDrawingCache(); } @Override public void showMediaDialog(BaseAdapter mediaAdapter) { mHelper.showMediaDialog(mediaAdapter); } public void onDateOverlayChanged() { mMapView.postInvalidate(); } @Override public String getDataSourceId() { return LoggerMapHelper.GOOGLE_PROVIDER; } @Override public boolean isOutsideScreen(GeoPoint lastPoint) { Point out = new Point(); this.mMapView.getProjection().toPixels(lastPoint, out); int height = this.mMapView.getHeight(); int width = this.mMapView.getWidth(); return (out.x < 0 || out.y < 0 || out.y > height || out.x > width); } @Override public boolean isNearScreenEdge(GeoPoint lastPoint) { Point out = new Point(); this.mMapView.getProjection().toPixels(lastPoint, out); int height = this.mMapView.getHeight(); int width = this.mMapView.getWidth(); return (out.x < width / 4 || out.y < height / 4 || out.x > (width / 4) * 3 || out.y > (height / 4) * 3); } @Override public void executePostponedActions() { // NOOP for Google Maps } @Override public void enableCompass() { mMylocation.enableCompass(); } @Override public void enableMyLocation() { mMylocation.enableMyLocation(); } @Override public void disableMyLocation() { mMylocation.disableMyLocation(); } @Override public void disableCompass() { mMylocation.disableCompass(); } @Override public void setZoom(int zoom) { mMapView.getController().setZoom(zoom); } @Override public void animateTo(GeoPoint storedPoint) { mMapView.getController().animateTo(storedPoint); } @Override public int getZoomLevel() { return mMapView.getZoomLevel(); } @Override public GeoPoint getMapCenter() { return mMapView.getMapCenter(); } @Override public boolean zoomOut() { return mMapView.getController().zoomOut(); } @Override public boolean zoomIn() { return mMapView.getController().zoomIn(); } @Override public void postInvalidate() { mMapView.postInvalidate(); } @Override public void clearAnimation() { mMapView.clearAnimation(); } @Override public void setCenter(GeoPoint lastPoint) { mMapView.getController().setCenter(lastPoint); } @Override public int getMaxZoomLevel() { return mMapView.getMaxZoomLevel(); } @Override public GeoPoint fromPixels(int x, int y) { return mMapView.getProjection().fromPixels(x, y); } @Override public boolean hasProjection() { return mMapView.getProjection() != null; } @Override public float metersToEquatorPixels(float float1) { return mMapView.getProjection().metersToEquatorPixels(float1); } @Override public void toPixels(GeoPoint geoPoint, Point screenPoint) { mMapView.getProjection().toPixels(geoPoint, screenPoint); } @Override public TextView[] getSpeedTextViews() { return mSpeedtexts; } @Override public TextView getAltitideTextView() { return mLastGPSAltitudeView; } @Override public TextView getSpeedTextView() { return mLastGPSSpeedView; } @Override public TextView getDistanceTextView() { return mDistanceView; } @Override public void addOverlay(OverlayProvider overlay) { mMapView.getOverlays().add(overlay.getGoogleOverlay()); } @Override public void clearOverlays() { mMapView.getOverlays().clear(); } @Override public SlidingIndicatorView getScaleIndicatorView() { return (SlidingIndicatorView) findViewById(R.id.scaleindicator); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/map/GoogleLoggerMap.java
Java
gpl3
12,883
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Feb 26, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.viewer.map; import nl.sogeti.android.gpstracker.util.SlidingIndicatorView; import nl.sogeti.android.gpstracker.viewer.map.overlay.OverlayProvider; import android.app.Activity; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Point; import android.widget.BaseAdapter; import android.widget.TextView; import com.google.android.maps.GeoPoint; /** * ???? * * @version $Id$ * @author rene (c) Feb 26, 2012, Sogeti B.V. */ public interface LoggerMap { void setDrawingCacheEnabled(boolean b); Activity getActivity(); void updateOverlays(); void onLayerCheckedChanged(int checkedId, boolean b); void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key); Bitmap getDrawingCache(); void showMediaDialog(BaseAdapter mediaAdapter); String getDataSourceId(); boolean isOutsideScreen(GeoPoint lastPoint); boolean isNearScreenEdge(GeoPoint lastPoint); void executePostponedActions(); void disableMyLocation(); void disableCompass(); void setZoom(int int1); void animateTo(GeoPoint storedPoint); int getZoomLevel(); GeoPoint getMapCenter(); boolean zoomOut(); boolean zoomIn(); void postInvalidate(); void enableCompass(); void enableMyLocation(); void addOverlay(OverlayProvider overlay); void clearAnimation(); void setCenter(GeoPoint lastPoint); int getMaxZoomLevel(); GeoPoint fromPixels(int x, int y); boolean hasProjection(); float metersToEquatorPixels(float float1); void toPixels(GeoPoint geopoint, Point screenPoint); TextView[] getSpeedTextViews(); TextView getAltitideTextView(); TextView getSpeedTextView(); TextView getDistanceTextView(); void clearOverlays(); SlidingIndicatorView getScaleIndicatorView(); }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/map/LoggerMap.java
Java
gpl3
2,656
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.viewer; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.actions.DescribeTrack; import nl.sogeti.android.gpstracker.actions.Statistics; import nl.sogeti.android.gpstracker.actions.tasks.GpxParser; import nl.sogeti.android.gpstracker.actions.utils.ProgressListener; import nl.sogeti.android.gpstracker.adapter.BreadcrumbsAdapter; import nl.sogeti.android.gpstracker.adapter.SectionedListAdapter; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService; import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService.LocalBinder; import nl.sogeti.android.gpstracker.db.DatabaseHelper; import nl.sogeti.android.gpstracker.db.GPStracking; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.Pair; import nl.sogeti.android.gpstracker.viewer.map.CommonLoggerMap; import nl.sogeti.android.gpstracker.viewer.map.LoggerMap; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ListActivity; import android.app.SearchManager; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * Show a list view of all tracks, also doubles for showing search results * * @version $Id$ * @author rene (c) Jan 11, 2009, Sogeti B.V. */ public class TrackList extends ListActivity implements ProgressListener { private static final String TAG = "OGT.TrackList"; private static final int MENU_DETELE = Menu.FIRST + 0; private static final int MENU_SHARE = Menu.FIRST + 1; private static final int MENU_RENAME = Menu.FIRST + 2; private static final int MENU_STATS = Menu.FIRST + 3; private static final int MENU_SEARCH = Menu.FIRST + 4; private static final int MENU_VACUUM = Menu.FIRST + 5; private static final int MENU_PICKER = Menu.FIRST + 6; private static final int MENU_BREADCRUMBS = Menu.FIRST + 7; public static final int DIALOG_FILENAME = Menu.FIRST + 22; private static final int DIALOG_RENAME = Menu.FIRST + 23; private static final int DIALOG_DELETE = Menu.FIRST + 24; private static final int DIALOG_VACUUM = Menu.FIRST + 25; private static final int DIALOG_IMPORT = Menu.FIRST + 26; private static final int DIALOG_INSTALL = Menu.FIRST + 27; protected static final int DIALOG_ERROR = Menu.FIRST + 28; private static final int PICKER_OI = Menu.FIRST + 29; private static final int DESCRIBE = Menu.FIRST + 30; private BreadcrumbsAdapter mBreadcrumbAdapter; private EditText mTrackNameView; private Uri mDialogTrackUri; private String mDialogCurrentName = ""; private String mErrorDialogMessage; private Exception mErrorDialogException; private Runnable mImportAction; private String mImportTrackName; private String mErrorTask; /** * Progress listener for the background tasks uploading to gobreadcrumbs */ private ProgressListener mExportListener; private int mPausePosition; private BreadcrumbsService mService; boolean mBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_PROGRESS); this.setContentView(R.layout.tracklist); displayIntent(getIntent()); ListView listView = getListView(); listView.setItemsCanFocus(true); // Add the context menu (the long press thing) registerForContextMenu(listView); if (savedInstanceState != null) { getListView().setSelection(savedInstanceState.getInt("POSITION")); } IntentFilter filter = new IntentFilter(); filter.addAction(BreadcrumbsService.NOTIFY_DATA_SET_CHANGED); registerReceiver(mReceiver, filter); Intent service = new Intent(this, BreadcrumbsService.class); startService(service); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, BreadcrumbsService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onResume() { if (mPausePosition != 0) { getListView().setSelection(mPausePosition); } super.onResume(); } @Override protected void onPause() { mPausePosition = getListView().getFirstVisiblePosition(); super.onPause(); } @Override protected void onStop() { if (mBound) { unbindService(mConnection); mBound = false; mService = null; } super.onStop(); } @Override protected void onDestroy() { if (isFinishing()) { Intent service = new Intent(this, BreadcrumbsService.class); stopService(service); } unregisterReceiver(mReceiver); super.onDestroy(); } @Override public void onNewIntent(Intent newIntent) { displayIntent(newIntent); } /* * (non-Javadoc) * @see android.app.ListActivity#onRestoreInstanceState(android.os.Bundle) */ @Override protected void onRestoreInstanceState(Bundle state) { super.onRestoreInstanceState(state); mDialogTrackUri = state.getParcelable("URI"); mDialogCurrentName = state.getString("NAME"); mDialogCurrentName = mDialogCurrentName != null ? mDialogCurrentName : ""; getListView().setSelection(state.getInt("POSITION")); } /* * (non-Javadoc) * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable("URI", mDialogTrackUri); outState.putString("NAME", mDialogCurrentName); outState.putInt("POSITION", getListView().getFirstVisiblePosition()); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); menu.add(ContextMenu.NONE, MENU_SEARCH, ContextMenu.NONE, android.R.string.search_go).setIcon(android.R.drawable.ic_search_category_default).setAlphabeticShortcut(SearchManager.MENU_KEY); menu.add(ContextMenu.NONE, MENU_VACUUM, ContextMenu.NONE, R.string.menu_vacuum).setIcon(android.R.drawable.ic_menu_crop); menu.add(ContextMenu.NONE, MENU_PICKER, ContextMenu.NONE, R.string.menu_picker).setIcon(android.R.drawable.ic_menu_add); menu.add(ContextMenu.NONE, MENU_BREADCRUMBS, ContextMenu.NONE, R.string.dialog_breadcrumbsconnect).setIcon(android.R.drawable.ic_menu_revert); return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = false; switch (item.getItemId()) { case MENU_SEARCH: onSearchRequested(); handled = true; break; case MENU_VACUUM: showDialog(DIALOG_VACUUM); break; case MENU_PICKER: try { Intent intent = new Intent("org.openintents.action.PICK_FILE"); intent.putExtra("org.openintents.extra.TITLE", getString(R.string.dialog_import_picker)); intent.putExtra("org.openintents.extra.BUTTON_TEXT", getString(R.string.menu_picker)); startActivityForResult(intent, PICKER_OI); } catch (ActivityNotFoundException e) { showDialog(DIALOG_INSTALL); } break; case MENU_BREADCRUMBS: mService.removeAuthentication(); mService.clearAllCache(); mService.collectBreadcrumbsOauthToken(); break; default: handled = super.onOptionsItemSelected(item); } return handled; } @Override protected void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); Object item = listView.getItemAtPosition(position); if (item instanceof String) { if (Constants.BREADCRUMBS_CONNECT.equals(item)) { mService.collectBreadcrumbsOauthToken(); } } else if (item instanceof Pair< ? , ? >) { @SuppressWarnings("unchecked") final Pair<Integer, Integer> track = (Pair<Integer, Integer>) item; if (track.first == Constants.BREADCRUMBS_TRACK_ITEM_VIEW_TYPE) { TextView tv = (TextView) view.findViewById(R.id.listitem_name); mImportTrackName = tv.getText().toString(); mImportAction = new Runnable() { @Override public void run() { mService.startDownloadTask(TrackList.this, TrackList.this, track); } }; showDialog(DIALOG_IMPORT); } } else { Intent intent = new Intent(); Uri trackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, id); intent.setData(trackUri); ComponentName caller = this.getCallingActivity(); if (caller != null) { setResult(RESULT_OK, intent); finish(); } else { intent.setClass(this, CommonLoggerMap.class); startActivity(intent); } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { if (menuInfo instanceof AdapterView.AdapterContextMenuInfo) { AdapterView.AdapterContextMenuInfo itemInfo = (AdapterView.AdapterContextMenuInfo) menuInfo; TextView textView = (TextView) itemInfo.targetView.findViewById(R.id.listitem_name); if (textView != null) { menu.setHeaderTitle(textView.getText()); } Object listItem = getListAdapter().getItem(itemInfo.position); if (listItem instanceof Cursor) { menu.add(0, MENU_STATS, 0, R.string.menu_statistics); menu.add(0, MENU_SHARE, 0, R.string.menu_shareTrack); menu.add(0, MENU_RENAME, 0, R.string.menu_renameTrack); menu.add(0, MENU_DETELE, 0, R.string.menu_deleteTrack); } } } @Override public boolean onContextItemSelected(MenuItem item) { boolean handled = false; AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "Bad menuInfo", e); return handled; } Object listItem = getListAdapter().getItem(info.position); if (listItem instanceof Cursor) { Cursor cursor = (Cursor) listItem; mDialogTrackUri = ContentUris.withAppendedId(Tracks.CONTENT_URI, cursor.getLong(0)); mDialogCurrentName = cursor.getString(1); mDialogCurrentName = mDialogCurrentName != null ? mDialogCurrentName : ""; switch (item.getItemId()) { case MENU_DETELE: { showDialog(DIALOG_DELETE); handled = true; break; } case MENU_SHARE: { Intent actionIntent = new Intent(Intent.ACTION_RUN); actionIntent.setDataAndType(mDialogTrackUri, Tracks.CONTENT_ITEM_TYPE); actionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(actionIntent, getString(R.string.share_track))); handled = true; break; } case MENU_RENAME: { showDialog(DIALOG_RENAME); handled = true; break; } case MENU_STATS: { Intent actionIntent = new Intent(this, Statistics.class); actionIntent.setData(mDialogTrackUri); startActivity(actionIntent); handled = true; break; } default: handled = super.onContextItemSelected(item); break; } } return handled; } /* * (non-Javadoc) * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; Builder builder = null; switch (id) { case DIALOG_RENAME: LayoutInflater factory = LayoutInflater.from(this); View view = factory.inflate(R.layout.namedialog, null); mTrackNameView = (EditText) view.findViewById(R.id.nameField); builder = new AlertDialog.Builder(this).setTitle(R.string.dialog_routename_title).setMessage(R.string.dialog_routename_message).setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_okay, mRenameOnClickListener).setNegativeButton(R.string.btn_cancel, null).setView(view); dialog = builder.create(); return dialog; case DIALOG_DELETE: builder = new AlertDialog.Builder(TrackList.this).setTitle(R.string.dialog_delete_title).setIcon(android.R.drawable.ic_dialog_alert).setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, mDeleteOnClickListener); dialog = builder.create(); String messageFormat = this.getResources().getString(R.string.dialog_delete_message); String message = String.format(messageFormat, ""); ((AlertDialog) dialog).setMessage(message); return dialog; case DIALOG_VACUUM: builder = new AlertDialog.Builder(TrackList.this).setTitle(R.string.dialog_vacuum_title).setMessage(R.string.dialog_vacuum_message).setIcon(android.R.drawable.ic_dialog_alert) .setNegativeButton(android.R.string.cancel, null).setPositiveButton(android.R.string.ok, mVacuumOnClickListener); dialog = builder.create(); return dialog; case DIALOG_IMPORT: builder = new AlertDialog.Builder(TrackList.this).setTitle(R.string.dialog_import_title).setMessage(getString(R.string.dialog_import_message, mImportTrackName)) .setIcon(android.R.drawable.ic_dialog_alert).setNegativeButton(android.R.string.cancel, null).setPositiveButton(android.R.string.ok, mImportOnClickListener); dialog = builder.create(); return dialog; case DIALOG_INSTALL: builder = new AlertDialog.Builder(this); builder.setTitle(R.string.dialog_nooipicker).setMessage(R.string.dialog_nooipicker_message).setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.btn_install, mOiPickerDialogListener).setNegativeButton(R.string.btn_cancel, null); dialog = builder.create(); return dialog; case DIALOG_ERROR: builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(android.R.string.dialog_alert_title).setMessage(mErrorDialogMessage).setNeutralButton(android.R.string.cancel, null); dialog = builder.create(); return dialog; default: return super.onCreateDialog(id); } } /* * (non-Javadoc) * @see android.app.Activity#onPrepareDialog(int, android.app.Dialog) */ @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); AlertDialog alert; String message; switch (id) { case DIALOG_RENAME: mTrackNameView.setText(mDialogCurrentName); mTrackNameView.setSelection(0, mDialogCurrentName.length()); break; case DIALOG_DELETE: alert = (AlertDialog) dialog; String messageFormat = this.getResources().getString(R.string.dialog_delete_message); message = String.format(messageFormat, mDialogCurrentName); alert.setMessage(message); break; case DIALOG_ERROR: alert = (AlertDialog) dialog; message = "Failed task:\n" + mErrorTask; message += "\n\n"; message += "Reason:\n" + mErrorDialogMessage; if (mErrorDialogException != null) { message += " (" + mErrorDialogException.getMessage() + ") "; } alert.setMessage(message); break; case DIALOG_IMPORT: alert = (AlertDialog) dialog; alert.setMessage(getString(R.string.dialog_import_message, mImportTrackName)); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_CANCELED) { switch (requestCode) { case PICKER_OI: new GpxParser(TrackList.this, TrackList.this).execute(data.getData()); break; case DESCRIBE: Uri trackUri = data.getData(); String name; if (data.getExtras() != null && data.getExtras().containsKey(Constants.NAME)) { name = data.getExtras().getString(Constants.NAME); } else { name = "shareToGobreadcrumbs"; } mService.startUploadTask(TrackList.this, mExportListener, trackUri, name); break; default: super.onActivityResult(requestCode, resultCode, data); break; } } else { if (requestCode == DESCRIBE) { mBreadcrumbAdapter.notifyDataSetChanged(); } } } private void displayIntent(Intent intent) { final String queryAction = intent.getAction(); final String orderby = Tracks.CREATION_TIME + " DESC"; Cursor tracksCursor = null; if (Intent.ACTION_SEARCH.equals(queryAction)) { // Got to SEARCH a query for tracks, make a list tracksCursor = doSearchWithIntent(intent); } else if (Intent.ACTION_VIEW.equals(queryAction)) { final Uri uri = intent.getData(); if ("content".equals(uri.getScheme()) && GPStracking.AUTHORITY.equals(uri.getAuthority())) { // Got to VIEW a single track, instead hand it of to the LoggerMap Intent notificationIntent = new Intent(this, LoggerMap.class); notificationIntent.setData(uri); startActivity(notificationIntent); finish(); } else if (uri.getScheme().equals("file") || uri.getScheme().equals("content")) { mImportTrackName = uri.getLastPathSegment(); // Got to VIEW a GPX filename mImportAction = new Runnable() { @Override public void run() { new GpxParser(TrackList.this, TrackList.this).execute(uri); } }; showDialog(DIALOG_IMPORT); tracksCursor = managedQuery(Tracks.CONTENT_URI, new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, null, null, orderby); } else { Log.e(TAG, "Unable to VIEW " + uri); } } else { // Got to nothing, make a list of everything tracksCursor = managedQuery(Tracks.CONTENT_URI, new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, null, null, orderby); } displayCursor(tracksCursor); } private void displayCursor(Cursor tracksCursor) { SectionedListAdapter sectionedAdapter = new SectionedListAdapter(this); String[] fromColumns = new String[] { Tracks.NAME, Tracks.CREATION_TIME, Tracks._ID }; int[] toItems = new int[] { R.id.listitem_name, R.id.listitem_from, R.id.bcSyncedCheckBox }; SimpleCursorAdapter trackAdapter = new SimpleCursorAdapter(this, R.layout.trackitem, tracksCursor, fromColumns, toItems); mBreadcrumbAdapter = new BreadcrumbsAdapter(this, mService); sectionedAdapter.addSection("Local", trackAdapter); sectionedAdapter.addSection("www.gobreadcrumbs.com", mBreadcrumbAdapter); // Enrich the track adapter with Breadcrumbs adapter data trackAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, final Cursor cursor, int columnIndex) { if (columnIndex == 0) { final long trackId = cursor.getLong(0); final String trackName = cursor.getString(1); // Show the check if Breadcrumbs is online final CheckBox checkbox = (CheckBox) view; final ProgressBar progressbar = (ProgressBar) ((View) view.getParent()).findViewById(R.id.bcExportProgress); if (mService != null && mService.isAuthorized()) { checkbox.setVisibility(View.VISIBLE); // Disable the checkbox if marked online boolean isOnline = mService.isLocalTrackSynced(trackId); checkbox.setEnabled(!isOnline); // Check the checkbox if determined synced boolean isSynced = mService.isLocalTrackSynced(trackId); checkbox.setOnCheckedChangeListener(null); checkbox.setChecked(isSynced); checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // Start a description of the track Intent namingIntent = new Intent(TrackList.this, DescribeTrack.class); namingIntent.setData(ContentUris.withAppendedId(Tracks.CONTENT_URI, trackId)); namingIntent.putExtra(Constants.NAME, trackName); mExportListener = new ProgressListener() { @Override public void setIndeterminate(boolean indeterminate) { progressbar.setIndeterminate(indeterminate); } @Override public void started() { checkbox.setVisibility(View.INVISIBLE); progressbar.setVisibility(View.VISIBLE); } @Override public void finished(Uri result) { checkbox.setVisibility(View.VISIBLE); progressbar.setVisibility(View.INVISIBLE); progressbar.setIndeterminate(false); } @Override public void setProgress(int value) { progressbar.setProgress(value); } @Override public void showError(String task, String errorMessage, Exception exception) { TrackList.this.showError(task, errorMessage, exception); } }; startActivityForResult(namingIntent, DESCRIBE); } } }); } else { checkbox.setVisibility(View.INVISIBLE); checkbox.setOnCheckedChangeListener(null); } return true; } return false; } }); setListAdapter(sectionedAdapter); } private Cursor doSearchWithIntent(final Intent queryIntent) { final String queryString = queryIntent.getStringExtra(SearchManager.QUERY); Cursor cursor = managedQuery(Tracks.CONTENT_URI, new String[] { Tracks._ID, Tracks.NAME, Tracks.CREATION_TIME }, "name LIKE ?", new String[] { "%" + queryString + "%" }, null); return cursor; } /*******************************************************************/ /** ProgressListener interface and UI actions (non-Javadoc) **/ /*******************************************************************/ @Override public void setIndeterminate(boolean indeterminate) { setProgressBarIndeterminate(indeterminate); } @Override public void started() { setProgressBarVisibility(true); setProgress(Window.PROGRESS_START); } @Override public void finished(Uri result) { setProgressBarVisibility(false); setProgressBarIndeterminate(false); } @Override public void showError(String task, String errorDialogMessage, Exception errorDialogException) { mErrorTask = task; mErrorDialogMessage = errorDialogMessage; mErrorDialogException = errorDialogException; Log.e(TAG, errorDialogMessage, errorDialogException); if (!isFinishing()) { showDialog(DIALOG_ERROR); } setProgressBarVisibility(false); setProgressBarIndeterminate(false); } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; mBreadcrumbAdapter.setService(mService); } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; mService = null; } }; private OnClickListener mDeleteOnClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { getContentResolver().delete(mDialogTrackUri, null, null); } }; private OnClickListener mRenameOnClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Log.d( TAG, "Context item selected: "+mDialogUri+" with name "+mDialogCurrentName ); String trackName = mTrackNameView.getText().toString(); ContentValues values = new ContentValues(); values.put(Tracks.NAME, trackName); TrackList.this.getContentResolver().update(mDialogTrackUri, values, null, null); } }; private OnClickListener mVacuumOnClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { DatabaseHelper helper = new DatabaseHelper(TrackList.this); helper.vacuum(); } }; private OnClickListener mImportOnClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mImportAction.run(); } }; private final DialogInterface.OnClickListener mOiPickerDialogListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Uri oiDownload = Uri.parse("market://details?id=org.openintents.filemanager"); Intent oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload); try { startActivity(oiAboutIntent); } catch (ActivityNotFoundException e) { oiDownload = Uri.parse("http://openintents.googlecode.com/files/FileManager-1.1.3.apk"); oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload); startActivity(oiAboutIntent); } } }; private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (BreadcrumbsService.NOTIFY_DATA_SET_CHANGED.equals(intent.getAction())) { mBreadcrumbAdapter.updateItemList(); } } }; }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/TrackList.java
Java
gpl3
32,071
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.viewer; import java.util.regex.Pattern; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.util.UnitsI18n; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; /** * Controller for the settings dialog * * @version $Id: ApplicationPreferenceActivity.java 1146 2011-11-05 11:36:51Z * rcgroot $ * @author rene (c) Jan 18, 2009, Sogeti B.V. */ public class ApplicationPreferenceActivity extends PreferenceActivity { public static final String STREAMBROADCAST_PREFERENCE = "streambroadcast_distance"; public static final String UNITS_IMPLEMENT_WIDTH_PREFERENCE = "units_implement_width"; public static final String CUSTOMPRECISIONDISTANCE_PREFERENCE = "customprecisiondistance"; public static final String CUSTOMPRECISIONTIME_PREFERENCE = "customprecisiontime"; public static final String PRECISION_PREFERENCE = "precision"; public static final String CUSTOMUPLOAD_BACKLOG = "CUSTOMUPLOAD_BACKLOG"; public static final String CUSTOMUPLOAD_URL = "CUSTOMUPLOAD_URL"; private EditTextPreference time; private EditTextPreference distance; private EditTextPreference implentWidth; private EditTextPreference streambroadcast_distance; private EditTextPreference custumupload_backlog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.layout.settings); ListPreference precision = (ListPreference) findPreference(PRECISION_PREFERENCE); time = (EditTextPreference) findPreference(CUSTOMPRECISIONTIME_PREFERENCE); distance = (EditTextPreference) findPreference(CUSTOMPRECISIONDISTANCE_PREFERENCE); implentWidth = (EditTextPreference) findPreference(UNITS_IMPLEMENT_WIDTH_PREFERENCE); streambroadcast_distance = (EditTextPreference) findPreference(STREAMBROADCAST_PREFERENCE); custumupload_backlog = (EditTextPreference) findPreference(CUSTOMUPLOAD_BACKLOG); setEnabledCustomValues(precision.getValue()); precision.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { setEnabledCustomValues(newValue); return true; } }); implentWidth.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String fpExpr = "\\d{1,4}([,\\.]\\d+)?"; return Pattern.matches(fpExpr, newValue.toString()); } }); streambroadcast_distance.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String fpExpr = "\\d{1,5}"; boolean matches = Pattern.matches(fpExpr, newValue.toString()); if (matches) { Editor editor = getPreferenceManager().getSharedPreferences().edit(); double value = new UnitsI18n(ApplicationPreferenceActivity.this).conversionFromLocalToMeters(Integer.parseInt(newValue.toString())); editor.putFloat("streambroadcast_distance_meter", (float) value); editor.commit(); } return matches; } }); custumupload_backlog.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String fpExpr = "\\d{1,3}"; return Pattern.matches(fpExpr, newValue.toString()); } }); } private void setEnabledCustomValues(Object newValue) { boolean customPresicion = Integer.toString(Constants.LOGGING_CUSTOM).equals(newValue); time.setEnabled(customPresicion); distance.setEnabled(customPresicion); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/ApplicationPreferenceActivity.java
Java
gpl3
5,868
/*------------------------------------------------------------------------------ ** Ident: Delivery Center Java ** Author: rene ** Copyright: (c) Feb 25, 2012 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ */ package nl.sogeti.android.gpstracker.viewer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import nl.sogeti.android.gpstracker.R; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.util.Log; import android.webkit.WebView; import android.widget.TextView; /** * ???? * * @version $Id:$ * @author rene (c) Feb 25, 2012, Sogeti B.V. */ public class About extends Activity { private static final String TAG = "OGT.About"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); fillContentFields(); } private void fillContentFields() { TextView version = (TextView) findViewById(R.id.version); try { version.setText(getPackageManager().getPackageInfo(getPackageName(), 0).versionName); } catch (NameNotFoundException e) { version.setText(""); } WebView license = (WebView) findViewById(R.id.license_body); license.loadUrl("file:///android_asset/license_short.html"); WebView contributions = (WebView) findViewById(R.id.contribution_body); contributions.loadUrl("file:///android_asset/contributions.html"); WebView notice = (WebView) findViewById(R.id.notices_body); notice.loadUrl("file:///android_asset/notices.html"); } public static String readRawTextFile(Context ctx, int resId) { InputStream inputStream = ctx.getResources().openRawResource(resId); InputStreamReader inputreader = new InputStreamReader(inputStream); BufferedReader buffreader = new BufferedReader(inputreader); String line; StringBuilder text = new StringBuilder(); try { while ((line = buffreader.readLine()) != null) { text.append(line); text.append('\n'); } } catch (IOException e) { Log.e(TAG, "Failed to read raw text resource", e); } return text.toString(); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/About.java
Java
gpl3
2,985
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.viewer; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.LiveFolders; /** * Activity to build a data set to be shown in a live folder in a Android desktop * * @version $Id$ * @author rene (c) Mar 22, 2009, Sogeti B.V. */ public class TracksLiveFolder extends Activity { @Override protected void onCreate( Bundle savedInstanceState ) { this.setVisible( false ); super.onCreate( savedInstanceState ); final Intent intent = getIntent(); final String action = intent.getAction(); if( LiveFolders.ACTION_CREATE_LIVE_FOLDER.equals( action ) ) { final Intent baseAction = new Intent( Intent.ACTION_VIEW, GPStracking.Tracks.CONTENT_URI ); Uri liveData = Uri.withAppendedPath( GPStracking.CONTENT_URI, "live_folders/tracks" ); final Intent createLiveFolder = new Intent(); createLiveFolder.setData( liveData ); createLiveFolder.putExtra( LiveFolders.EXTRA_LIVE_FOLDER_NAME, getString(R.string.track_list) ); createLiveFolder.putExtra( LiveFolders.EXTRA_LIVE_FOLDER_ICON, Intent.ShortcutIconResource.fromContext( this, R.drawable.live ) ); createLiveFolder.putExtra( LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, LiveFolders.DISPLAY_MODE_LIST ); createLiveFolder.putExtra( LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT, baseAction ); setResult( RESULT_OK, createLiveFolder ); } else { setResult( RESULT_CANCELED ); } finish(); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/viewer/TracksLiveFolder.java
Java
gpl3
3,237
package nl.sogeti.android.gpstracker.logger; import android.net.Uri; import android.location.Location; interface IGPSLoggerServiceRemote { int loggingState(); long startLogging(); void pauseLogging(); long resumeLogging(); void stopLogging(); Uri storeMediaUri(in Uri mediaUri); boolean isMediaPrepared(); void storeDerivedDataSource(in String sourceName); Location getLastWaypoint(); float getTrackedDistance(); }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/logger/IGPSLoggerServiceRemote.aidl
AIDL
gpl3
465
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.logger; import nl.sogeti.android.gpstracker.util.Constants; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.location.Location; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * Class to interact with the service that tracks and logs the locations * * @version $Id$ * @author rene (c) Jan 18, 2009, Sogeti B.V. */ public class GPSLoggerServiceManager { private static final String TAG = "OGT.GPSLoggerServiceManager"; private static final String REMOTE_EXCEPTION = "REMOTE_EXCEPTION"; private IGPSLoggerServiceRemote mGPSLoggerRemote; public final Object mStartLock = new Object(); private boolean mBound = false; /** * Class for interacting with the main interface of the service. */ private ServiceConnection mServiceConnection; private Runnable mOnServiceConnected; public GPSLoggerServiceManager(Context ctx) { ctx.startService(new Intent(Constants.SERVICENAME)); } public Location getLastWaypoint() { synchronized (mStartLock) { Location lastWaypoint = null; try { if( mBound ) { lastWaypoint = this.mGPSLoggerRemote.getLastWaypoint(); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could get lastWaypoint GPSLoggerService.", e ); } return lastWaypoint; } } public float getTrackedDistance() { synchronized (mStartLock) { float distance = 0F; try { if( mBound ) { distance = this.mGPSLoggerRemote.getTrackedDistance(); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could get tracked distance from GPSLoggerService.", e ); } return distance; } } public int getLoggingState() { synchronized (mStartLock) { int logging = Constants.UNKNOWN; try { if( mBound ) { logging = this.mGPSLoggerRemote.loggingState(); // Log.d( TAG, "mGPSLoggerRemote tells state to be "+logging ); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could stat GPSLoggerService.", e ); } return logging; } } public boolean isMediaPrepared() { synchronized (mStartLock) { boolean prepared = false; try { if( mBound ) { prepared = this.mGPSLoggerRemote.isMediaPrepared(); } else { Log.w( TAG, "Remote interface to logging service not found. Started: " + mBound ); } } catch (RemoteException e) { Log.e( TAG, "Could stat GPSLoggerService.", e ); } return prepared; } } public long startGPSLogging( String name ) { synchronized (mStartLock) { if( mBound ) { try { return this.mGPSLoggerRemote.startLogging(); } catch (RemoteException e) { Log.e( TAG, "Could not start GPSLoggerService.", e ); } } return -1; } } public void pauseGPSLogging() { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.pauseLogging(); } catch (RemoteException e) { Log.e( TAG, "Could not start GPSLoggerService.", e ); } } } } public long resumeGPSLogging() { synchronized (mStartLock) { if( mBound ) { try { return this.mGPSLoggerRemote.resumeLogging(); } catch (RemoteException e) { Log.e( TAG, "Could not start GPSLoggerService.", e ); } } return -1; } } public void stopGPSLogging() { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.stopLogging(); } catch (RemoteException e) { Log.e( GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not stop GPSLoggerService.", e ); } } else { Log.e( TAG, "No GPSLoggerRemote service connected to this manager" ); } } } public void storeDerivedDataSource( String datasource ) { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.storeDerivedDataSource( datasource ); } catch (RemoteException e) { Log.e( GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send datasource to GPSLoggerService.", e ); } } else { Log.e( TAG, "No GPSLoggerRemote service connected to this manager" ); } } } public void storeMediaUri( Uri mediaUri ) { synchronized (mStartLock) { if( mBound ) { try { this.mGPSLoggerRemote.storeMediaUri( mediaUri ); } catch (RemoteException e) { Log.e( GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send media to GPSLoggerService.", e ); } } else { Log.e( TAG, "No GPSLoggerRemote service connected to this manager" ); } } } /** * Means by which an Activity lifecycle aware object hints about binding and unbinding * * @param onServiceConnected Run on main thread after the service is bound */ public void startup( Context context, final Runnable onServiceConnected ) { // Log.d( TAG, "connectToGPSLoggerService()" ); synchronized (mStartLock) { if( !mBound ) { mOnServiceConnected = onServiceConnected; mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected( ComponentName className, IBinder service ) { synchronized (mStartLock) { // Log.d( TAG, "onServiceConnected() "+ Thread.currentThread().getId() ); GPSLoggerServiceManager.this.mGPSLoggerRemote = IGPSLoggerServiceRemote.Stub.asInterface( service ); mBound = true; } if( mOnServiceConnected != null ) { mOnServiceConnected.run(); mOnServiceConnected = null; } } @Override public void onServiceDisconnected( ComponentName className ) { synchronized (mStartLock) { // Log.d( TAG, "onServiceDisconnected()"+ Thread.currentThread().getId() ); mBound = false; } } }; context.bindService( new Intent( Constants.SERVICENAME ), this.mServiceConnection, Context.BIND_AUTO_CREATE ); } else { Log.w( TAG, "Attempting to connect whilst already connected" ); } } } /** * Means by which an Activity lifecycle aware object hints about binding and unbinding */ public void shutdown(Context context) { // Log.d( TAG, "disconnectFromGPSLoggerService()" ); synchronized (mStartLock) { try { if( mBound ) { // Log.d( TAG, "unbindService()"+this.mServiceConnection ); context.unbindService( this.mServiceConnection ); GPSLoggerServiceManager.this.mGPSLoggerRemote = null; mServiceConnection = null; mBound = false; } } catch (IllegalArgumentException e) { Log.w( TAG, "Failed to unbind a service, prehaps the service disapearded?", e ); } } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/logger/GPSLoggerServiceManager.java
Java
gpl3
10,546
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.logger; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import java.util.LinkedList; import java.util.Queue; import java.util.Timer; import java.util.TimerTask; import java.util.Vector; import java.util.concurrent.Semaphore; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.db.GPStracking.Media; import nl.sogeti.android.gpstracker.db.GPStracking.MetaData; import nl.sogeti.android.gpstracker.db.GPStracking.Tracks; import nl.sogeti.android.gpstracker.db.GPStracking.Waypoints; import nl.sogeti.android.gpstracker.streaming.StreamUtils; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.viewer.map.CommonLoggerMap; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.Cursor; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.GpsStatus.Listener; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.RingtoneManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.PowerManager; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; /** * A system service as controlling the background logging of gps locations. * * @version $Id$ * @author rene (c) Jan 22, 2009, Sogeti B.V. */ public class GPSLoggerService extends Service implements LocationListener { private static final float FINE_DISTANCE = 5F; private static final long FINE_INTERVAL = 1000l; private static final float FINE_ACCURACY = 20f; private static final float NORMAL_DISTANCE = 10F; private static final long NORMAL_INTERVAL = 15000l; private static final float NORMAL_ACCURACY = 30f; private static final float COARSE_DISTANCE = 25F; private static final long COARSE_INTERVAL = 30000l; private static final float COARSE_ACCURACY = 75f; private static final float GLOBAL_DISTANCE = 500F; private static final long GLOBAL_INTERVAL = 300000l; private static final float GLOBAL_ACCURACY = 1000f; /** * <code>MAX_REASONABLE_SPEED</code> is about 324 kilometer per hour or 201 * mile per hour. */ private static final int MAX_REASONABLE_SPEED = 90; /** * <code>MAX_REASONABLE_ALTITUDECHANGE</code> between the last few waypoints * and a new one the difference should be less then 200 meter. */ private static final int MAX_REASONABLE_ALTITUDECHANGE = 200; private static final Boolean DEBUG = false; private static final boolean VERBOSE = false; private static final String TAG = "OGT.GPSLoggerService"; private static final String SERVICESTATE_DISTANCE = "SERVICESTATE_DISTANCE"; private static final String SERVICESTATE_STATE = "SERVICESTATE_STATE"; private static final String SERVICESTATE_PRECISION = "SERVICESTATE_PRECISION"; private static final String SERVICESTATE_SEGMENTID = "SERVICESTATE_SEGMENTID"; private static final String SERVICESTATE_TRACKID = "SERVICESTATE_TRACKID"; private static final int ADDGPSSTATUSLISTENER = 0; private static final int REQUEST_FINEGPS_LOCATIONUPDATES = 1; private static final int REQUEST_NORMALGPS_LOCATIONUPDATES = 2; private static final int REQUEST_COARSEGPS_LOCATIONUPDATES = 3; private static final int REQUEST_GLOBALNETWORK_LOCATIONUPDATES = 4; private static final int REQUEST_CUSTOMGPS_LOCATIONUPDATES = 5; private static final int STOPLOOPER = 6; private static final int GPSPROBLEM = 7; private static final int LOGGING_UNAVAILABLE = R.string.service_connectiondisabled; /** * DUP from android.app.Service.START_STICKY */ private static final int START_STICKY = 1; public static final String COMMAND = "nl.sogeti.android.gpstracker.extra.COMMAND"; public static final int EXTRA_COMMAND_START = 0; public static final int EXTRA_COMMAND_PAUSE = 1; public static final int EXTRA_COMMAND_RESUME = 2; public static final int EXTRA_COMMAND_STOP = 3; private LocationManager mLocationManager; private NotificationManager mNoticationManager; private PowerManager.WakeLock mWakeLock; private Handler mHandler; /** * If speeds should be checked to sane values */ private boolean mSpeedSanityCheck; /** * If broadcasts of location about should be sent to stream location */ private boolean mStreamBroadcast; private long mTrackId = -1; private long mSegmentId = -1; private long mWaypointId = -1; private int mPrecision; private int mLoggingState = Constants.STOPPED; private boolean mStartNextSegment; private String mSources; private Location mPreviousLocation; private float mDistance; private Notification mNotification; private Vector<Location> mWeakLocations; private Queue<Double> mAltitudes; /** * <code>mAcceptableAccuracy</code> indicates the maximum acceptable accuracy * of a waypoint in meters. */ private float mMaxAcceptableAccuracy = 20; private int mSatellites = 0; private boolean mShowingGpsDisabled; /** * Should the GPS Status monitor update the notification bar */ private boolean mStatusMonitor; /** * Time thread to runs tasks that check whether the GPS listener has received * enough to consider the GPS system alive. */ private Timer mHeartbeatTimer; /** * Listens to changes in preference to precision and sanity checks */ private OnSharedPreferenceChangeListener mSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Constants.PRECISION) || key.equals(Constants.LOGGING_DISTANCE) || key.equals(Constants.LOGGING_INTERVAL)) { sendRequestLocationUpdatesMessage(); crashProtectState(); updateNotification(); broadCastLoggingState(); } else if (key.equals(Constants.SPEEDSANITYCHECK)) { mSpeedSanityCheck = sharedPreferences.getBoolean(Constants.SPEEDSANITYCHECK, true); } else if (key.equals(Constants.STATUS_MONITOR)) { mLocationManager.removeGpsStatusListener(mStatusListener); sendRequestStatusUpdateMessage(); updateNotification(); } else if(key.equals(Constants.BROADCAST_STREAM) || key.equals("VOICEOVER_ENABLED") || key.equals("CUSTOMUPLOAD_ENABLED") ) { if (key.equals(Constants.BROADCAST_STREAM)) { mStreamBroadcast = sharedPreferences.getBoolean(Constants.BROADCAST_STREAM, false); } StreamUtils.shutdownStreams(GPSLoggerService.this); if( !mStreamBroadcast ) { StreamUtils.initStreams(GPSLoggerService.this); } } } }; @Override public void onLocationChanged(Location location) { if (VERBOSE) { Log.v(TAG, "onLocationChanged( Location " + location + " )"); } ; // Might be claiming GPS disabled but when we were paused this changed and this location proves so if (mShowingGpsDisabled) { notifyOnEnabledProviderNotification(R.string.service_gpsenabled); } Location filteredLocation = locationFilter(location); if (filteredLocation != null) { if (mStartNextSegment) { mStartNextSegment = false; // Obey the start segment if the previous location is unknown or far away if (mPreviousLocation == null || filteredLocation.distanceTo(mPreviousLocation) > 4 * mMaxAcceptableAccuracy) { startNewSegment(); } } else if( mPreviousLocation != null ) { mDistance += mPreviousLocation.distanceTo(filteredLocation); } storeLocation(filteredLocation); broadcastLocation(filteredLocation); mPreviousLocation = location; } } @Override public void onProviderDisabled(String provider) { if (DEBUG) { Log.d(TAG, "onProviderDisabled( String " + provider + " )"); } ; if (mPrecision != Constants.LOGGING_GLOBAL && provider.equals(LocationManager.GPS_PROVIDER)) { notifyOnDisabledProvider(R.string.service_gpsdisabled); } else if (mPrecision == Constants.LOGGING_GLOBAL && provider.equals(LocationManager.NETWORK_PROVIDER)) { notifyOnDisabledProvider(R.string.service_datadisabled); } } @Override public void onProviderEnabled(String provider) { if (DEBUG) { Log.d(TAG, "onProviderEnabled( String " + provider + " )"); } ; if (mPrecision != Constants.LOGGING_GLOBAL && provider.equals(LocationManager.GPS_PROVIDER)) { notifyOnEnabledProviderNotification(R.string.service_gpsenabled); mStartNextSegment = true; } else if (mPrecision == Constants.LOGGING_GLOBAL && provider.equals(LocationManager.NETWORK_PROVIDER)) { notifyOnEnabledProviderNotification(R.string.service_dataenabled); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { if (DEBUG) { Log.d(TAG, "onStatusChanged( String " + provider + ", int " + status + ", Bundle " + extras + " )"); } ; if (status == LocationProvider.OUT_OF_SERVICE) { Log.e(TAG, String.format("Provider %s changed to status %d", provider, status)); } } /** * Listens to GPS status changes */ private Listener mStatusListener = new GpsStatus.Listener() { @Override public synchronized void onGpsStatusChanged(int event) { switch (event) { case GpsStatus.GPS_EVENT_SATELLITE_STATUS: if (mStatusMonitor) { GpsStatus status = mLocationManager.getGpsStatus(null); mSatellites = 0; Iterable<GpsSatellite> list = status.getSatellites(); for (GpsSatellite satellite : list) { if (satellite.usedInFix()) { mSatellites++; } } updateNotification(); } break; case GpsStatus.GPS_EVENT_STOPPED: break; case GpsStatus.GPS_EVENT_STARTED: break; default: break; } } }; private IBinder mBinder = new IGPSLoggerServiceRemote.Stub() { @Override public int loggingState() throws RemoteException { return mLoggingState; } @Override public long startLogging() throws RemoteException { GPSLoggerService.this.startLogging(); return mTrackId; } @Override public void pauseLogging() throws RemoteException { GPSLoggerService.this.pauseLogging(); } @Override public long resumeLogging() throws RemoteException { GPSLoggerService.this.resumeLogging(); return mSegmentId; } @Override public void stopLogging() throws RemoteException { GPSLoggerService.this.stopLogging(); } @Override public Uri storeMediaUri(Uri mediaUri) throws RemoteException { GPSLoggerService.this.storeMediaUri(mediaUri); return null; } @Override public boolean isMediaPrepared() throws RemoteException { return GPSLoggerService.this.isMediaPrepared(); } @Override public void storeDerivedDataSource(String sourceName) throws RemoteException { GPSLoggerService.this.storeDerivedDataSource(sourceName); } @Override public Location getLastWaypoint() throws RemoteException { return GPSLoggerService.this.getLastWaypoint(); } @Override public float getTrackedDistance() throws RemoteException { return GPSLoggerService.this.getTrackedDistance(); } }; /** * Task that will be run periodically during active logging to verify that * the logging really happens and that the GPS hasn't silently stopped. */ private TimerTask mHeartbeat = null; /** * Task to determine if the GPS is alive */ class Heartbeat extends TimerTask { private String mProvider; public Heartbeat(String provider) { mProvider = provider; } @Override public void run() { if (isLogging()) { // Collect the last location from the last logged location or a more recent from the last weak location Location checkLocation = mPreviousLocation; synchronized (mWeakLocations) { if (!mWeakLocations.isEmpty()) { if (checkLocation == null) { checkLocation = mWeakLocations.lastElement(); } else { Location weakLocation = mWeakLocations.lastElement(); checkLocation = weakLocation.getTime() > checkLocation.getTime() ? weakLocation : checkLocation; } } } // Is the last known GPS location something nearby we are not told? Location managerLocation = mLocationManager.getLastKnownLocation(mProvider); if (managerLocation != null && checkLocation != null) { if (checkLocation.distanceTo(managerLocation) < 2 * mMaxAcceptableAccuracy) { checkLocation = managerLocation.getTime() > checkLocation.getTime() ? managerLocation : checkLocation; } } if (checkLocation == null || checkLocation.getTime() + mCheckPeriod < new Date().getTime()) { Log.w(TAG, "GPS system failed to produce a location during logging: " + checkLocation); mLoggingState = Constants.PAUSED; resumeLogging(); if (mStatusMonitor) { soundGpsSignalAlarm(); } } } } }; /** * Number of milliseconds that a functioning GPS system needs to provide a * location. Calculated to be either 120 seconds or 4 times the requested * period, whichever is larger. */ private long mCheckPeriod; private float mBroadcastDistance; private long mLastTimeBroadcast; private class GPSLoggerServiceThread extends Thread { public Semaphore ready = new Semaphore(0); GPSLoggerServiceThread() { this.setName("GPSLoggerServiceThread"); } @Override public void run() { Looper.prepare(); mHandler = new Handler() { @Override public void handleMessage(Message msg) { _handleMessage(msg); } }; ready.release(); // Signal the looper and handler are created Looper.loop(); } } /** * Called by the system when the service is first created. Do not call this * method directly. Be sure to call super.onCreate(). */ @Override public void onCreate() { super.onCreate(); if (DEBUG) { Log.d(TAG, "onCreate()"); } ; GPSLoggerServiceThread looper = new GPSLoggerServiceThread(); looper.start(); try { looper.ready.acquire(); } catch (InterruptedException e) { Log.e(TAG, "Interrupted during wait for the GPSLoggerServiceThread to start, prepare for trouble!", e); } mHeartbeatTimer = new Timer("heartbeat", true); mWeakLocations = new Vector<Location>(3); mAltitudes = new LinkedList<Double>(); mLoggingState = Constants.STOPPED; mStartNextSegment = false; mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); mNoticationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); stopNotification(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mSpeedSanityCheck = sharedPreferences.getBoolean(Constants.SPEEDSANITYCHECK, true); mStreamBroadcast = sharedPreferences.getBoolean(Constants.BROADCAST_STREAM, false); boolean startImmidiatly = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.LOGATSTARTUP, false); crashRestoreState(); if (startImmidiatly && mLoggingState == Constants.STOPPED) { startLogging(); ContentValues values = new ContentValues(); values.put(Tracks.NAME, "Recorded at startup"); getContentResolver().update(ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId), values, null, null); } else { broadCastLoggingState(); } } /** * This is the old onStart method that will be called on the pre-2.0 * * @see android.app.Service#onStart(android.content.Intent, int) platform. On * 2.0 or later we override onStartCommand() so this method will not be * called. */ @Override public void onStart(Intent intent, int startId) { handleCommand(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleCommand(intent); // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } private void handleCommand(Intent intent) { if (DEBUG) { Log.d(TAG, "handleCommand(Intent " + intent + ")"); } ; if (intent != null && intent.hasExtra(COMMAND)) { switch (intent.getIntExtra(COMMAND, -1)) { case EXTRA_COMMAND_START: startLogging(); break; case EXTRA_COMMAND_PAUSE: pauseLogging(); break; case EXTRA_COMMAND_RESUME: resumeLogging(); break; case EXTRA_COMMAND_STOP: stopLogging(); break; default: break; } } } /** * (non-Javadoc) * * @see android.app.Service#onDestroy() */ @Override public void onDestroy() { if (DEBUG) { Log.d(TAG, "onDestroy()"); } ; super.onDestroy(); if (isLogging()) { Log.w(TAG, "Destroyin an activly logging service"); } mHeartbeatTimer.cancel(); mHeartbeatTimer.purge(); if (this.mWakeLock != null) { this.mWakeLock.release(); this.mWakeLock = null; } PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this.mSharedPreferenceChangeListener); mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); mNoticationManager.cancel(R.layout.map_widgets); Message msg = Message.obtain(); msg.what = STOPLOOPER; mHandler.sendMessage(msg); } private void crashProtectState() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); Editor editor = preferences.edit(); editor.putLong(SERVICESTATE_TRACKID, mTrackId); editor.putLong(SERVICESTATE_SEGMENTID, mSegmentId); editor.putInt(SERVICESTATE_PRECISION, mPrecision); editor.putInt(SERVICESTATE_STATE, mLoggingState); editor.putFloat(SERVICESTATE_DISTANCE, mDistance); editor.commit(); if (DEBUG) { Log.d(TAG, "crashProtectState()"); } ; } private synchronized void crashRestoreState() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); long previousState = preferences.getInt(SERVICESTATE_STATE, Constants.STOPPED); if (previousState == Constants.LOGGING || previousState == Constants.PAUSED) { Log.w(TAG, "Recovering from a crash or kill and restoring state."); startNotification(); mTrackId = preferences.getLong(SERVICESTATE_TRACKID, -1); mSegmentId = preferences.getLong(SERVICESTATE_SEGMENTID, -1); mPrecision = preferences.getInt(SERVICESTATE_PRECISION, -1); mDistance = preferences.getFloat(SERVICESTATE_DISTANCE, 0F); if (previousState == Constants.LOGGING) { mLoggingState = Constants.PAUSED; resumeLogging(); } else if (previousState == Constants.PAUSED) { mLoggingState = Constants.LOGGING; pauseLogging(); } } } /** * (non-Javadoc) * * @see android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent intent) { return this.mBinder; } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#getLoggingState() */ protected boolean isLogging() { return this.mLoggingState == Constants.LOGGING; } /** * Provides the cached last stored waypoint it current logging is active alse * null. * * @return last waypoint location or null */ protected Location getLastWaypoint() { Location myLastWaypoint = null; if (isLogging()) { myLastWaypoint = mPreviousLocation; } return myLastWaypoint; } public float getTrackedDistance() { float distance = 0F; if (isLogging()) { distance = mDistance; } return distance; } protected boolean isMediaPrepared() { return !(mTrackId < 0 || mSegmentId < 0 || mWaypointId < 0); } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#startLogging() */ public synchronized void startLogging() { if (DEBUG) { Log.d(TAG, "startLogging()"); } ; if (this.mLoggingState == Constants.STOPPED) { startNewTrack(); sendRequestLocationUpdatesMessage(); sendRequestStatusUpdateMessage(); this.mLoggingState = Constants.LOGGING; updateWakeLock(); startNotification(); crashProtectState(); broadCastLoggingState(); } } public synchronized void pauseLogging() { if (DEBUG) { Log.d(TAG, "pauseLogging()"); } ; if (this.mLoggingState == Constants.LOGGING) { mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); mLoggingState = Constants.PAUSED; mPreviousLocation = null; updateWakeLock(); updateNotification(); mSatellites = 0; updateNotification(); crashProtectState(); broadCastLoggingState(); } } public synchronized void resumeLogging() { if (DEBUG) { Log.d(TAG, "resumeLogging()"); } ; if (this.mLoggingState == Constants.PAUSED) { if (mPrecision != Constants.LOGGING_GLOBAL) { mStartNextSegment = true; } sendRequestLocationUpdatesMessage(); sendRequestStatusUpdateMessage(); this.mLoggingState = Constants.LOGGING; updateWakeLock(); updateNotification(); crashProtectState(); broadCastLoggingState(); } } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#stopLogging() */ public synchronized void stopLogging() { if (DEBUG) { Log.d(TAG, "stopLogging()"); } ; mLoggingState = Constants.STOPPED; crashProtectState(); updateWakeLock(); PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this.mSharedPreferenceChangeListener); mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); stopNotification(); broadCastLoggingState(); } private void startListening(String provider, long intervaltime, float distance) { mLocationManager.removeUpdates(this); mLocationManager.requestLocationUpdates(provider, intervaltime, distance, this); mCheckPeriod = Math.max(12 * intervaltime, 120 * 1000); if (mHeartbeat != null) { mHeartbeat.cancel(); mHeartbeat = null; } mHeartbeat = new Heartbeat(provider); mHeartbeatTimer.schedule(mHeartbeat, mCheckPeriod, mCheckPeriod); } private void stopListening() { if (mHeartbeat != null) { mHeartbeat.cancel(); mHeartbeat = null; } mLocationManager.removeUpdates(this); } /** * (non-Javadoc) * * @see nl.sogeti.android.gpstracker.IGPSLoggerService#storeDerivedDataSource(java.lang.String) */ public void storeDerivedDataSource(String sourceName) { Uri trackMetaDataUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/metadata"); if (mTrackId >= 0) { if (mSources == null) { Cursor metaData = null; String source = null; try { metaData = this.getContentResolver().query(trackMetaDataUri, new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ", new String[] { Constants.DATASOURCES_KEY }, null); if (metaData.moveToFirst()) { source = metaData.getString(0); } } finally { if (metaData != null) { metaData.close(); } } if (source != null) { mSources = source; } else { mSources = sourceName; ContentValues args = new ContentValues(); args.put(MetaData.KEY, Constants.DATASOURCES_KEY); args.put(MetaData.VALUE, mSources); this.getContentResolver().insert(trackMetaDataUri, args); } } if (!mSources.contains(sourceName)) { mSources += "," + sourceName; ContentValues args = new ContentValues(); args.put(MetaData.VALUE, mSources); this.getContentResolver().update(trackMetaDataUri, args, MetaData.KEY + " = ? ", new String[] { Constants.DATASOURCES_KEY }); } } } private void startNotification() { mNoticationManager.cancel(R.layout.map_widgets); int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = getResources().getString(R.string.service_start); long when = System.currentTimeMillis(); mNotification = new Notification(icon, tickerText, when); mNotification.flags |= Notification.FLAG_ONGOING_EVENT; updateNotification(); if (Build.VERSION.SDK_INT >= 5) { startForegroundReflected(R.layout.map_widgets, mNotification); } else { mNoticationManager.notify(R.layout.map_widgets, mNotification); } } private void updateNotification() { CharSequence contentTitle = getResources().getString(R.string.app_name); String precision = getResources().getStringArray(R.array.precision_choices)[mPrecision]; String state = getResources().getStringArray(R.array.state_choices)[mLoggingState - 1]; CharSequence contentText; switch (mPrecision) { case (Constants.LOGGING_GLOBAL): contentText = getResources().getString(R.string.service_networkstatus, state, precision); break; default: if (mStatusMonitor) { contentText = getResources().getString(R.string.service_gpsstatus, state, precision, mSatellites); } else { contentText = getResources().getString(R.string.service_gpsnostatus, state, precision); } break; } Intent notificationIntent = new Intent(this, CommonLoggerMap.class); notificationIntent.setData(ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId)); mNotification.contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK); mNotification.setLatestEventInfo(this, contentTitle, contentText, mNotification.contentIntent); mNoticationManager.notify(R.layout.map_widgets, mNotification); } private void stopNotification() { if (Build.VERSION.SDK_INT >= 5) { stopForegroundReflected(true); } else { mNoticationManager.cancel(R.layout.map_widgets); } } private void notifyOnEnabledProviderNotification(int resId) { mNoticationManager.cancel(LOGGING_UNAVAILABLE); mShowingGpsDisabled = false; CharSequence text = this.getString(resId); Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG); toast.show(); } private void notifyOnPoorSignal(int resId) { int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = getResources().getString(resId); long when = System.currentTimeMillis(); Notification signalNotification = new Notification(icon, tickerText, when); CharSequence contentTitle = getResources().getString(R.string.app_name); Intent notificationIntent = new Intent(this, CommonLoggerMap.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK); signalNotification.setLatestEventInfo(this, contentTitle, tickerText, contentIntent); signalNotification.flags |= Notification.FLAG_AUTO_CANCEL; mNoticationManager.notify(resId, signalNotification); } private void notifyOnDisabledProvider(int resId) { int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = getResources().getString(resId); long when = System.currentTimeMillis(); Notification gpsNotification = new Notification(icon, tickerText, when); gpsNotification.flags |= Notification.FLAG_AUTO_CANCEL; CharSequence contentTitle = getResources().getString(R.string.app_name); CharSequence contentText = getResources().getString(resId); Intent notificationIntent = new Intent(this, CommonLoggerMap.class); notificationIntent.setData(ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId)); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK); gpsNotification.setLatestEventInfo(this, contentTitle, contentText, contentIntent); mNoticationManager.notify(LOGGING_UNAVAILABLE, gpsNotification); mShowingGpsDisabled = true; } /** * Send a system broadcast to notify a change in the logging or precision */ private void broadCastLoggingState() { Intent broadcast = new Intent(Constants.LOGGING_STATE_CHANGED_ACTION); broadcast.putExtra(Constants.EXTRA_LOGGING_PRECISION, mPrecision); broadcast.putExtra(Constants.EXTRA_LOGGING_STATE, mLoggingState); this.getApplicationContext().sendBroadcast(broadcast); if( isLogging() ) { StreamUtils.initStreams(this); } else { StreamUtils.shutdownStreams(this); } } private void sendRequestStatusUpdateMessage() { mStatusMonitor = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Constants.STATUS_MONITOR, false); Message msg = Message.obtain(); msg.what = ADDGPSSTATUSLISTENER; mHandler.sendMessage(msg); } private void sendRequestLocationUpdatesMessage() { stopListening(); mPrecision = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.PRECISION, "2")).intValue(); Message msg = Message.obtain(); switch (mPrecision) { case (Constants.LOGGING_FINE): // Fine msg.what = REQUEST_FINEGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_NORMAL): // Normal msg.what = REQUEST_NORMALGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_COARSE): // Coarse msg.what = REQUEST_COARSEGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_GLOBAL): // Global msg.what = REQUEST_GLOBALNETWORK_LOCATIONUPDATES; mHandler.sendMessage(msg); break; case (Constants.LOGGING_CUSTOM): // Global msg.what = REQUEST_CUSTOMGPS_LOCATIONUPDATES; mHandler.sendMessage(msg); break; default: Log.e(TAG, "Unknown precision " + mPrecision); break; } } /** * Message handler method to do the work off-loaded by mHandler to * GPSLoggerServiceThread * * @param msg */ private void _handleMessage(Message msg) { if (DEBUG) { Log.d(TAG, "_handleMessage( Message " + msg + " )"); } ; long intervaltime = 0; float distance = 0; switch (msg.what) { case ADDGPSSTATUSLISTENER: this.mLocationManager.addGpsStatusListener(mStatusListener); break; case REQUEST_FINEGPS_LOCATIONUPDATES: mMaxAcceptableAccuracy = FINE_ACCURACY; intervaltime = FINE_INTERVAL; distance = FINE_DISTANCE; startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case REQUEST_NORMALGPS_LOCATIONUPDATES: mMaxAcceptableAccuracy = NORMAL_ACCURACY; intervaltime = NORMAL_INTERVAL; distance = NORMAL_DISTANCE; startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case REQUEST_COARSEGPS_LOCATIONUPDATES: mMaxAcceptableAccuracy = COARSE_ACCURACY; intervaltime = COARSE_INTERVAL; distance = COARSE_DISTANCE; startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case REQUEST_GLOBALNETWORK_LOCATIONUPDATES: mMaxAcceptableAccuracy = GLOBAL_ACCURACY; intervaltime = GLOBAL_INTERVAL; distance = GLOBAL_DISTANCE; startListening(LocationManager.NETWORK_PROVIDER, intervaltime, distance); if (!isNetworkConnected()) { notifyOnDisabledProvider(R.string.service_connectiondisabled); } break; case REQUEST_CUSTOMGPS_LOCATIONUPDATES: intervaltime = 60 * 1000 * Long.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.LOGGING_INTERVAL, "15000")); distance = Float.valueOf(PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.LOGGING_DISTANCE, "10")); mMaxAcceptableAccuracy = Math.max(10f, Math.min(distance, 50f)); startListening(LocationManager.GPS_PROVIDER, intervaltime, distance); break; case STOPLOOPER: mLocationManager.removeGpsStatusListener(mStatusListener); stopListening(); Looper.myLooper().quit(); break; case GPSPROBLEM: notifyOnPoorSignal(R.string.service_gpsproblem); break; } } private void updateWakeLock() { if (this.mLoggingState == Constants.LOGGING) { PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener); PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); if (this.mWakeLock != null) { this.mWakeLock.release(); this.mWakeLock = null; } this.mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); this.mWakeLock.acquire(); } else { if (this.mWakeLock != null) { this.mWakeLock.release(); this.mWakeLock = null; } } } /** * Some GPS waypoints received are of to low a quality for tracking use. Here * we filter those out. * * @param proposedLocation * @return either the (cleaned) original or null when unacceptable */ public Location locationFilter(Location proposedLocation) { // Do no include log wrong 0.0 lat 0.0 long, skip to next value in while-loop if (proposedLocation != null && (proposedLocation.getLatitude() == 0.0d || proposedLocation.getLongitude() == 0.0d)) { Log.w(TAG, "A wrong location was received, 0.0 latitude and 0.0 longitude... "); proposedLocation = null; } // Do not log a waypoint which is more inaccurate then is configured to be acceptable if (proposedLocation != null && proposedLocation.getAccuracy() > mMaxAcceptableAccuracy) { Log.w(TAG, String.format("A weak location was received, lots of inaccuracy... (%f is more then max %f)", proposedLocation.getAccuracy(), mMaxAcceptableAccuracy)); proposedLocation = addBadLocation(proposedLocation); } // Do not log a waypoint which might be on any side of the previous waypoint if (proposedLocation != null && mPreviousLocation != null && proposedLocation.getAccuracy() > mPreviousLocation.distanceTo(proposedLocation)) { Log.w(TAG, String.format("A weak location was received, not quite clear from the previous waypoint... (%f more then max %f)", proposedLocation.getAccuracy(), mPreviousLocation.distanceTo(proposedLocation))); proposedLocation = addBadLocation(proposedLocation); } // Speed checks, check if the proposed location could be reached from the previous one in sane speed // Common to jump on network logging and sometimes jumps on Samsung Galaxy S type of devices if (mSpeedSanityCheck && proposedLocation != null && mPreviousLocation != null) { // To avoid near instant teleportation on network location or glitches cause continent hopping float meters = proposedLocation.distanceTo(mPreviousLocation); long seconds = (proposedLocation.getTime() - mPreviousLocation.getTime()) / 1000L; float speed = meters / seconds; if (speed > MAX_REASONABLE_SPEED) { Log.w(TAG, "A strange location was received, a really high speed of " + speed + " m/s, prob wrong..."); proposedLocation = addBadLocation(proposedLocation); // Might be a messed up Samsung Galaxy S GPS, reset the logging if (speed > 2 * MAX_REASONABLE_SPEED && mPrecision != Constants.LOGGING_GLOBAL) { Log.w(TAG, "A strange location was received on GPS, reset the GPS listeners"); stopListening(); mLocationManager.removeGpsStatusListener(mStatusListener); mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); sendRequestStatusUpdateMessage(); sendRequestLocationUpdatesMessage(); } } } // Remove speed if not sane if (mSpeedSanityCheck && proposedLocation != null && proposedLocation.getSpeed() > MAX_REASONABLE_SPEED) { Log.w(TAG, "A strange speed, a really high speed, prob wrong..."); proposedLocation.removeSpeed(); } // Remove altitude if not sane if (mSpeedSanityCheck && proposedLocation != null && proposedLocation.hasAltitude()) { if (!addSaneAltitude(proposedLocation.getAltitude())) { Log.w(TAG, "A strange altitude, a really big difference, prob wrong..."); proposedLocation.removeAltitude(); } } // Older bad locations will not be needed if (proposedLocation != null) { mWeakLocations.clear(); } return proposedLocation; } /** * Store a bad location, when to many bad locations are stored the the * storage is cleared and the least bad one is returned * * @param location bad location * @return null when the bad location is stored or the least bad one if the * storage was full */ private Location addBadLocation(Location location) { mWeakLocations.add(location); if (mWeakLocations.size() < 3) { location = null; } else { Location best = mWeakLocations.lastElement(); for (Location whimp : mWeakLocations) { if (whimp.hasAccuracy() && best.hasAccuracy() && whimp.getAccuracy() < best.getAccuracy()) { best = whimp; } else { if (whimp.hasAccuracy() && !best.hasAccuracy()) { best = whimp; } } } synchronized (mWeakLocations) { mWeakLocations.clear(); } location = best; } return location; } /** * Builds a bit of knowledge about altitudes to expect and return if the * added value is deemed sane. * * @param altitude * @return whether the altitude is considered sane */ private boolean addSaneAltitude(double altitude) { boolean sane = true; double avg = 0; int elements = 0; // Even insane altitude shifts increases alter perception mAltitudes.add(altitude); if (mAltitudes.size() > 3) { mAltitudes.poll(); } for (Double alt : mAltitudes) { avg += alt; elements++; } avg = avg / elements; sane = Math.abs(altitude - avg) < MAX_REASONABLE_ALTITUDECHANGE; return sane; } /** * Trigged by events that start a new track */ private void startNewTrack() { mDistance = 0; Uri newTrack = this.getContentResolver().insert(Tracks.CONTENT_URI, new ContentValues(0)); mTrackId = Long.valueOf(newTrack.getLastPathSegment()).longValue(); startNewSegment(); } /** * Trigged by events that start a new segment */ private void startNewSegment() { this.mPreviousLocation = null; Uri newSegment = this.getContentResolver().insert(Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments"), new ContentValues(0)); mSegmentId = Long.valueOf(newSegment.getLastPathSegment()).longValue(); crashProtectState(); } protected void storeMediaUri(Uri mediaUri) { if (isMediaPrepared()) { Uri mediaInsertUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mSegmentId + "/waypoints/" + mWaypointId + "/media"); ContentValues args = new ContentValues(); args.put(Media.URI, mediaUri.toString()); this.getContentResolver().insert(mediaInsertUri, args); } else { Log.e(TAG, "No logging done under which to store the track"); } } /** * Use the ContentResolver mechanism to store a received location * * @param location */ public void storeLocation(Location location) { if (!isLogging()) { Log.e(TAG, String.format("Not logging but storing location %s, prepare to fail", location.toString())); } ContentValues args = new ContentValues(); args.put(Waypoints.LATITUDE, Double.valueOf(location.getLatitude())); args.put(Waypoints.LONGITUDE, Double.valueOf(location.getLongitude())); args.put(Waypoints.SPEED, Float.valueOf(location.getSpeed())); args.put(Waypoints.TIME, Long.valueOf(System.currentTimeMillis())); if (location.hasAccuracy()) { args.put(Waypoints.ACCURACY, Float.valueOf(location.getAccuracy())); } if (location.hasAltitude()) { args.put(Waypoints.ALTITUDE, Double.valueOf(location.getAltitude())); } if (location.hasBearing()) { args.put(Waypoints.BEARING, Float.valueOf(location.getBearing())); } Uri waypointInsertUri = Uri.withAppendedPath(Tracks.CONTENT_URI, mTrackId + "/segments/" + mSegmentId + "/waypoints"); Uri inserted = this.getContentResolver().insert(waypointInsertUri, args); mWaypointId = Long.parseLong(inserted.getLastPathSegment()); } /** * Consult broadcast options and execute broadcast if necessary * * @param location */ public void broadcastLocation(Location location) { Intent intent = new Intent(Constants.STREAMBROADCAST); if (mStreamBroadcast) { final long minDistance = (long) PreferenceManager.getDefaultSharedPreferences(this).getFloat("streambroadcast_distance_meter", 5000F); final long minTime = 60000 * Long.parseLong(PreferenceManager.getDefaultSharedPreferences(this).getString("streambroadcast_time", "1")); final long nowTime = location.getTime(); if (mPreviousLocation != null) { mBroadcastDistance += location.distanceTo(mPreviousLocation); } if (mLastTimeBroadcast == 0) { mLastTimeBroadcast = nowTime; } long passedTime = (nowTime - mLastTimeBroadcast); intent.putExtra(Constants.EXTRA_DISTANCE, (int) mBroadcastDistance); intent.putExtra(Constants.EXTRA_TIME, (int) passedTime/60000); intent.putExtra(Constants.EXTRA_LOCATION, location); intent.putExtra(Constants.EXTRA_TRACK, ContentUris.withAppendedId(Tracks.CONTENT_URI, mTrackId)); boolean distanceBroadcast = minDistance > 0 && mBroadcastDistance >= minDistance; boolean timeBroadcast = minTime > 0 && passedTime >= minTime; if (distanceBroadcast || timeBroadcast) { if (distanceBroadcast) { mBroadcastDistance = 0; } if (timeBroadcast) { mLastTimeBroadcast = nowTime; } this.sendBroadcast(intent, "android.permission.ACCESS_FINE_LOCATION"); } } } private boolean isNetworkConnected() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = connMgr.getActiveNetworkInfo(); return (info != null && info.isConnected()); } private void soundGpsSignalAlarm() { Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); if (alert == null) { alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); if (alert == null) { alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); } } MediaPlayer mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(GPSLoggerService.this, alert); final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) { mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mMediaPlayer.setLooping(false); mMediaPlayer.prepare(); mMediaPlayer.start(); } } catch (IllegalArgumentException e) { Log.e(TAG, "Problem setting data source for mediaplayer", e); } catch (SecurityException e) { Log.e(TAG, "Problem setting data source for mediaplayer", e); } catch (IllegalStateException e) { Log.e(TAG, "Problem with mediaplayer", e); } catch (IOException e) { Log.e(TAG, "Problem with mediaplayer", e); } Message msg = Message.obtain(); msg.what = GPSPROBLEM; mHandler.sendMessage(msg); } @SuppressWarnings("rawtypes") private void startForegroundReflected(int id, Notification notification) { Method mStartForeground; Class[] mStartForegroundSignature = new Class[] { int.class, Notification.class }; Object[] mStartForegroundArgs = new Object[2]; mStartForegroundArgs[0] = Integer.valueOf(id); mStartForegroundArgs[1] = notification; try { mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature); mStartForeground.invoke(this, mStartForegroundArgs); } catch (NoSuchMethodException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } catch (IllegalArgumentException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } catch (IllegalAccessException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } catch (InvocationTargetException e) { Log.e(TAG, "Failed starting foreground notification using reflection", e); } } @SuppressWarnings("rawtypes") private void stopForegroundReflected(boolean b) { Class[] mStopForegroundSignature = new Class[] { boolean.class }; Method mStopForeground; Object[] mStopForegroundArgs = new Object[1]; mStopForegroundArgs[0] = Boolean.TRUE; try { mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature); mStopForeground.invoke(this, mStopForegroundArgs); } catch (NoSuchMethodException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } catch (IllegalArgumentException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } catch (IllegalAccessException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } catch (InvocationTargetException e) { Log.e(TAG, "Failed stopping foreground notification using reflection", e); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/logger/GPSLoggerService.java
Java
gpl3
53,293
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.streaming; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.speech.tts.TextToSpeech; import android.util.Log; public class VoiceOver extends BroadcastReceiver implements TextToSpeech.OnInitListener { private static VoiceOver sVoiceOver = null; private static final String TAG = "OGT.VoiceOver"; public static synchronized void initStreaming(Context ctx) { if( sVoiceOver != null ) { shutdownStreaming(ctx); } sVoiceOver = new VoiceOver(ctx); IntentFilter filter = new IntentFilter(Constants.STREAMBROADCAST); ctx.registerReceiver(sVoiceOver, filter); } public static synchronized void shutdownStreaming(Context ctx) { if( sVoiceOver != null ) { ctx.unregisterReceiver(sVoiceOver); sVoiceOver.onShutdown(); sVoiceOver = null; } } private TextToSpeech mTextToSpeech; private int mVoiceStatus = -1; private Context mContext; public VoiceOver(Context ctx) { mContext = ctx.getApplicationContext(); mTextToSpeech = new TextToSpeech(mContext, this); } @Override public void onInit(int status) { mVoiceStatus = status; } private void onShutdown() { mVoiceStatus = -1; mTextToSpeech.shutdown(); } @Override public void onReceive(Context context, Intent intent) { if( mVoiceStatus == TextToSpeech.SUCCESS ) { int meters = intent.getIntExtra(Constants.EXTRA_DISTANCE, 0); int minutes = intent.getIntExtra(Constants.EXTRA_TIME, 0); String myText = context.getString(R.string.voiceover_speaking, minutes, meters); mTextToSpeech.speak(myText, TextToSpeech.QUEUE_ADD, null); } else { Log.w(TAG, "Voice stream failed TTS not ready"); } } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/streaming/VoiceOver.java
Java
gpl3
3,582
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.streaming; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; import java.util.Queue; import nl.sogeti.android.gpstracker.R; import nl.sogeti.android.gpstracker.util.Constants; import nl.sogeti.android.gpstracker.viewer.ApplicationPreferenceActivity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.client.ClientProtocolException; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.impl.client.DefaultHttpClient; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.location.Location; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; public class CustomUpload extends BroadcastReceiver { private static final String CUSTOMUPLOAD_BACKLOG_DEFAULT = "20"; private static CustomUpload sCustomUpload = null; private static final String TAG = "OGT.CustomUpload"; private static final int NOTIFICATION_ID = R.string.customupload_failed; private static Queue<HttpGet> sRequestBacklog = new LinkedList<HttpGet>(); public static synchronized void initStreaming(Context ctx) { if( sCustomUpload != null ) { shutdownStreaming(ctx); } sCustomUpload = new CustomUpload(); sRequestBacklog = new LinkedList<HttpGet>(); IntentFilter filter = new IntentFilter(Constants.STREAMBROADCAST); ctx.registerReceiver(sCustomUpload, filter); } public static synchronized void shutdownStreaming(Context ctx) { if( sCustomUpload != null ) { ctx.unregisterReceiver(sCustomUpload); sCustomUpload.onShutdown(); sCustomUpload = null; } } private void onShutdown() { } @Override public void onReceive(Context context, Intent intent) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String prefUrl = preferences.getString(ApplicationPreferenceActivity.CUSTOMUPLOAD_URL, "http://www.example.com"); Integer prefBacklog = Integer.valueOf( preferences.getString(ApplicationPreferenceActivity.CUSTOMUPLOAD_BACKLOG, CUSTOMUPLOAD_BACKLOG_DEFAULT) ); Location loc = intent.getParcelableExtra(Constants.EXTRA_LOCATION); Uri trackUri = intent.getParcelableExtra(Constants.EXTRA_TRACK); String buildUrl = prefUrl; buildUrl = buildUrl.replace("@LAT@", Double.toString(loc.getLatitude())); buildUrl = buildUrl.replace("@LON@", Double.toString(loc.getLongitude())); buildUrl = buildUrl.replace("@ID@", trackUri.getLastPathSegment()); buildUrl = buildUrl.replace("@TIME@", Long.toString(loc.getTime())); buildUrl = buildUrl.replace("@SPEED@", Float.toString(loc.getSpeed())); buildUrl = buildUrl.replace("@ACC@", Float.toString(loc.getAccuracy())); buildUrl = buildUrl.replace("@ALT@", Double.toString(loc.getAltitude())); buildUrl = buildUrl.replace("@BEAR@", Float.toString(loc.getBearing())); HttpClient client = new DefaultHttpClient(); URI uploadUri; try { uploadUri = new URI(buildUrl); HttpGet currentRequest = new HttpGet(uploadUri ); sRequestBacklog.add(currentRequest); if( sRequestBacklog.size() > prefBacklog ) { sRequestBacklog.poll(); } while( !sRequestBacklog.isEmpty() ) { HttpGet request = sRequestBacklog.peek(); HttpResponse response = client.execute(request); sRequestBacklog.poll(); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { throw new IOException("Invalid response from server: " + status.toString()); } clearNotification(context); } } catch (URISyntaxException e) { notifyError(context, e); } catch (ClientProtocolException e) { notifyError(context, e); } catch (IOException e) { notifyError(context, e); } } private void notifyError(Context context, Exception e) { Log.e( TAG, "Custom upload failed", e); String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns); int icon = R.drawable.ic_maps_indicator_current_position; CharSequence tickerText = context.getText(R.string.customupload_failed); long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); Context appContext = context.getApplicationContext(); CharSequence contentTitle = tickerText; CharSequence contentText = e.getMessage(); Intent notificationIntent = new Intent(context, CustomUpload.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(appContext, contentTitle, contentText, contentIntent); notification.flags = Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(NOTIFICATION_ID, notification); } private void clearNotification(Context context) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns); mNotificationManager.cancel(NOTIFICATION_ID); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/streaming/CustomUpload.java
Java
gpl3
7,377
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) Apr 24, 2011 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.streaming; import nl.sogeti.android.gpstracker.util.Constants; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class StreamUtils { @SuppressWarnings("unused") private static final String TAG = "OGT.StreamUtils"; /** * Initialize all appropriate stream listeners * @param ctx */ public static void initStreams(final Context ctx) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ctx); boolean streams_enabled = sharedPreferences.getBoolean(Constants.BROADCAST_STREAM, false); if (streams_enabled && sharedPreferences.getBoolean("VOICEOVER_ENABLED", false)) { VoiceOver.initStreaming(ctx); } if (streams_enabled && sharedPreferences.getBoolean("CUSTOMUPLOAD_ENABLED", false)) { CustomUpload.initStreaming(ctx); } } /** * Shutdown all stream listeners * * @param ctx */ public static void shutdownStreams(Context ctx) { VoiceOver.shutdownStreaming(ctx); CustomUpload.shutdownStreaming(ctx); } }
zzy157-running
OpenGPSTracker/application/src/nl/sogeti/android/gpstracker/streaming/StreamUtils.java
Java
gpl3
2,708
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.contrib.auth; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.SortedMap; import java.util.TreeMap; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.auth.AuthScheme; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.Credentials; import org.apache.http.auth.MalformedChallengeException; import org.apache.http.impl.cookie.DateUtils; import org.apache.http.message.BasicHeader; /** * Implementation of Amazon S3 authentication. This scheme must be used * preemptively only. * <p> * Reference Document: {@link http * ://docs.amazonwebservices.com/AmazonS3/latest/index * .html?RESTAuthentication.html} */ public class AWSScheme implements AuthScheme { private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; public static final String NAME = "AWS"; public AWSScheme() { } public Header authenticate( final Credentials credentials, final HttpRequest request) throws AuthenticationException { // If the Date header has not been provided add it as it is required if (request.getFirstHeader("Date") == null) { Header dateHeader = new BasicHeader("Date", DateUtils.formatDate(new Date())); request.addHeader(dateHeader); } String canonicalizedAmzHeaders = getCanonicalizedAmzHeaders(request.getAllHeaders()); String canonicalizedResource = getCanonicalizedResource(request.getRequestLine().getUri(), (request.getFirstHeader("Host") != null ? request.getFirstHeader("Host").getValue() : null)); String contentMD5 = request.getFirstHeader("Content-MD5") != null ? request.getFirstHeader( "Content-MD5").getValue() : ""; String contentType = request.getFirstHeader("Content-Type") != null ? request .getFirstHeader("Content-Type").getValue() : ""; String date = request.getFirstHeader("Date").getValue(); String method = request.getRequestLine().getMethod(); StringBuilder toSign = new StringBuilder(); toSign.append(method).append("\n"); toSign.append(contentMD5).append("\n"); toSign.append(contentType).append("\n"); toSign.append(date).append("\n"); toSign.append(canonicalizedAmzHeaders); toSign.append(canonicalizedResource); String signature = calculateRFC2104HMAC(toSign.toString(), credentials.getPassword()); String headerValue = NAME + " " + credentials.getUserPrincipal().getName() + ":" + signature.trim(); return new BasicHeader("Authorization", headerValue); } /** * Computes RFC 2104-compliant HMAC signature. * * @param data * The data to be signed. * @param key * The signing key. * @return The Base64-encoded RFC 2104-compliant HMAC signature. * @throws RuntimeException * when signature generation fails */ private static String calculateRFC2104HMAC( final String data, final String key) throws AuthenticationException { try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // base64-encode the hmac return Base64.encodeBase64String(rawHmac); } catch (InvalidKeyException ex) { throw new AuthenticationException("Failed to generate HMAC: " + ex.getMessage(), ex); } catch (NoSuchAlgorithmException ex) { throw new AuthenticationException(HMAC_SHA1_ALGORITHM + " algorithm is not supported", ex); } } /** * Returns the canonicalized AMZ headers. * * @param headers * The list of request headers. * @return The canonicalized AMZ headers. */ private static String getCanonicalizedAmzHeaders(final Header[] headers) { StringBuilder sb = new StringBuilder(); Pattern spacePattern = Pattern.compile("\\s+"); // Create a lexographically sorted list of headers that begin with x-amz SortedMap<String, String> amzHeaders = new TreeMap<String, String>(); for (Header header : headers) { String name = header.getName().toLowerCase(); if (name.startsWith("x-amz-")) { String value = ""; if (amzHeaders.containsKey(name)) value = amzHeaders.get(name) + "," + header.getValue(); else value = header.getValue(); // All newlines and multiple spaces must be replaced with a // single space character. Matcher m = spacePattern.matcher(value); value = m.replaceAll(" "); amzHeaders.put(name, value); } } // Concatenate all AMZ headers for (Entry<String, String> entry : amzHeaders.entrySet()) { sb.append(entry.getKey()).append(':').append(entry.getValue()).append("\n"); } return sb.toString(); } /** * Returns the canonicalized resource. * * @param uri * The resource uri * @param hostName * the host name * @return The canonicalized resource. */ private static String getCanonicalizedResource(String uri, String hostName) { StringBuilder sb = new StringBuilder(); // Append the bucket if there is one if (hostName != null) { // If the host name contains a port number remove it if (hostName.contains(":")) hostName = hostName.substring(0, hostName.indexOf(":")); // Now extract the bucket if there is one if (hostName.endsWith(".s3.amazonaws.com")) { String bucketName = hostName.substring(0, hostName.length() - 17); sb.append("/" + bucketName); } } int queryIdx = uri.indexOf("?"); // Append the resource path if (queryIdx >= 0) sb.append(uri.substring(0, queryIdx)); else sb.append(uri.substring(0, uri.length())); // Append the AWS sub-resource if (queryIdx >= 0) { String query = uri.substring(queryIdx - 1, uri.length()); if (query.contains("?acl")) sb.append("?acl"); else if (query.contains("?location")) sb.append("?location"); else if (query.contains("?logging")) sb.append("?logging"); else if (query.contains("?torrent")) sb.append("?torrent"); } return sb.toString(); } public String getParameter(String name) { return null; } public String getRealm() { return null; } public String getSchemeName() { return NAME; } public boolean isComplete() { return true; } public boolean isConnectionBased() { return false; } public void processChallenge(final Header header) throws MalformedChallengeException { // Nothing to do here } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient-contrib/src/main/java/org/apache/http/contrib/auth/AWSScheme.java
Java
gpl3
9,031
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.contrib.auth; import org.apache.http.auth.AuthScheme; import org.apache.http.auth.AuthSchemeFactory; import org.apache.http.params.HttpParams; /** * {@link AuthSchemeFactory} implementation that creates and initializes * {@link AWSScheme} instances. */ public class AWSSchemeFactory implements AuthSchemeFactory { public AuthScheme newInstance(final HttpParams params) { return new AWSScheme(); } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient-contrib/src/main/java/org/apache/http/contrib/auth/AWSSchemeFactory.java
Java
gpl3
1,631
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.contrib.auth; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.impl.auth.SpnegoTokenGenerator; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.util.ASN1Dump; /** * Takes Kerberos ticket and wraps into a SPNEGO token. Leaving some optional fields out. */ public class BouncySpnegoTokenGenerator implements SpnegoTokenGenerator { private final Log log = LogFactory.getLog(getClass()); private final DERObjectIdentifier spnegoOid; private final DERObjectIdentifier kerbOid; public BouncySpnegoTokenGenerator() { super(); this.spnegoOid = new DERObjectIdentifier("1.3.6.1.5.5.2"); this.kerbOid = new DERObjectIdentifier("1.2.840.113554.1.2.2"); } public byte [] generateSpnegoDERObject(byte [] kerbTicket) throws IOException { DEROctetString ourKerberosTicket = new DEROctetString(kerbTicket); DERSequence kerbOidSeq = new DERSequence(kerbOid); DERTaggedObject tagged0 = new DERTaggedObject(0, kerbOidSeq); DERTaggedObject tagged2 = new DERTaggedObject(2, ourKerberosTicket); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tagged0); v.add(tagged2); DERSequence seq = new DERSequence(v); DERTaggedObject taggedSpnego = new DERTaggedObject(0, seq); ByteArrayOutputStream out = new ByteArrayOutputStream(); ASN1OutputStream asn1Out = new ASN1OutputStream(out); ASN1Object spnegoOIDASN1 = (ASN1Object) spnegoOid.toASN1Object(); ASN1Object taggedSpnegoASN1 = (ASN1Object) taggedSpnego.toASN1Object(); int length = spnegoOIDASN1.getDEREncoded().length + taggedSpnegoASN1.getDEREncoded().length; byte [] lenBytes = writeLength(length); byte[] appWrap = new byte[lenBytes.length + 1]; appWrap[0] = 0x60; for(int i=1; i < appWrap.length; i++){ appWrap[i] = lenBytes[i-1]; } asn1Out.write(appWrap); asn1Out.writeObject(spnegoOid.toASN1Object()); asn1Out.writeObject(taggedSpnego.toASN1Object()); byte[] app = out.toByteArray(); ASN1InputStream in = new ASN1InputStream(app); if (log.isDebugEnabled() ){ int skip = 12; byte [] manipBytes = new byte[app.length - skip]; for(int i=skip; i < app.length; i++){ manipBytes[i-skip] = app[i]; } ASN1InputStream ourSpnego = new ASN1InputStream( manipBytes ); log.debug(ASN1Dump.dumpAsString(ourSpnego.readObject())); } return in.readObject().getDEREncoded(); } private byte [] writeLength(int length) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); if (length > 127) { int size = 1; int val = length; while ((val >>>= 8) != 0) { size++; } out.write((byte) (size | 0x80)); for (int i = (size - 1) * 8; i >= 0; i -= 8) { out.write((byte) (length >> i)); } } else { out.write((byte) length); } return out.toByteArray(); } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient-contrib/src/main/java/org/apache/http/contrib/auth/BouncySpnegoTokenGenerator.java
Java
gpl3
4,843
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.mockup; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import org.apache.ogt.http.conn.ConnectTimeoutException; import org.apache.ogt.http.conn.scheme.SchemeSocketFactory; import org.apache.ogt.http.params.HttpParams; /** * {@link SchemeSocketFactory} mockup implementation. */ public class SocketFactoryMockup implements SchemeSocketFactory { /* A default instance of this mockup. */ public final static SchemeSocketFactory INSTANCE = new SocketFactoryMockup("INSTANCE"); /** The name of this mockup socket factory. */ protected final String mockup_name; public SocketFactoryMockup(String name) { mockup_name = (name != null) ? name : String.valueOf(hashCode()); } // don't implement equals and hashcode, all instances are different! @Override public String toString() { return "SocketFactoryMockup." + mockup_name; } public Socket createSocket(final HttpParams params) { throw new UnsupportedOperationException("I'm a mockup!"); } public Socket connectSocket( Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { throw new UnsupportedOperationException("I'm a mockup!"); } public boolean isSecure(Socket sock) { // no way that the argument is from *this* factory... throw new IllegalArgumentException("I'm a mockup!"); } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/mockup/SocketFactoryMockup.java
Java
gpl3
2,802
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.mockup; import java.io.IOException; import org.apache.ogt.http.HttpConnection; import org.apache.ogt.http.HttpConnectionMetrics; /** * {@link HttpConnection} mockup implementation. * */ public class HttpConnectionMockup implements HttpConnection { private boolean open = true; public HttpConnectionMockup() { super(); } public void close() throws IOException { this.open = false; } public void shutdown() throws IOException { this.open = false; } public int getSocketTimeout() { return 0; } public boolean isOpen() { return this.open; } public boolean isStale() { return false; } public void setSocketTimeout(int timeout) { } public HttpConnectionMetrics getMetrics() { return null; } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/mockup/HttpConnectionMockup.java
Java
gpl3
2,039
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.mockup; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import org.apache.ogt.http.impl.io.AbstractSessionInputBuffer; import org.apache.ogt.http.params.BasicHttpParams; import org.apache.ogt.http.params.HttpParams; /** * {@link org.apache.ogt.http.io.SessionInputBuffer} mockup implementation. */ public class SessionInputBufferMockup extends AbstractSessionInputBuffer { public static final int BUFFER_SIZE = 16; public SessionInputBufferMockup( final InputStream instream, int buffersize, final HttpParams params) { super(); init(instream, buffersize, params); } public SessionInputBufferMockup( final InputStream instream, int buffersize) { this(instream, buffersize, new BasicHttpParams()); } public SessionInputBufferMockup( final byte[] bytes, final HttpParams params) { this(bytes, BUFFER_SIZE, params); } public SessionInputBufferMockup( final byte[] bytes) { this(bytes, BUFFER_SIZE, new BasicHttpParams()); } public SessionInputBufferMockup( final byte[] bytes, int buffersize, final HttpParams params) { this(new ByteArrayInputStream(bytes), buffersize, params); } public SessionInputBufferMockup( final byte[] bytes, int buffersize) { this(new ByteArrayInputStream(bytes), buffersize, new BasicHttpParams()); } public SessionInputBufferMockup( final String s, final String charset, int buffersize, final HttpParams params) throws UnsupportedEncodingException { this(s.getBytes(charset), buffersize, params); } public SessionInputBufferMockup( final String s, final String charset, int buffersize) throws UnsupportedEncodingException { this(s.getBytes(charset), buffersize, new BasicHttpParams()); } public SessionInputBufferMockup( final String s, final String charset, final HttpParams params) throws UnsupportedEncodingException { this(s.getBytes(charset), params); } public SessionInputBufferMockup( final String s, final String charset) throws UnsupportedEncodingException { this(s.getBytes(charset), new BasicHttpParams()); } public boolean isDataAvailable(int timeout) throws IOException { return true; } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/mockup/SessionInputBufferMockup.java
Java
gpl3
3,868
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.mockup; import java.net.URI; import java.net.Proxy; import java.net.ProxySelector; import java.net.SocketAddress; import java.util.List; import java.util.ArrayList; import java.io.IOException; /** * Mockup of a {@link ProxySelector}. * Always returns a fixed list. */ public class ProxySelectorMockup extends ProxySelector { protected List<Proxy> proxyList; /** * Creates a mock proxy selector. * * @param proxies the list of proxies, or * <code>null</code> for direct connections */ public ProxySelectorMockup(List<Proxy> proxies) { if (proxies == null) { proxies = new ArrayList<Proxy>(1); proxies.add(Proxy.NO_PROXY); } else if (proxies.isEmpty()) { throw new IllegalArgumentException ("Proxy list must not be empty."); } proxyList = proxies; } /** * Obtains the constructor argument. * * @param ignored not used by this mockup * * @return the list passed to the constructor, * or a default list with "DIRECT" as the only element */ @Override public List<Proxy> select(URI ignored) { return proxyList; } /** * Does nothing. */ @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { // no body } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/mockup/ProxySelectorMockup.java
Java
gpl3
2,608
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.mockup; import java.net.Socket; import org.apache.ogt.http.conn.scheme.LayeredSchemeSocketFactory; /** * {@link LayeredSchemeSocketFactory} mockup implementation. */ public class SecureSocketFactoryMockup extends SocketFactoryMockup implements LayeredSchemeSocketFactory { /* A default instance of this mockup. */ public final static LayeredSchemeSocketFactory INSTANCE = new SecureSocketFactoryMockup("INSTANCE"); public SecureSocketFactoryMockup(String name) { super(name); } // don't implement equals and hashcode, all instances are different! @Override public String toString() { return "SecureSocketFactoryMockup." + mockup_name; } public Socket createLayeredSocket(Socket socket, String host, int port, boolean autoClose) { throw new UnsupportedOperationException("I'm a mockup!"); } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/mockup/SecureSocketFactoryMockup.java
Java
gpl3
2,123
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.impl.conn.tsccm; import java.util.Date; import java.util.concurrent.locks.Lock; import org.apache.ogt.http.impl.conn.tsccm.WaitingThread; /** * Thread to await something. */ public class AwaitThread extends Thread { protected final WaitingThread wait_object; protected final Lock wait_lock; protected final Date wait_deadline; protected volatile boolean waiting; protected volatile Throwable exception; /** * Creates a new thread. * When this thread is started, it will wait on the argument object. */ public AwaitThread(WaitingThread where, Lock lck, Date deadline) { wait_object = where; wait_lock = lck; wait_deadline = deadline; } /** * This method is executed when the thread is started. */ @Override public void run() { try { wait_lock.lock(); waiting = true; wait_object.await(wait_deadline); } catch (Throwable dart) { exception = dart; } finally { waiting = false; wait_lock.unlock(); } // terminate } public Throwable getException() { return exception; } public boolean isWaiting() { try { wait_lock.lock(); return waiting; } finally { wait_lock.unlock(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/impl/conn/tsccm/AwaitThread.java
Java
gpl3
2,630
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.impl.conn; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.ExecutionContext; import org.apache.ogt.http.protocol.HttpContext; import org.apache.ogt.http.protocol.HttpProcessor; import org.apache.ogt.http.protocol.HttpRequestExecutor; import org.apache.ogt.http.util.EntityUtils; /** * Executes a request from a new thread. * */ public class ExecReqThread extends GetConnThread { protected final ClientConnectionManager conn_manager; protected final RequestSpec request_spec; protected volatile HttpResponse response; protected volatile byte[] response_data; /** * Executes a request. * This involves the following steps: * <ol> * <li>obtain a connection (see base class)</li> * <li>open the connection</li> * <li>prepare context and request</li> * <li>execute request to obtain the response</li> * <li>consume the response entity (if there is one)</li> * <li>release the connection</li> * </ol> */ public ExecReqThread(ClientConnectionManager mgr, HttpRoute route, long timeout, RequestSpec reqspec) { super(mgr, route, timeout); this.conn_manager = mgr; request_spec = reqspec; } public HttpResponse getResponse() { return response; } public byte[] getResponseData() { return response_data; } /** * This method is invoked when the thread is started. * It invokes the base class implementation. */ @Override public void run() { super.run(); // obtain connection if (connection == null) return; // problem obtaining connection try { request_spec.context.setAttribute (ExecutionContext.HTTP_CONNECTION, connection); doOpenConnection(); HttpRequest request = (HttpRequest) request_spec.context. getAttribute(ExecutionContext.HTTP_REQUEST); request_spec.executor.preProcess (request, request_spec.processor, request_spec.context); response = request_spec.executor.execute (request, connection, request_spec.context); request_spec.executor.postProcess (response, request_spec.processor, request_spec.context); doConsumeResponse(); } catch (Throwable dart) { dart.printStackTrace(System.out); if (exception != null) exception = dart; } finally { conn_manager.releaseConnection(connection, -1, null); } } /** * Opens the connection after it has been obtained. */ protected void doOpenConnection() throws Exception { connection.open (conn_route, request_spec.context, request_spec.params); } /** * Reads the response entity, if there is one. */ protected void doConsumeResponse() throws Exception { if (response.getEntity() != null) response_data = EntityUtils.toByteArray(response.getEntity()); } /** * Helper class collecting request data. * The request and target are expected in the context. */ public static class RequestSpec { public HttpRequestExecutor executor; public HttpProcessor processor; public HttpContext context; public HttpParams params; } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/impl/conn/ExecReqThread.java
Java
gpl3
4,873
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.impl.conn; import java.util.concurrent.TimeUnit; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.ClientConnectionRequest; import org.apache.ogt.http.conn.ManagedClientConnection; import org.apache.ogt.http.conn.routing.HttpRoute; /** * Thread to get a connection from a connection manager. * Used by connection manager tests. * Code based on HttpClient 3.x class <code>TestHttpConnectionManager</code>. */ public class GetConnThread extends Thread { protected final HttpRoute conn_route; protected final long conn_timeout; protected final ClientConnectionRequest conn_request; protected volatile ManagedClientConnection connection; protected volatile Throwable exception; /** * Creates a new thread for requesting a connection from the given manager. * * When this thread is started, it will try to obtain a connection. * The timeout is in milliseconds. */ public GetConnThread(ClientConnectionManager mgr, HttpRoute route, long timeout) { this(mgr.requestConnection(route, null), route, timeout); } /** * Creates a new for requesting a connection from the given request object. * * When this thread is started, it will try to obtain a connection. * The timeout is in milliseconds. */ public GetConnThread(ClientConnectionRequest connectionRequest, HttpRoute route, long timeout) { conn_route = route; conn_timeout = timeout; conn_request = connectionRequest; } /** * This method is executed when the thread is started. */ @Override public void run() { try { connection = conn_request.getConnection (conn_timeout, TimeUnit.MILLISECONDS); } catch (Throwable dart) { exception = dart; } // terminate } public Throwable getException() { return exception; } public ManagedClientConnection getConnection() { return connection; } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/impl/conn/GetConnThread.java
Java
gpl3
3,337
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.impl.conn; import org.apache.ogt.http.HttpClientConnection; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.params.DefaultedHttpParams; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.ExecutionContext; import org.apache.ogt.http.protocol.HttpContext; import org.apache.ogt.http.protocol.HttpProcessor; import org.apache.ogt.http.protocol.HttpRequestExecutor; /** * Static helper methods. */ public final class Helper { /** Disabled default constructor. */ private Helper() { // no body } /** * Executes a request. */ public static HttpResponse execute(HttpRequest req, HttpClientConnection conn, HttpHost target, HttpRequestExecutor exec, HttpProcessor proc, HttpParams params, HttpContext ctxt) throws Exception { ctxt.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); ctxt.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); ctxt.setAttribute(ExecutionContext.HTTP_REQUEST, req); req.setParams(new DefaultedHttpParams(req.getParams(), params)); exec.preProcess(req, proc, ctxt); HttpResponse rsp = exec.execute(req, conn, ctxt); rsp.setParams(new DefaultedHttpParams(rsp.getParams(), params)); exec.postProcess(rsp, proc, ctxt); return rsp; } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/impl/conn/Helper.java
Java
gpl3
2,868
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.impl.conn; import java.io.IOException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.impl.conn.AbstractClientConnAdapter; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.protocol.HttpContext; /** * Mockup connection adapter. */ public class ClientConnAdapterMockup extends AbstractClientConnAdapter { public ClientConnAdapterMockup(ClientConnectionManager mgr) { super(mgr, null); } public void close() { } public HttpRoute getRoute() { throw new UnsupportedOperationException("just a mockup"); } public void layerProtocol(HttpContext context, HttpParams params) { throw new UnsupportedOperationException("just a mockup"); } public void open(HttpRoute route, HttpContext context, HttpParams params) throws IOException { throw new UnsupportedOperationException("just a mockup"); } public void shutdown() { } public void tunnelTarget(boolean secure, HttpParams params) { throw new UnsupportedOperationException("just a mockup"); } public void tunnelProxy(HttpHost next, boolean secure, HttpParams params) { throw new UnsupportedOperationException("just a mockup"); } public Object getState() { throw new UnsupportedOperationException("just a mockup"); } public void setState(Object state) { throw new UnsupportedOperationException("just a mockup"); } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/impl/conn/ClientConnAdapterMockup.java
Java
gpl3
2,775
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.conn.ssl; /** * Some X509 certificates to test against. * <p/> * Note: some of these certificates have Japanese Kanji in the "subjectAlt" * field (UTF8). Not sure how realistic that is since international characters * in DNS names usually get translated into ASCII using "xn--" style DNS * entries. "xn--i8s592g.co.jp" is what FireFox actually uses when trying to * find &#x82b1;&#x5b50;.co.jp. So would the CN in the certificate contain * "xn--i8s592g.co.jp" in ASCII, or "&#x82b1;&#x5b50;.co.jp" in UTF8? (Both?) * * @since 11-Dec-2006 */ public class CertificatesToPlayWith { /** * CN=foo.com */ public final static byte[] X509_FOO = ( "-----BEGIN CERTIFICATE-----\n" + "MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aQMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzE0MVoXDTI4MTEwNTE1MzE0MVowgaQx\n" + "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" + "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" + "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" + "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" + "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" + "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" + "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" + "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" + "hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" + "FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" + "yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQC3jRmEya6sQCkmieULcvx8zz1euCk9\n" + "fSez7BEtki8+dmfMXe3K7sH0lI8f4jJR0rbSCjpmCQLYmzC3NxBKeJOW0RcjNBpO\n" + "c2JlGO9auXv2GDP4IYiXElLJ6VSqc8WvDikv0JmCCWm0Zga+bZbR/EWN5DeEtFdF\n" + "815CLpJZNcYwiYwGy/CVQ7w2TnXlG+mraZOz+owr+cL6J/ZesbdEWfjoS1+cUEhE\n" + "HwlNrAu8jlZ2UqSgskSWlhYdMTAP9CPHiUv9N7FcT58Itv/I4fKREINQYjDpvQcx\n" + "SaTYb9dr5sB4WLNglk7zxDtM80H518VvihTcP7FHL+Gn6g4j5fkI98+S\n" + "-----END CERTIFICATE-----\n").getBytes(); /** * CN=&#x82b1;&#x5b50;.co.jp */ public final static byte[] X509_HANAKO = ( "-----BEGIN CERTIFICATE-----\n" + "MIIESzCCAzOgAwIBAgIJAIz+EYMBU6aTMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1NDIxNVoXDTI4MTEwNTE1NDIxNVowgakx\n" + "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" + "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" + "cnRpZmljYXRlczEVMBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkB\n" + "FhZqdWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n" + "MIIBCgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjU\n" + "g4pNjYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQc\n" + "wHf0ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t\n" + "7iu1JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAn\n" + "AxK6q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArD\n" + "qUYxqJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwG\n" + "CWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNV\n" + "HQ4EFgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLS\n" + "rNuzA1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBALJ27i3okV/KvlDp6KMID3gd\n" + "ITl68PyItzzx+SquF8gahMh016NX73z/oVZoVUNdftla8wPUB1GwIkAnGkhQ9LHK\n" + "spBdbRiCj0gMmLCsX8SrjFvr7cYb2cK6J/fJe92l1tg/7Y4o7V/s4JBe/cy9U9w8\n" + "a0ctuDmEBCgC784JMDtT67klRfr/2LlqWhlOEq7pUFxRLbhpquaAHSOjmIcWnVpw\n" + "9BsO7qe46hidgn39hKh1WjKK2VcL/3YRsC4wUi0PBtFW6ScMCuMhgIRXSPU55Rae\n" + "UIlOdPjjr1SUNWGId1rD7W16Scpwnknn310FNxFMHVI0GTGFkNdkilNCFJcIoRA=\n" + "-----END CERTIFICATE-----\n").getBytes(); /** * CN=foo.com, subjectAlt=bar.com */ public final static byte[] X509_FOO_BAR = ( "-----BEGIN CERTIFICATE-----\n" + "MIIEXDCCA0SgAwIBAgIJAIz+EYMBU6aRMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzYyOVoXDTI4MTEwNTE1MzYyOVowgaQx\n" + "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" + "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" + "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" + "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" + "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" + "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" + "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" + "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCG\n" + "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" + "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" + "A1LKh6YNPg0wEgYDVR0RBAswCYIHYmFyLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEA\n" + "dQyprNZBmVnvuVWjV42sey/PTfkYShJwy1j0/jcFZR/ypZUovpiHGDO1DgL3Y3IP\n" + "zVQ26uhUsSw6G0gGRiaBDe/0LUclXZoJzXX1qpS55OadxW73brziS0sxRgGrZE/d\n" + "3g5kkio6IED47OP6wYnlmZ7EKP9cqjWwlnvHnnUcZ2SscoLNYs9rN9ccp8tuq2by\n" + "88OyhKwGjJfhOudqfTNZcDzRHx4Fzm7UsVaycVw4uDmhEHJrAsmMPpj/+XRK9/42\n" + "2xq+8bc6HojdtbCyug/fvBZvZqQXSmU8m8IVcMmWMz0ZQO8ee3QkBHMZfCy7P/kr\n" + "VbWx/uETImUu+NZg22ewEw==\n" + "-----END CERTIFICATE-----\n").getBytes(); /** * CN=foo.com, subjectAlt=bar.com, subjectAlt=&#x82b1;&#x5b50;.co.jp * (hanako.co.jp in kanji) */ public final static byte[] X509_FOO_BAR_HANAKO = ( "-----BEGIN CERTIFICATE-----\n" + "MIIEajCCA1KgAwIBAgIJAIz+EYMBU6aSMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzgxM1oXDTI4MTEwNTE1MzgxM1owgaQx\n" + "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" + "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" + "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" + "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" + "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" + "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" + "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" + "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBnjCBmzAJBgNVHRMEAjAAMCwGCWCG\n" + "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" + "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" + "A1LKh6YNPg0wIAYDVR0RBBkwF4IHYmFyLmNvbYIM6Iqx5a2QLmNvLmpwMA0GCSqG\n" + "SIb3DQEBBQUAA4IBAQBeZs7ZIYyKtdnVxVvdLgwySEPOE4pBSXii7XYv0Q9QUvG/\n" + "++gFGQh89HhABzA1mVUjH5dJTQqSLFvRfqTHqLpxSxSWqMHnvRM4cPBkIRp/XlMK\n" + "PlXadYtJLPTgpbgvulA1ickC9EwlNYWnowZ4uxnfsMghW4HskBqaV+PnQ8Zvy3L0\n" + "12c7Cg4mKKS5pb1HdRuiD2opZ+Hc77gRQLvtWNS8jQvd/iTbh6fuvTKfAOFoXw22\n" + "sWIKHYrmhCIRshUNohGXv50m2o+1w9oWmQ6Dkq7lCjfXfUB4wIbggJjpyEtbNqBt\n" + "j4MC2x5rfsLKKqToKmNE7pFEgqwe8//Aar1b+Qj+\n" + "-----END CERTIFICATE-----\n").getBytes(); /** * CN=*.foo.com */ public final static byte[] X509_WILD_FOO = ( "-----BEGIN CERTIFICATE-----\n" + "MIIESDCCAzCgAwIBAgIJAIz+EYMBU6aUMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTU1NVoXDTI4MTEwNTE2MTU1NVowgaYx\n" + "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + "cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" + "dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" + "CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" + "jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" + "ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" + "JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" + "q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" + "qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCG\n" + "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" + "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" + "A1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBAH0ipG6J561UKUfgkeW7GvYwW98B\n" + "N1ZooWX+JEEZK7+Pf/96d3Ij0rw9ACfN4bpfnCq0VUNZVSYB+GthQ2zYuz7tf/UY\n" + "A6nxVgR/IjG69BmsBl92uFO7JTNtHztuiPqBn59pt+vNx4yPvno7zmxsfI7jv0ww\n" + "yfs+0FNm7FwdsC1k47GBSOaGw38kuIVWqXSAbL4EX9GkryGGOKGNh0qvAENCdRSB\n" + "G9Z6tyMbmfRY+dLSh3a9JwoEcBUso6EWYBakLbq4nG/nvYdYvG9ehrnLVwZFL82e\n" + "l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc=\n" + "-----END CERTIFICATE-----\n").getBytes(); /** * CN=*.co.jp */ public final static byte[] X509_WILD_CO_JP = ( "-----BEGIN CERTIFICATE-----\n" + "MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aVMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTYzMFoXDTI4MTEwNTE2MTYzMFowgaQx\n" + "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + "cnRpZmljYXRlczEQMA4GA1UEAxQHKi5jby5qcDElMCMGCSqGSIb3DQEJARYWanVs\n" + "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" + "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" + "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" + "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" + "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" + "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" + "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" + "hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" + "FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" + "yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQA0sWglVlMx2zNGvUqFC73XtREwii53\n" + "CfMM6mtf2+f3k/d8KXhLNySrg8RRlN11zgmpPaLtbdTLrmG4UdAHHYr8O4y2BBmE\n" + "1cxNfGxxechgF8HX10QV4dkyzp6Z1cfwvCeMrT5G/V1pejago0ayXx+GPLbWlNeZ\n" + "S+Kl0m3p+QplXujtwG5fYcIpaGpiYraBLx3Tadih39QN65CnAh/zRDhLCUzKyt9l\n" + "UGPLEUDzRHMPHLnSqT1n5UU5UDRytbjJPXzF+l/+WZIsanefWLsxnkgAuZe/oMMF\n" + "EJMryEzOjg4Tfuc5qM0EXoPcQ/JlheaxZ40p2IyHqbsWV4MRYuFH4bkM\n" + "-----END CERTIFICATE-----\n").getBytes(); /** * CN=*.foo.com, subjectAlt=*.bar.com, subjectAlt=*.&#x82b1;&#x5b50;.co.jp * (*.hanako.co.jp in kanji) */ public final static byte[] X509_WILD_FOO_BAR_HANAKO = ( "-----BEGIN CERTIFICATE-----\n" + "MIIEcDCCA1igAwIBAgIJAIz+EYMBU6aWMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTczMVoXDTI4MTEwNTE2MTczMVowgaYx\n" + "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" + "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" + "cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" + "dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" + "CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" + "jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" + "ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" + "JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" + "q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" + "qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo4GiMIGfMAkGA1UdEwQCMAAwLAYJ\n" + "YIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1Ud\n" + "DgQWBBSfFHe/Pzq2yjiCQkgWLNrQy16H2DAfBgNVHSMEGDAWgBR7mtqPkJlOUtKs\n" + "27MDUsqHpg0+DTAkBgNVHREEHTAbggkqLmJhci5jb22CDiou6Iqx5a2QLmNvLmpw\n" + "MA0GCSqGSIb3DQEBBQUAA4IBAQBobWC+D5/lx6YhX64CwZ26XLjxaE0S415ajbBq\n" + "DK7lz+Rg7zOE3GsTAMi+ldUYnhyz0wDiXB8UwKXl0SDToB2Z4GOgqQjAqoMmrP0u\n" + "WB6Y6dpkfd1qDRUzI120zPYgSdsXjHW9q2H77iV238hqIU7qCvEz+lfqqWEY504z\n" + "hYNlknbUnR525ItosEVwXFBJTkZ3Yw8gg02c19yi8TAh5Li3Ad8XQmmSJMWBV4XK\n" + "qFr0AIZKBlg6NZZFf/0dP9zcKhzSriW27bY0XfzA6GSiRDXrDjgXq6baRT6YwgIg\n" + "pgJsDbJtZfHnV1nd3M6zOtQPm1TIQpNmMMMd/DPrGcUQerD3\n" + "-----END CERTIFICATE-----\n").getBytes(); /** * CN=foo.com, CN=bar.com, CN=&#x82b1;&#x5b50;.co.jp */ public final static byte[] X509_THREE_CNS_FOO_BAR_HANAKO = ( "-----BEGIN CERTIFICATE-----\n" + "MIIEbzCCA1egAwIBAgIJAIz+EYMBU6aXMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTk0NVoXDTI4MTEwNTE2MTk0NVowgc0x\n" + "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" + "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" + "cnRpZmljYXRlczEQMA4GA1UEAwwHZm9vLmNvbTEQMA4GA1UEAwwHYmFyLmNvbTEV\n" + "MBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + "ZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyGOv\n" + "loI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pNjYGViGjg7zhf\n" + "bjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0ZHLN6sD9m2uV\n" + "Sp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1JVjTuE0pcBva\n" + "h2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6q/wGqcZ3zvFB\n" + "TcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYxqJUlPGlMqrKb\n" + "3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQf\n" + "Fh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86\n" + "tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0w\n" + "DQYJKoZIhvcNAQEFBQADggEBAGuZb8ai1NO2j4v3y9TLZvd5s0vh5/TE7n7RX+8U\n" + "y37OL5k7x9nt0mM1TyAKxlCcY+9h6frue8MemZIILSIvMrtzccqNz0V1WKgA+Orf\n" + "uUrabmn+CxHF5gpy6g1Qs2IjVYWA5f7FROn/J+Ad8gJYc1azOWCLQqSyfpNRLSvY\n" + "EriQFEV63XvkJ8JrG62b+2OT2lqT4OO07gSPetppdlSa8NBSKP6Aro9RIX1ZjUZQ\n" + "SpQFCfo02NO0uNRDPUdJx2huycdNb+AXHaO7eXevDLJ+QnqImIzxWiY6zLOdzjjI\n" + "VBMkLHmnP7SjGSQ3XA4ByrQOxfOUTyLyE7NuemhHppuQPxE=\n" + "-----END CERTIFICATE-----\n").getBytes(); /** * subjectAlt=foo.com */ public final static byte[] X509_NO_CNS_FOO = ( "-----BEGIN CERTIFICATE-----\n" + "MIIESjCCAzKgAwIBAgIJAIz+EYMBU6aYMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" + "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" + "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" + "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" + "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MjYxMFoXDTI4MTEwNTE2MjYxMFowgZIx\n" + "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" + "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" + "cnRpZmljYXRlczElMCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNv\n" + "bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMhjr5aCPoyp0R1iroWA\n" + "fnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2BlYho4O84X244QrZTRl8kQbYt\n" + "xnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRyzerA/ZtrlUqf+lKo0uWcocxe\n" + "Rc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY07hNKXAb2odnVqgzcYiDkLV8\n" + "ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8BqnGd87xQU3FVZI4tbtkB+Kz\n" + "jD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiVJTxpTKqym93whYk93l3ocEe5\n" + "5c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM\n" + "IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86tso4gkJIFiza\n" + "0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0wEgYDVR0RBAsw\n" + "CYIHZm9vLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEAjl78oMjzFdsMy6F1sGg/IkO8\n" + "tF5yUgPgFYrs41yzAca7IQu6G9qtFDJz/7ehh/9HoG+oqCCIHPuIOmS7Sd0wnkyJ\n" + "Y7Y04jVXIb3a6f6AgBkEFP1nOT0z6kjT7vkA5LJ2y3MiDcXuRNMSta5PYVnrX8aZ\n" + "yiqVUNi40peuZ2R8mAUSBvWgD7z2qWhF8YgDb7wWaFjg53I36vWKn90ZEti3wNCw\n" + "qAVqixM+J0qJmQStgAc53i2aTMvAQu3A3snvH/PHTBo+5UL72n9S1kZyNCsVf1Qo\n" + "n8jKTiRriEM+fMFlcgQP284EBFzYHyCXFb9O/hMjK2+6mY9euMB1U1aFFzM/Bg==\n" + "-----END CERTIFICATE-----\n").getBytes(); /** * Intermediate CA for all of these. */ public final static byte[] X509_INTERMEDIATE_CA = ( "-----BEGIN CERTIFICATE-----\n" + "MIIEnDCCA4SgAwIBAgIJAJTNwZ6yNa5cMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" + "VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" + "BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" + "hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjE0OTMx\n" + "WhcNMDcxMTA1MjE0OTMxWjCBojELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRIw\n" + "EAYDVQQHEwlWYW5jb3V2ZXIxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDASBgNV\n" + "BAsUC2NvbW1vbnNfc3NsMR0wGwYDVQQDFBRkZW1vX2ludGVybWVkaWF0ZV9jYTEl\n" + "MCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZI\n" + "hvcNAQEBBQADggEPADCCAQoCggEBAL0S4y3vUO0EM6lwqOEfK8fvrUprIbsikXaG\n" + "XzejcZ+T3l2Dc7t8WtBfRf78i4JypMqJQSijrUicj3H6mOMIReKaXm6ls4hA5d8w\n" + "Lhmgiqsz/kW+gA8SeWGWRN683BD/RbQmzOls6ynBvap9jZlthXWBrSIlPCQoBLXY\n" + "KVaxGzbL4ezaq+XFMKMQSm2uKwVmHHQNbfmZlPsuendBVomb/ked53Ab9IH6dwwN\n" + "qJH9WIrvIzIVEXWlpvQ5MCqozM7u1akU+G8cazr8theGPCaYkzoXnigWua4OjdpV\n" + "9z5ZDknhfBzG1AjapdG07FIirwWWgIyZXqZSD96ikmLtwT29qnsCAwEAAaOB7jCB\n" + "6zAdBgNVHQ4EFgQUe5raj5CZTlLSrNuzA1LKh6YNPg0wgbsGA1UdIwSBszCBsIAU\n" + "rN8eFIvMiRFXXgDqKumS0/W2AhOhgYykgYkwgYYxCzAJBgNVBAYTAkNBMQswCQYD\n" + "VQQIEwJCQzEWMBQGA1UEChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9u\n" + "c19zc2wxFTATBgNVBAMUDGRlbW9fcm9vdF9jYTElMCMGCSqGSIb3DQEJARYWanVs\n" + "aXVzZGF2aWVzQGdtYWlsLmNvbYIJAJTNwZ6yNa5bMAwGA1UdEwQFMAMBAf8wDQYJ\n" + "KoZIhvcNAQEFBQADggEBAIB4KMZvHD20pdKajFtMBpL7X4W4soq6EeTtjml3NYa9\n" + "Qc52bsQEGNccKY9afYSBIndaQvFdtmz6HdoN+B8TjYShw2KhyjtKimGLpWYoi1YF\n" + "e4aHdmA/Gp5xk8pZzR18FmooxC9RqBux+NAM2iTFSLgDtGIIj4sg2rbn6Bb6ZlQT\n" + "1rg6VucXCA1629lNfMeNcu7CBNmUKIdaxHR/YJQallE0KfGRiOIWPrPj/VNk0YA6\n" + "XFg0ocjqXJ2/N0N9rWVshMUaXgOh7m4D/5zga5/nuxDU+PoToA6mQ4bV6eCYqZbh\n" + "aa1kQYtR9B4ZiG6pB82qVc2dCqStOH2FAEWos2gAVkQ=\n" + "-----END CERTIFICATE-----\n").getBytes(); /** * Root CA for all of these. */ public final static byte[] X509_ROOT_CA = ( "-----BEGIN CERTIFICATE-----\n" + "MIIEgDCCA2igAwIBAgIJAJTNwZ6yNa5bMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" + "VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" + "BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" + "hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjEzNjQz\n" + "WhcNMjYxMTA1MjEzNjQzWjCBhjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYw\n" + "FAYDVQQKEw13d3cuY3VjYmMuY29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMG\n" + "A1UEAxQMZGVtb19yb290X2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNA\n" + "Z21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv+OnocmJ\n" + "79UeO2hlCwK+Cle5uZWnU6uwJl+08z5cvebb5tT64WL9+psDbfgUH/Gm9JsuxKTg\n" + "w1tZO/4duIgnaLNSx4HoqaTjwigd/hR3TsoGEPXTCkz1ikgTCOEDvl+iMid6aOrd\n" + "mViE8HhscxKZ+h5FE7oHZyuT6gFoiaIXhFq+xK2w4ZwDz9L+paiwqywyUJJMnh9U\n" + "jKorY+nua81N0oxpIhHPspCanDU4neMzCzYOZyLR/LqV5xORvHcFY84GWMz5hI25\n" + "JbgaWJsYKuCAvNsnQwVoqKPGa7x1fn7x6oGsXJaCVt8weUwIj2xwg1lxMhrNaisH\n" + "EvKpEAEnGGwWKQIDAQABo4HuMIHrMB0GA1UdDgQWBBSs3x4Ui8yJEVdeAOoq6ZLT\n" + "9bYCEzCBuwYDVR0jBIGzMIGwgBSs3x4Ui8yJEVdeAOoq6ZLT9bYCE6GBjKSBiTCB\n" + "hjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYwFAYDVQQKEw13d3cuY3VjYmMu\n" + "Y29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMGA1UEAxQMZGVtb19yb290X2Nh\n" + "MSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNAZ21haWwuY29tggkAlM3BnrI1\n" + "rlswDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAlPl3/8h1LttR1svC\n" + "S8RXbHpAWIT2BEDhGHUNjSmgDQNkE/itf/FCEXh0tlU4bYdtBSOHzflbnzOyIPId\n" + "VZeSWs33V38xDFy6KoVg1gT8JxkLmE5S1vWkpsHIlpw/U6r7KD0Kx9FYx5AiXjw0\n" + "lzz/zlVNuO2U09KIDwDPVG1mBzQiMiSWj1U1pM4KxINkWQwDy/fvu/I983s8lW5z\n" + "hf2WuFNzQN3fcMK5dpBE9NVIu27oYuGYh2sak34v+7T700W2ooBB71qFXtm9P5rl\n" + "Yp9RCEsg3KEEPNTtCBs8fROeXvLDrP0cmBIqwGYDuRNCxFDTOdjv6YGdA8nLOjaH\n" + "2dDk0g==\n" + "-----END CERTIFICATE-----\n").getBytes(); /** * Below is the private key for all the server certificates above (but * not the intermediate CA or the root CA). All of those server certs * came from the same private key. */ public final static String RSA_PUBLIC_MODULUS = "00c863af96823e8ca9d11d62ae85807e713204c1985a80a2747f7ac863c5" + "8d82e8c1ecf9698298d4838a4d8d81958868e0ef385f6e3842b653465f24" + "41b62dc671a1e204820fe67c82367f80cbcb52586a39bf965cf0141cc077" + "f46472cdeac0fd9b6b954a9ffa52a8d2e59ca1cc5e45cefbd4a37c70f1f7" + "9c7674ad5d07c78640672e94e31c4e6dee2bb52558d3b84d29701bda8767" + "56a83371888390b57c8a5bc49a8356316ae9f1406a913729121621098a77" + "713920270312baabfc06a9c677cef1414dc5559238b5bb6407e2b38c3f73" + "cfc4020c901f0e3647474dca350e66c4e817c31c0ac3a94631a895253c69" + "4caab29bddf085893dde5de87047b9e5cd"; public final static String RSA_PUBLIC_EXPONENT = "65537"; public final static String RSA_PRIVATE_EXPONENT = "577abd3295553d0efd4d38c13b62a6d03fa7b7e40cce4f1d5071877d96c6" + "7a39a63f0f7ab21a89db8acae45587b3ef251309a70f74dc1ac02bde68f3" + "8ed658e54e685ed370a18c054449512ea66a2252ed36e82b565b5159ec83" + "f23df40ae189550a183865b25fd77789e960f0d8cedcd72f32d7a66edb4b" + "a0a2baf3fbeb6c7d75f56ef0af9a7cff1c8c7f297d72eae7982164e50a89" + "d450698cf598d39343201094241d2d180a95882a7111e58f4a5bdbc5c125" + "a967dd6ed9ec614c5853e88e4c71e8b682a7cf89cb1d82b6fe78cc865084" + "c8c5dfbb50c939df2b839c977b0245bfa3615e0592b527b1013d5b675ecb" + "44e6b355c1df581f50997175166eef39"; public final static String RSA_PRIME1 = "00fe759c4f0ce8b763880215e82767e7a937297668f4e4b1e119c6b22a3c" + "a2c7b06c547d88d0aa45f645d7d3aeadaf7f8bc594deae0978529592977c" + "b1ff890f05033a9e9e15551cad9fbf9c41d12139ccd99c1c3ac7b2197eff" + "350d236bb900c1440953b64956e0a058ef824a2e16894af175177c77dbe1" + "fef7d8b532608d2513"; public final static String RSA_PRIME2 = "00c99a45878737a4cf73f9896680b75487f1b669b7686a6ba07103856f31" + "db668c2c440c44cdd116f708f631c37a9adf119f5b5cb58ffe3dc62e20af" + "af72693d936dc6bb3c5194996468389c1f094079b81522e94572b4ad7d39" + "529178e9b8ebaeb1f0fdd83b8731c5223f1dea125341d1d64917f6b1a6ae" + "c18d320510d79f859f"; public final static String RSA_EXPONENT1 = "029febf0d4cd41b7011c2465b4a259bd6118486464c247236f44a169d61e" + "47b9062508f674508d5031003ceabc57e714e600d71b2c75d5443db2da52" + "6bb45a374f0537c5a1aab3150764ce93cf386c84346a6bd01f6732e42075" + "c7a0e9e78a9e73b934e7d871d0f75673820089e129a1604438edcbbeb4e2" + "106467da112ce389"; public final static String RSA_EXPONENT2 = "00827e76650c946afcd170038d32e1f8386ab00d6be78d830efe382e45d4" + "7ad4bd04e6231ee22e66740efbf52838134932c9f8c460cdccdec58a1424" + "4427859192fd6ab6c58b74e97941b0eaf577f2a11713af5e5952af3ae124" + "9a9a892e98410dfa2628d9af668a43b5302fb7d496c9b2fec69f595292b6" + "e997f079b0f6314eb7"; public final static String RSA_COEFFICIENT = "00e6b62add350f1a2a8968903ff76c31cf703b0d7326c4a620aef01225b7" + "1640b3f2ec375208c5f7299863f6005b7799b6e529bb1133c8435bf5fdb5" + "a786f6cd8a19ee7094a384e6557c600a38845a0960ddbfd1df18d0af5740" + "001853788f1b5ccbf9affb4c52c9d2efdb8aab0183d86735b32737fb4e79" + "2b8a9c7d91c7d175ae"; /** * subjectAlt=IP Address:127.0.0.1, email:oleg@ural.ru, DNS:localhost.localdomain */ public final static byte[] X509_MULTIPLE_SUBJECT_ALT = ( "-----BEGIN CERTIFICATE-----\n" + "MIIDcTCCAtqgAwIBAgIBATANBgkqhkiG9w0BAQUFADBAMQswCQYDVQQGEwJDSDEL\n" + "MAkGA1UECBMCWkgxDzANBgNVBAcTBlp1cmljaDETMBEGA1UEAxMKTXkgVGVzdCBD\n" + "QTAeFw0wODEwMzExMTU3NDVaFw0wOTEwMzExMTU3NDVaMGkxCzAJBgNVBAYTAkNI\n" + "MRAwDgYDVQQIEwdVbmtub3duMRAwDgYDVQQHEwdVbmtub3duMRAwDgYDVQQKEwdV\n" + "bmtub3duMRAwDgYDVQQLEwdVbmtub3duMRIwEAYDVQQDEwlsb2NhbGhvc3QwggG4\n" + "MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YRt1I870QAwx4/\n" + "gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQ\n" + "IsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZ\n" + "ndFIAccCFQCXYFCPFSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5\n" + "eZSvu/o66oL5V0wLPQeCZ1FZV4661FlP5nEHEIGAtEkWcSPoTCgWE7fPCTKMyKbh\n" + "PBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7YnoBJDvMpPG+qFGQiaiD3+Fa5Z8G\n" + "kotmXoB7VSVkAUw7/s9JKgOBhQACgYEA6ogAb/YLM1Rz9AoXKW4LA70VtFf7Mqqp\n" + "divdu9f72WQc1vMKo1YMf3dQadkMfBYRvAAa1IXDnoiFCHhXnVRkWkoUBJyNebLB\n" + "N92CZc0RVFZiMFgQMEh8UldnvAIi4cBk0/YuN3BGl4MzmquVIGrFovdWGqeaveOu\n" + "Xcu4lKGJNiqjODA2MDQGA1UdEQQtMCuHBH8AAAGBDG9sZWdAdXJhbC5ydYIVbG9j\n" + "YWxob3N0LmxvY2FsZG9tYWluMA0GCSqGSIb3DQEBBQUAA4GBAIgEwIoCSRkU3O7K\n" + "USYaOYyfJB9hsvs6YpClvYXiQ/5kPGARP60pM62v4wC7wI9shEizokIAxY2+O3cC\n" + "vwuJhNYaa2FJMELIwRN3XES8X8R6JHWbPaRjaAAPhczuEd8SZYy8yiVLmJTgw0gH\n" + "BSW775NHlkjsscFVgXkNf0PobqJ9\n" + "-----END CERTIFICATE-----").getBytes(); }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/conn/ssl/CertificatesToPlayWith.java
Java
gpl3
30,373
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.localserver; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseInterceptor; import org.apache.ogt.http.HttpStatus; import org.apache.ogt.http.auth.AUTH; import org.apache.ogt.http.protocol.HttpContext; public class ResponseBasicUnauthorized implements HttpResponseInterceptor { public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { response.addHeader(AUTH.WWW_AUTH, "Basic realm=\"test realm\""); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/localserver/ResponseBasicUnauthorized.java
Java
gpl3
1,918
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.localserver; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Locale; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpStatus; import org.apache.ogt.http.MethodNotSupportedException; import org.apache.ogt.http.entity.AbstractHttpEntity; import org.apache.ogt.http.protocol.HttpContext; import org.apache.ogt.http.protocol.HttpRequestHandler; /** * A handler that generates random data. * * * * <!-- empty lines to avoid 'svn diff' problems --> */ public class RandomHandler implements HttpRequestHandler { // public default constructor /** * Handles a request by generating random data. * The length of the response can be specified in the request URI * as a number after the last /. For example /random/whatever/20 * will generate 20 random bytes in the printable ASCII range. * If the request URI ends with /, a random number of random bytes * is generated, but at least one. * * @param request the request * @param response the response * @param context the context * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem */ public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!"GET".equals(method) && !"HEAD".equals(method)) { throw new MethodNotSupportedException (method + " not supported by " + getClass().getName()); } String uri = request.getRequestLine().getUri(); int slash = uri.lastIndexOf('/'); int length = -1; if (slash < uri.length()-1) { try { // no more than Integer, 2 GB ought to be enough for anybody length = Integer.parseInt(uri.substring(slash+1)); if (length < 0) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); response.setReasonPhrase("LENGTH " + length); } } catch (NumberFormatException nfx) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); response.setReasonPhrase(nfx.toString()); } } else { // random length, but make sure at least something is sent length = 1 + (int)(Math.random() * 79.0); } if (length >= 0) { response.setStatusCode(HttpStatus.SC_OK); if (!"HEAD".equals(method)) { RandomEntity entity = new RandomEntity(length); entity.setContentType("text/plain; charset=US-ASCII"); response.setEntity(entity); } else { response.setHeader("Content-Type", "text/plain; charset=US-ASCII"); response.setHeader("Content-Length", String.valueOf(length)); } } } // handle /** * An entity that generates random data. * This is an outgoing entity, it supports {@link #writeTo writeTo} * but not {@link #getContent getContent}. */ public static class RandomEntity extends AbstractHttpEntity { /** The range from which to generate random data. */ private final static byte[] RANGE; static { byte[] range = null; try { range = ("abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" ).getBytes("US-ASCII"); } catch (UnsupportedEncodingException uex) { // never, US-ASCII is guaranteed } RANGE = range; } /** The length of the random data to generate. */ protected final long length; /** * Creates a new entity generating the given amount of data. * * @param len the number of random bytes to generate, * 0 to maxint */ public RandomEntity(long len) { if (len < 0L) throw new IllegalArgumentException ("Length must not be negative"); if (len > Integer.MAX_VALUE) throw new IllegalArgumentException ("Length must not exceed Integer.MAX_VALUE"); length = len; } /** * Tells that this entity is not streaming. * * @return false */ public final boolean isStreaming() { return false; } /** * Tells that this entity is repeatable, in a way. * Repetitions will generate different random data, * unless perchance the same random data is generated twice. * * @return <code>true</code> */ public boolean isRepeatable() { return true; } /** * Obtains the size of the random data. * * @return the number of random bytes to generate */ public long getContentLength() { return length; } /** * Not supported. * This method throws an exception. * * @return never anything */ public InputStream getContent() { throw new UnsupportedOperationException(); } /** * Generates the random content. * * @param out where to write the content to */ public void writeTo(OutputStream out) throws IOException { final int blocksize = 2048; int remaining = (int) length; // range checked in constructor byte[] data = new byte[Math.min(remaining, blocksize)]; while (remaining > 0) { final int end = Math.min(remaining, data.length); double value = 0.0; for (int i = 0; i < end; i++) { // we get 5 random characters out of one random value if (i%5 == 0) { value = Math.random(); } value = value * RANGE.length; int d = (int) value; value = value - d; data[i] = RANGE[d]; } out.write(data, 0, end); out.flush(); remaining = remaining - end; } out.close(); } // writeTo } // class RandomEntity } // class RandomHandler
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/localserver/RandomHandler.java
Java
gpl3
8,144
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.localserver; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocketFactory; import org.apache.ogt.http.ConnectionReuseStrategy; import org.apache.ogt.http.HttpResponseFactory; import org.apache.ogt.http.HttpResponseInterceptor; import org.apache.ogt.http.HttpServerConnection; import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy; import org.apache.ogt.http.impl.DefaultHttpResponseFactory; import org.apache.ogt.http.impl.DefaultHttpServerConnection; import org.apache.ogt.http.params.CoreConnectionPNames; import org.apache.ogt.http.params.CoreProtocolPNames; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.params.SyncBasicHttpParams; import org.apache.ogt.http.protocol.BasicHttpContext; import org.apache.ogt.http.protocol.BasicHttpProcessor; import org.apache.ogt.http.protocol.HttpContext; import org.apache.ogt.http.protocol.HttpExpectationVerifier; import org.apache.ogt.http.protocol.HttpProcessor; import org.apache.ogt.http.protocol.HttpRequestHandler; import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry; import org.apache.ogt.http.protocol.HttpService; import org.apache.ogt.http.protocol.ImmutableHttpProcessor; import org.apache.ogt.http.protocol.ResponseConnControl; import org.apache.ogt.http.protocol.ResponseContent; import org.apache.ogt.http.protocol.ResponseDate; import org.apache.ogt.http.protocol.ResponseServer; /** * Local HTTP server for tests that require one. * Based on the <code>ElementalHttpServer</code> example in HttpCore. */ public class LocalTestServer { /** * The local address to bind to. * The host is an IP number rather than "localhost" to avoid surprises * on hosts that map "localhost" to an IPv6 address or something else. * The port is 0 to let the system pick one. */ public final static InetSocketAddress TEST_SERVER_ADDR = new InetSocketAddress("127.0.0.1", 0); /** The request handler registry. */ private final HttpRequestHandlerRegistry handlerRegistry; private final HttpService httpservice; /** Optional SSL context */ private final SSLContext sslcontext; /** The server socket, while being served. */ private volatile ServerSocket servicedSocket; /** The request listening thread, while listening. */ private volatile ListenerThread listenerThread; /** Set of active worker threads */ private final Set<Worker> workers; /** The number of connections this accepted. */ private final AtomicInteger acceptedConnections = new AtomicInteger(0); /** * Creates a new test server. * * @param proc the HTTP processors to be used by the server, or * <code>null</code> to use a * {@link #newProcessor default} processor * @param reuseStrat the connection reuse strategy to be used by the * server, or <code>null</code> to use * {@link #newConnectionReuseStrategy() default} * strategy. * @param params the parameters to be used by the server, or * <code>null</code> to use * {@link #newDefaultParams default} parameters * @param sslcontext optional SSL context if the server is to leverage * SSL/TLS transport security */ public LocalTestServer( final BasicHttpProcessor proc, final ConnectionReuseStrategy reuseStrat, final HttpResponseFactory responseFactory, final HttpExpectationVerifier expectationVerifier, final HttpParams params, final SSLContext sslcontext) { super(); this.handlerRegistry = new HttpRequestHandlerRegistry(); this.workers = Collections.synchronizedSet(new HashSet<Worker>()); this.httpservice = new HttpService( proc != null ? proc : newProcessor(), reuseStrat != null ? reuseStrat: newConnectionReuseStrategy(), responseFactory != null ? responseFactory: newHttpResponseFactory(), handlerRegistry, expectationVerifier, params != null ? params : newDefaultParams()); this.sslcontext = sslcontext; } /** * Creates a new test server with SSL/TLS encryption. * * @param sslcontext SSL context */ public LocalTestServer(final SSLContext sslcontext) { this(null, null, null, null, null, sslcontext); } /** * Creates a new test server. * * @param proc the HTTP processors to be used by the server, or * <code>null</code> to use a * {@link #newProcessor default} processor * @param params the parameters to be used by the server, or * <code>null</code> to use * {@link #newDefaultParams default} parameters */ public LocalTestServer( BasicHttpProcessor proc, HttpParams params) { this(proc, null, null, null, params, null); } /** * Obtains an HTTP protocol processor with default interceptors. * * @return a protocol processor for server-side use */ protected HttpProcessor newProcessor() { return new ImmutableHttpProcessor( new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); } /** * Obtains a set of reasonable default parameters for a server. * * @return default parameters */ protected HttpParams newDefaultParams() { HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "LocalTestServer/1.1"); return params; } protected ConnectionReuseStrategy newConnectionReuseStrategy() { return new DefaultConnectionReuseStrategy(); } protected HttpResponseFactory newHttpResponseFactory() { return new DefaultHttpResponseFactory(); } /** * Returns the number of connections this test server has accepted. */ public int getAcceptedConnectionCount() { return acceptedConnections.get(); } /** * {@link #register Registers} a set of default request handlers. * <pre> * URI pattern Handler * ----------- ------- * /echo/* {@link EchoHandler EchoHandler} * /random/* {@link RandomHandler RandomHandler} * </pre> */ public void registerDefaultHandlers() { handlerRegistry.register("/echo/*", new EchoHandler()); handlerRegistry.register("/random/*", new RandomHandler()); } /** * Registers a handler with the local registry. * * @param pattern the URL pattern to match * @param handler the handler to apply */ public void register(String pattern, HttpRequestHandler handler) { handlerRegistry.register(pattern, handler); } /** * Unregisters a handler from the local registry. * * @param pattern the URL pattern */ public void unregister(String pattern) { handlerRegistry.unregister(pattern); } /** * Starts this test server. */ public void start() throws Exception { if (servicedSocket != null) { throw new IllegalStateException(this.toString() + " already running"); } ServerSocket ssock; if (sslcontext != null) { SSLServerSocketFactory sf = sslcontext.getServerSocketFactory(); ssock = sf.createServerSocket(); } else { ssock = new ServerSocket(); } ssock.setReuseAddress(true); // probably pointless for port '0' ssock.bind(TEST_SERVER_ADDR); servicedSocket = ssock; listenerThread = new ListenerThread(); listenerThread.setDaemon(false); listenerThread.start(); } /** * Stops this test server. */ public void stop() throws Exception { if (servicedSocket == null) { return; // not running } ListenerThread t = listenerThread; if (t != null) { t.shutdown(); } synchronized (workers) { for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) { Worker worker = it.next(); worker.shutdown(); } } } public void awaitTermination(long timeMs) throws InterruptedException { if (listenerThread != null) { listenerThread.join(timeMs); } } @Override public String toString() { ServerSocket ssock = servicedSocket; // avoid synchronization StringBuilder sb = new StringBuilder(80); sb.append("LocalTestServer/"); if (ssock == null) sb.append("stopped"); else sb.append(ssock.getLocalSocketAddress()); return sb.toString(); } /** * Obtains the local address the server is listening on * * @return the service address */ public InetSocketAddress getServiceAddress() { ServerSocket ssock = servicedSocket; // avoid synchronization if (ssock == null) { throw new IllegalStateException("not running"); } return (InetSocketAddress) ssock.getLocalSocketAddress(); } /** * The request listener. * Accepts incoming connections and launches a service thread. */ class ListenerThread extends Thread { private volatile Exception exception; ListenerThread() { super(); } @Override public void run() { try { while (!interrupted()) { Socket socket = servicedSocket.accept(); acceptedConnections.incrementAndGet(); DefaultHttpServerConnection conn = new DefaultHttpServerConnection(); conn.bind(socket, httpservice.getParams()); // Start worker thread Worker worker = new Worker(conn); workers.add(worker); worker.setDaemon(true); worker.start(); } } catch (Exception ex) { this.exception = ex; } finally { try { servicedSocket.close(); } catch (IOException ignore) { } } } public void shutdown() { interrupt(); try { servicedSocket.close(); } catch (IOException ignore) { } } public Exception getException() { return this.exception; } } class Worker extends Thread { private final HttpServerConnection conn; private volatile Exception exception; public Worker(final HttpServerConnection conn) { this.conn = conn; } @Override public void run() { HttpContext context = new BasicHttpContext(); try { while (this.conn.isOpen() && !Thread.interrupted()) { httpservice.handleRequest(this.conn, context); } } catch (Exception ex) { this.exception = ex; } finally { workers.remove(this); try { this.conn.shutdown(); } catch (IOException ignore) { } } } public void shutdown() { interrupt(); try { this.conn.shutdown(); } catch (IOException ignore) { } } public Exception getException() { return this.exception; } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/localserver/LocalTestServer.java
Java
gpl3
13,856
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.localserver; import org.apache.commons.codec.BinaryDecoder; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base64; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.auth.AUTH; import org.apache.ogt.http.util.EncodingUtils; public class BasicAuthTokenExtractor { public String extract(final HttpRequest request) throws HttpException { String auth = null; Header h = request.getFirstHeader(AUTH.WWW_AUTH_RESP); if (h != null) { String s = h.getValue(); if (s != null) { auth = s.trim(); } } if (auth != null) { int i = auth.indexOf(' '); if (i == -1) { throw new ProtocolException("Invalid Authorization header: " + auth); } String authscheme = auth.substring(0, i); if (authscheme.equalsIgnoreCase("basic")) { String s = auth.substring(i + 1).trim(); try { byte[] credsRaw = EncodingUtils.getAsciiBytes(s); BinaryDecoder codec = new Base64(); auth = EncodingUtils.getAsciiString(codec.decode(credsRaw)); } catch (DecoderException ex) { throw new ProtocolException("Malformed BASIC credentials"); } } } return auth; } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/localserver/BasicAuthTokenExtractor.java
Java
gpl3
2,767
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.localserver; import java.net.InetSocketAddress; import org.apache.ogt.http.HttpHost; import org.junit.After; /** * Base class for tests using {@link LocalTestServer}. The server will not be started * per default. */ public abstract class BasicServerTestBase { /** The local server for testing. */ protected LocalTestServer localServer; @After public void tearDown() throws Exception { if (localServer != null) { localServer.stop(); } } /** * Obtains the address of the local test server. * * @return the test server host, with a scheme name of "http" */ protected HttpHost getServerHttp() { InetSocketAddress address = localServer.getServiceAddress(); return new HttpHost( address.getHostName(), address.getPort(), "http"); } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/localserver/BasicServerTestBase.java
Java
gpl3
2,096
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.localserver; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.conn.scheme.PlainSocketFactory; import org.apache.ogt.http.conn.scheme.Scheme; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.conn.scheme.SchemeSocketFactory; import org.apache.ogt.http.impl.DefaultHttpClientConnection; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.params.HttpProtocolParams; import org.apache.ogt.http.params.SyncBasicHttpParams; import org.apache.ogt.http.protocol.BasicHttpContext; import org.apache.ogt.http.protocol.BasicHttpProcessor; import org.apache.ogt.http.protocol.HttpRequestExecutor; import org.apache.ogt.http.protocol.RequestConnControl; import org.apache.ogt.http.protocol.RequestContent; import org.junit.Before; /** * Base class for tests using {@link LocalTestServer LocalTestServer}. * Note that the test server will be {@link #setUp set up} before each * individual tests and {@link #tearDown teared down} afterwards. * Use this base class <i>exclusively</i> for tests that require the * server. If you have some tests that require the server and others * that don't, split them in two different classes. */ public abstract class ServerTestBase extends BasicServerTestBase { /** The available schemes. */ protected SchemeRegistry supportedSchemes; /** The default parameters for the client side. */ protected HttpParams defaultParams; /** The HTTP processor for the client side. */ protected BasicHttpProcessor httpProcessor; /** The default context for the client side. */ protected BasicHttpContext httpContext; /** The request executor for the client side. */ protected HttpRequestExecutor httpExecutor; /** * Prepares the local server for testing. * Derived classes that override this method MUST call * the implementation here. That SHOULD be done at the * beginning of the overriding method. * <br/> * Derived methods can modify for example the default parameters * being set up, or the interceptors. * <p> * This method will re-use the helper objects from a previous run * if they are still available. For example, the local test server * will be re-started rather than re-created. * {@link #httpContext httpContext} will always be re-created. * Tests that modify the other helper objects should afterwards * set the respective attributes to <code>null</code> in a * <code>finally{}</code> block to force re-creation for * subsequent tests. * Of course that shouldn't be done with the test server, * or only after shutting that down. * * @throws Exception in case of a problem */ @Before public void setUp() throws Exception { if (defaultParams == null) { defaultParams = new SyncBasicHttpParams(); HttpProtocolParams.setVersion (defaultParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset (defaultParams, "UTF-8"); HttpProtocolParams.setUserAgent (defaultParams, "TestAgent/1.1"); HttpProtocolParams.setUseExpectContinue (defaultParams, false); } if (supportedSchemes == null) { supportedSchemes = new SchemeRegistry(); SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", 80, sf)); } if (httpProcessor == null) { httpProcessor = new BasicHttpProcessor(); httpProcessor.addInterceptor(new RequestContent()); httpProcessor.addInterceptor(new RequestConnControl()); // optional } // the context is created each time, it may get modified by test cases httpContext = new BasicHttpContext(null); if (httpExecutor == null) { httpExecutor = new HttpRequestExecutor(); } if (localServer == null) { localServer = new LocalTestServer(null, null); localServer.registerDefaultHandlers(); } localServer.start(); } // setUp /** * Opens a connection to the given target using * {@link #defaultParams default parameters}. * Maps to {@link #connectTo(HttpHost,HttpParams) * connectTo(target,defaultParams)}. * * @param target the target to connect to * * @return a new connection opened to the target * * @throws Exception in case of a problem */ protected DefaultHttpClientConnection connectTo(HttpHost target) throws Exception { return connectTo(target, defaultParams); } /** * Opens a connection to the given target using the given parameters. * * @param target the target to connect to * * @return a new connection opened to the target * * @throws Exception in case of a problem */ protected DefaultHttpClientConnection connectTo(HttpHost target, HttpParams params) throws Exception { Scheme schm = supportedSchemes.get(target.getSchemeName()); int port = schm.resolvePort(target.getPort()); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); InetSocketAddress address = new InetSocketAddress( InetAddress.getByName(target.getHostName()), port); Socket sock = schm.getSchemeSocketFactory().connectSocket(null, address, null, params); conn.bind(sock, params); return conn; } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/localserver/ServerTestBase.java
Java
gpl3
7,022
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.localserver; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.protocol.HttpContext; public class RequestBasicAuth implements HttpRequestInterceptor { private final BasicAuthTokenExtractor authTokenExtractor; public RequestBasicAuth() { super(); this.authTokenExtractor = new BasicAuthTokenExtractor(); } public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { context.setAttribute("creds", this.authTokenExtractor.extract(request)); } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/localserver/RequestBasicAuth.java
Java
gpl3
1,919
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.localserver; import java.io.IOException; import java.util.Locale; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpStatus; import org.apache.ogt.http.MethodNotSupportedException; import org.apache.ogt.http.entity.ByteArrayEntity; import org.apache.ogt.http.protocol.HttpContext; import org.apache.ogt.http.protocol.HttpRequestHandler; import org.apache.ogt.http.util.EntityUtils; /** * A handler that echos the incoming request entity. * * * * <!-- empty lines to avoid 'svn diff' problems --> */ public class EchoHandler implements HttpRequestHandler { // public default constructor /** * Handles a request by echoing the incoming request entity. * If there is no request entity, an empty document is returned. * * @param request the request * @param response the response * @param context the context * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem */ public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!"GET".equals(method) && !"POST".equals(method) && !"PUT".equals(method) ) { throw new MethodNotSupportedException (method + " not supported by " + getClass().getName()); } HttpEntity entity = null; if (request instanceof HttpEntityEnclosingRequest) entity = ((HttpEntityEnclosingRequest)request).getEntity(); // For some reason, just putting the incoming entity into // the response will not work. We have to buffer the message. byte[] data; if (entity == null) { data = new byte [0]; } else { data = EntityUtils.toByteArray(entity); } ByteArrayEntity bae = new ByteArrayEntity(data); if (entity != null) { bae.setContentType(entity.getContentType()); } entity = bae; response.setStatusCode(HttpStatus.SC_OK); response.setEntity(entity); } // handle } // class EchoHandler
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/test/java/org/apache/ogt/http/localserver/EchoHandler.java
Java
gpl3
3,716
@import url("../../../css/hc-maven.css");
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/site/resources/css/site.css
CSS
gpl3
42
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import java.io.IOException; import java.io.InputStream; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.impl.client.DefaultHttpClient; /** * This example demonstrates the recommended way of using API to make sure * the underlying connection gets released back to the connection manager. */ public class ClientConnectionRelease { public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet("http://www.apache.org/"); // Execute HTTP request System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); // Get hold of the response entity HttpEntity entity = response.getEntity(); // If the response does not enclose an entity, there is no need // to bother about connection release if (entity != null) { InputStream instream = entity.getContent(); try { instream.read(); // do something useful with the response } catch (IOException ex) { // In case of an IOException the connection will be released // back to the connection manager automatically throw ex; } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection immediately. httpget.abort(); throw ex; } finally { // Closing the input stream will trigger connection release try { instream.close(); } catch (Exception ignore) {} } } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientConnectionRelease.java
Java
gpl3
3,794
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import java.util.ArrayList; import java.util.List; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.client.entity.UrlEncodedFormEntity; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpPost; import org.apache.ogt.http.cookie.Cookie; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.message.BasicNameValuePair; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.util.EntityUtils; /** * A example that demonstrates how HttpClient APIs can be used to perform * form-based logon. */ public class ClientFormLogin { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); System.out.println("Initial set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" + "org=self_registered_users&" + "goto=/portal/dt&" + "gotoOnFail=/portal/dt?error=true"); List <NameValuePair> nvps = new ArrayList <NameValuePair>(); nvps.add(new BasicNameValuePair("IDToken1", "username")); nvps.add(new BasicNameValuePair("IDToken2", "password")); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); response = httpclient.execute(httpost); entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientFormLogin.java
Java
gpl3
4,234
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.ogt.http.protocol.BasicHttpContext; import org.apache.ogt.http.protocol.HttpContext; import org.apache.ogt.http.util.EntityUtils; /** * An example that performs GETs from multiple threads. * */ public class ClientMultiThreadedExecution { public static void main(String[] args) throws Exception { // Create an HttpClient with the ThreadSafeClientConnManager. // This connection manager must be used if more than one thread will // be using the HttpClient. ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(); cm.setMaxTotal(100); HttpClient httpclient = new DefaultHttpClient(cm); try { // create an array of URIs to perform GETs on String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/", "http://hc.apache.org/httpcomponents-client-ga/", "http://svn.apache.org/viewvc/httpcomponents/" }; // create a thread for each URI GetThread[] threads = new GetThread[urisToGet.length]; for (int i = 0; i < threads.length; i++) { HttpGet httpget = new HttpGet(urisToGet[i]); threads[i] = new GetThread(httpclient, httpget, i + 1); } // start the threads for (int j = 0; j < threads.length; j++) { threads[j].start(); } // join the threads for (int j = 0; j < threads.length; j++) { threads[j].join(); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } /** * A thread that performs a GET. */ static class GetThread extends Thread { private final HttpClient httpClient; private final HttpContext context; private final HttpGet httpget; private final int id; public GetThread(HttpClient httpClient, HttpGet httpget, int id) { this.httpClient = httpClient; this.context = new BasicHttpContext(); this.httpget = httpget; this.id = id; } /** * Executes the GetMethod and prints some status information. */ @Override public void run() { System.out.println(id + " - about to get something from " + httpget.getURI()); try { // execute the method HttpResponse response = httpClient.execute(httpget, context); System.out.println(id + " - get executed"); // get the response body as an array of bytes HttpEntity entity = response.getEntity(); if (entity != null) { byte[] bytes = EntityUtils.toByteArray(entity); System.out.println(id + " - " + bytes.length + " bytes read"); } } catch (Exception e) { httpget.abort(); System.out.println(id + " - error: " + e); } } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientMultiThreadedExecution.java
Java
gpl3
4,857
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import java.io.File; import java.io.FileInputStream; import java.security.KeyStore; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.conn.scheme.Scheme; import org.apache.ogt.http.conn.ssl.SSLSocketFactory; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; /** * This example demonstrates how to create secure connections with a custom SSL * context. */ public class ClientCustomSSL { public final static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("my.keystore")); try { trustStore.load(instream, "nopassword".toCharArray()); } finally { try { instream.close(); } catch (Exception ignore) {} } SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); Scheme sch = new Scheme("https", 443, socketFactory); httpclient.getConnectionManager().getSchemeRegistry().register(sch); HttpGet httpget = new HttpGet("https://localhost/"); System.out.println("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientCustomSSL.java
Java
gpl3
3,395
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.conn.ConnectTimeoutException; import org.apache.ogt.http.conn.scheme.Scheme; import org.apache.ogt.http.conn.scheme.SchemeSocketFactory; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.params.HttpConnectionParams; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.util.EntityUtils; /** * How to send a request via SOCKS proxy using {@link HttpClient}. * * @since 4.1 */ public class ClientExecuteSOCKS { public static void main(String[] args)throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { httpclient.getParams().setParameter("socks.host", "mysockshost"); httpclient.getParams().setParameter("socks.port", 1234); httpclient.getConnectionManager().getSchemeRegistry().register( new Scheme("http", 80, new MySchemeSocketFactory())); HttpHost target = new HttpHost("www.apache.org", 80, "http"); HttpGet req = new HttpGet("/"); System.out.println("executing request to " + target + " via SOCKS proxy"); HttpResponse rsp = httpclient.execute(target, req); HttpEntity entity = rsp.getEntity(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); Header[] headers = rsp.getAllHeaders(); for (int i = 0; i<headers.length; i++) { System.out.println(headers[i]); } System.out.println("----------------------------------------"); if (entity != null) { System.out.println(EntityUtils.toString(entity)); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } static class MySchemeSocketFactory implements SchemeSocketFactory { public Socket createSocket(final HttpParams params) throws IOException { if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } String proxyHost = (String) params.getParameter("socks.host"); Integer proxyPort = (Integer) params.getParameter("socks.port"); InetSocketAddress socksaddr = new InetSocketAddress(proxyHost, proxyPort); Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr); return new Socket(proxy); } public Socket connectSocket( final Socket socket, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (remoteAddress == null) { throw new IllegalArgumentException("Remote address may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } Socket sock; if (socket != null) { sock = socket; } else { sock = createSocket(params); } if (localAddress != null) { sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params)); sock.bind(localAddress); } int timeout = HttpConnectionParams.getConnectionTimeout(params); try { sock.connect(remoteAddress, timeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/" + remoteAddress.getAddress() + " timed out"); } return sock; } public boolean isSecure(final Socket sock) throws IllegalArgumentException { return false; } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientExecuteSOCKS.java
Java
gpl3
5,816
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import org.apache.ogt.http.client.ResponseHandler; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.impl.client.BasicResponseHandler; import org.apache.ogt.http.impl.client.DefaultHttpClient; /** * This example demonstrates the use of the {@link ResponseHandler} to simplify * the process of processing the HTTP response and releasing associated resources. */ public class ClientWithResponseHandler { public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet("http://www.google.com/"); System.out.println("executing request " + httpget.getURI()); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); System.out.println("----------------------------------------"); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientWithResponseHandler.java
Java
gpl3
2,677
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import java.util.List; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.CookieStore; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.protocol.ClientContext; import org.apache.ogt.http.cookie.Cookie; import org.apache.ogt.http.impl.client.BasicCookieStore; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.protocol.HttpContext; import org.apache.ogt.http.protocol.BasicHttpContext; import org.apache.ogt.http.util.EntityUtils; /** * This example demonstrates the use of a local HTTP context populated with * custom attributes. */ public class ClientCustomContext { public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); try { // Create a local instance of cookie store CookieStore cookieStore = new BasicCookieStore(); // Create local HTTP context HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet httpget = new HttpGet("http://www.google.com/"); System.out.println("executing request " + httpget.getURI()); // Pass local context as a parameter HttpResponse response = httpclient.execute(httpget, localContext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } List<Cookie> cookies = cookieStore.getCookies(); for (int i = 0; i < cookies.size(); i++) { System.out.println("Local cookie: " + cookies.get(i)); } // Consume response content EntityUtils.consume(entity); System.out.println("----------------------------------------"); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientCustomContext.java
Java
gpl3
3,732
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.ogt.http.examples.client; import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpStatus; import org.apache.ogt.http.auth.AuthScope; import org.apache.ogt.http.auth.AuthState; import org.apache.ogt.http.auth.Credentials; import org.apache.ogt.http.auth.UsernamePasswordCredentials; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.protocol.ClientContext; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.protocol.BasicHttpContext; import org.apache.ogt.http.protocol.HttpContext; import org.apache.ogt.http.util.EntityUtils; /** * A simple example that uses HttpClient to execute an HTTP request against * a target site that requires user authentication. */ public class ClientInteractiveAuthentication { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { // Create local execution context HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet("http://localhost/test"); boolean trying = true; while (trying) { System.out.println("executing request " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget, localContext); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // Consume response content HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); int sc = response.getStatusLine().getStatusCode(); AuthState authState = null; if (sc == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (authState != null) { System.out.println("----------------------------------------"); AuthScope authScope = authState.getAuthScope(); System.out.println("Please provide credentials"); System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort()); System.out.println(" Realm: " + authScope.getRealm()); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter username: "); String user = console.readLine(); System.out.print("Enter password: "); String password = console.readLine(); if (user != null && user.length() > 0) { Credentials creds = new UsernamePasswordCredentials(user, password); httpclient.getCredentialsProvider().setCredentials(authScope, creds); trying = true; } else { trying = false; } } else { trying = false; } } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientInteractiveAuthentication.java
Java
gpl3
5,073
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.ogt.http.examples.client; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.auth.AuthScope; import org.apache.ogt.http.auth.UsernamePasswordCredentials; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; /** * A simple example that uses HttpClient to execute an HTTP request against * a target site that requires user authentication. */ public class ClientAuthentication { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { httpclient.getCredentialsProvider().setCredentials( new AuthScope("localhost", 443), new UsernamePasswordCredentials("username", "password")); HttpGet httpget = new HttpGet("https://localhost/protected"); System.out.println("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientAuthentication.java
Java
gpl3
2,953
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.ogt.http.examples.client; import java.security.Principal; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.auth.AuthScope; import org.apache.ogt.http.auth.Credentials; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.methods.HttpUriRequest; import org.apache.ogt.http.client.params.AuthPolicy; import org.apache.ogt.http.impl.auth.NegotiateSchemeFactory; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; /** * Kerberos auth example. * * <p><b>Information</b></p> * <p>For the best compatibility use Java >= 1.6 as it supports SPNEGO authentication more completely.</p> * <p><em>NegotiateSchemeFactory</em> kas two custom methods</p> * <p><em>#setStripPort(boolean)</em> - default is false, with strip the port off the Kerberos * service name if true. Found useful with JBoss Negotiation. Can be used with Java >= 1.5</p> * <p><em>#setSpengoGenerator(SpnegoTokenGenerator)</em> - default is null, class to use to wrap * kerberos token. An example is in contrib - <em>org.apache.ogt.http.contrib.auth.BouncySpnegoTokenGenerator</em>. * Requires use of <a href="http://www.bouncycastle.org/java.html">bouncy castle libs</a>. * Useful with Java 1.5. * </p> * <p><b>Addtional Config Files</b></p> * <p>Two files control how Java uses/configures Kerberos. Very basic examples are below. There * is a large amount of information on the web.</p> * <p><a href="http://java.sun.com/j2se/1.5.0/docs/guide/security/jaas/spec/com/sun/security/auth/module/Krb5LoginModule.html">http://java.sun.com/j2se/1.5.0/docs/guide/security/jaas/spec/com/sun/security/auth/module/Krb5LoginModule.html</a> * <p><b>krb5.conf</b></p> * <pre> * [libdefaults] * default_realm = AD.EXAMPLE.NET * udp_preference_limit = 1 * [realms] * AD.EXAMPLE.NET = { * kdc = AD.EXAMPLE.NET * } * DEV.EXAMPLE.NET = { * kdc = DEV.EXAMPLE.NET * } * [domain_realms] * .ad.example.net = AD.EXAMPLE.NET * ad.example.net = AD.EXAMPLE.NET * .dev.example.net = DEV.EXAMPLE.NET * dev.example.net = DEV.EXAMPLE.NET * gb.dev.example.net = DEV.EXAMPLE.NET * .gb.dev.example.net = DEV.EXAMPLE.NET * </pre> * <b>login.conf</b> * <pre> *com.sun.security.jgss.login { * com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true; *}; * *com.sun.security.jgss.initiate { * com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true; *}; * *com.sun.security.jgss.accept { * com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true; *}; * </pre> * <p><b>Windows specific configuration</b></p> * <p> * The registry key <em>allowtgtsessionkey</em> should be added, and set correctly, to allow * session keys to be sent in the Kerberos Ticket-Granting Ticket. * </p> * <p> * On the Windows Server 2003 and Windows 2000 SP4, here is the required registry setting: * </p> * <pre> * HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters * Value Name: allowtgtsessionkey * Value Type: REG_DWORD * Value: 0x01 * </pre> * <p> * Here is the location of the registry setting on Windows XP SP2: * </p> * <pre> * HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\ * Value Name: allowtgtsessionkey * Value Type: REG_DWORD * Value: 0x01 * </pre> * * @since 4.1 */ public class ClientKerberosAuthentication { public static void main(String[] args) throws Exception { System.setProperty("java.security.auth.login.config", "login.conf"); System.setProperty("java.security.krb5.conf", "krb5.conf"); System.setProperty("sun.security.krb5.debug", "true"); System.setProperty("javax.security.auth.useSubjectCredsOnly","false"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { NegotiateSchemeFactory nsf = new NegotiateSchemeFactory(); // nsf.setStripPort(false); // nsf.setSpengoGenerator(new BouncySpnegoTokenGenerator()); httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf); Credentials use_jaas_creds = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; httpclient.getCredentialsProvider().setCredentials( new AuthScope(null, -1, null), use_jaas_creds); HttpUriRequest request = new HttpGet("http://kerberoshost/"); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println("----------------------------------------"); if (entity != null) { System.out.println(EntityUtils.toString(entity)); } System.out.println("----------------------------------------"); // This ensures the connection gets released back to the manager EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientKerberosAuthentication.java
Java
gpl3
6,896
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.ogt.http.examples.client; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.auth.AuthScope; import org.apache.ogt.http.auth.UsernamePasswordCredentials; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.conn.params.ConnRoutePNames; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; /** * A simple example that uses HttpClient to execute an HTTP request * over a secure connection tunneled through an authenticating proxy. */ public class ClientProxyAuthentication { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { httpclient.getCredentialsProvider().setCredentials( new AuthScope("localhost", 8080), new UsernamePasswordCredentials("username", "password")); HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https"); HttpHost proxy = new HttpHost("localhost", 8080); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); HttpGet httpget = new HttpGet("/"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("via proxy: " + proxy); System.out.println("to target: " + targetHost); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } EntityUtils.consume(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientProxyAuthentication.java
Java
gpl3
3,401
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; /** * How to send a request directly using {@link HttpClient}. * * @since 4.0 */ public class ClientExecuteDirect { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpHost target = new HttpHost("www.apache.org", 80, "http"); HttpGet req = new HttpGet("/"); System.out.println("executing request to " + target); HttpResponse rsp = httpclient.execute(target, req); HttpEntity entity = rsp.getEntity(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); Header[] headers = rsp.getAllHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); } System.out.println("----------------------------------------"); if (entity != null) { System.out.println(EntityUtils.toString(entity)); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientExecuteDirect.java
Java
gpl3
2,913
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.ogt.http.examples.client; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.auth.AuthScope; import org.apache.ogt.http.auth.UsernamePasswordCredentials; import org.apache.ogt.http.client.AuthCache; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.protocol.ClientContext; import org.apache.ogt.http.impl.auth.BasicScheme; import org.apache.ogt.http.impl.client.BasicAuthCache; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.protocol.BasicHttpContext; import org.apache.ogt.http.util.EntityUtils; /** * An example of HttpClient can be customized to authenticate * preemptively using BASIC scheme. * <b/> * Generally, preemptive authentication can be considered less * secure than a response to an authentication challenge * and therefore discouraged. */ public class ClientPreemptiveBasicAuthentication { public static void main(String[] args) throws Exception { HttpHost targetHost = new HttpHost("localhost", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("username", "password")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpGet httpget = new HttpGet("/"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("to target: " + targetHost); for (int i = 0; i < 3; i++) { HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } EntityUtils.consume(entity); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveBasicAuthentication.java
Java
gpl3
4,145
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseInterceptor; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.entity.HttpEntityWrapper; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.protocol.HttpContext; import org.apache.ogt.http.util.EntityUtils; /** * Demonstration of the use of protocol interceptors to transparently * modify properties of HTTP messages sent / received by the HTTP client. * <p/> * In this particular case HTTP client is made capable of transparent content * GZIP compression by adding two protocol interceptors: a request interceptor * that adds 'Accept-Encoding: gzip' header to all outgoing requests and * a response interceptor that automatically expands compressed response * entities by wrapping them with a uncompressing decorator class. The use of * protocol interceptors makes content compression completely transparent to * the consumer of the {@link org.apache.ogt.http.client.HttpClient HttpClient} * interface. */ public class ClientGZipContentCompression { public final static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity( new GzipDecompressingEntity(response.getEntity())); return; } } } } }); HttpGet httpget = new HttpGet("http://www.apache.org/"); // Execute HTTP request System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); System.out.println(response.getLastHeader("Content-Encoding")); System.out.println(response.getLastHeader("Content-Length")); System.out.println("----------------------------------------"); HttpEntity entity = response.getEntity(); if (entity != null) { String content = EntityUtils.toString(entity); System.out.println(content); System.out.println("----------------------------------------"); System.out.println("Uncompressed size: "+content.length()); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } static class GzipDecompressingEntity extends HttpEntityWrapper { public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } @Override public long getContentLength() { // length of ungzipped content is not known return -1; } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientGZipContentCompression.java
Java
gpl3
6,126
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import java.util.concurrent.TimeUnit; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.ogt.http.util.EntityUtils; /** * Example demonstrating how to evict expired and idle connections * from the connection pool. */ public class ClientEvictExpiredConnections { public static void main(String[] args) throws Exception { ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(); cm.setMaxTotal(100); HttpClient httpclient = new DefaultHttpClient(cm); try { // create an array of URIs to perform GETs on String[] urisToGet = { "http://jakarta.apache.org/", "http://jakarta.apache.org/commons/", "http://jakarta.apache.org/commons/httpclient/", "http://svn.apache.org/viewvc/jakarta/httpcomponents/" }; IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm); connEvictor.start(); for (int i = 0; i < urisToGet.length; i++) { String requestURI = urisToGet[i]; HttpGet req = new HttpGet(requestURI); System.out.println("executing request " + requestURI); HttpResponse rsp = httpclient.execute(req); HttpEntity entity = rsp.getEntity(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } System.out.println("----------------------------------------"); EntityUtils.consume(entity); } // Sleep 10 sec and let the connection evictor do its job Thread.sleep(20000); // Shut down the evictor thread connEvictor.shutdown(); connEvictor.join(); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } public static class IdleConnectionEvictor extends Thread { private final ClientConnectionManager connMgr; private volatile boolean shutdown; public IdleConnectionEvictor(ClientConnectionManager connMgr) { super(); this.connMgr = connMgr; } @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); // Close expired connections connMgr.closeExpiredConnections(); // Optionally, close connections // that have been idle longer than 5 sec connMgr.closeIdleConnections(5, TimeUnit.SECONDS); } } } catch (InterruptedException ex) { // terminate } } public void shutdown() { shutdown = true; synchronized (this) { notifyAll(); } } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientEvictExpiredConnections.java
Java
gpl3
4,903
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.ogt.http.examples.client; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.auth.AuthScope; import org.apache.ogt.http.auth.UsernamePasswordCredentials; import org.apache.ogt.http.client.AuthCache; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.client.protocol.ClientContext; import org.apache.ogt.http.impl.auth.DigestScheme; import org.apache.ogt.http.impl.client.BasicAuthCache; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.protocol.BasicHttpContext; import org.apache.ogt.http.util.EntityUtils; /** * An example of HttpClient can be customized to authenticate * preemptively using DIGEST scheme. * <b/> * Generally, preemptive authentication can be considered less * secure than a response to an authentication challenge * and therefore discouraged. */ public class ClientPreemptiveDigestAuthentication { public static void main(String[] args) throws Exception { HttpHost targetHost = new HttpHost("localhost", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("username", "password")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate DIGEST scheme object, initialize it and add it to the local // auth cache DigestScheme digestAuth = new DigestScheme(); // Suppose we already know the realm name digestAuth.overrideParamter("realm", "some realm"); // Suppose we already know the expected nonce value digestAuth.overrideParamter("nonce", "whatever"); authCache.put(targetHost, digestAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpGet httpget = new HttpGet("/"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("to target: " + targetHost); for (int i = 0; i < 3; i++) { HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } EntityUtils.consume(entity); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientPreemptiveDigestAuthentication.java
Java
gpl3
4,412
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.impl.client.DefaultHttpClient; /** * This example demonstrates how to abort an HTTP method before its normal completion. */ public class ClientAbortMethod { public final static void main(String[] args) throws Exception { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet("http://www.apache.org/"); System.out.println("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } System.out.println("----------------------------------------"); // Do not feel like reading the response body // Call abort on the request object httpget.abort(); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientAbortMethod.java
Java
gpl3
2,764
/* * ==================================================================== * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import java.io.File; import java.io.FileInputStream; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpPost; import org.apache.ogt.http.entity.InputStreamEntity; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; /** * Example how to use unbuffered chunk-encoded POST request. */ public class ClientChunkEncodedPost { public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); File file = new File(args[0]); InputStreamEntity reqEntity = new InputStreamEntity( new FileInputStream(file), -1); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); // It may be more appropriate to use FileEntity class in this particular // instance but we are using a more generic InputStreamEntity to demonstrate // the capability to stream out data from any arbitrary source // // FileEntity entity = new FileEntity(file, "binary/octet-stream"); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); } EntityUtils.consume(resEntity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientChunkEncodedPost.java
Java
gpl3
3,672
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.client; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.client.HttpClient; import org.apache.ogt.http.client.methods.HttpGet; import org.apache.ogt.http.conn.params.ConnRoutePNames; import org.apache.ogt.http.impl.client.DefaultHttpClient; import org.apache.ogt.http.util.EntityUtils; /** * How to send a request via proxy using {@link HttpClient}. * * @since 4.0 */ public class ClientExecuteProxy { public static void main(String[] args)throws Exception { HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); HttpHost target = new HttpHost("issues.apache.org", 443, "https"); HttpGet req = new HttpGet("/"); System.out.println("executing request to " + target + " via " + proxy); HttpResponse rsp = httpclient.execute(target, req); HttpEntity entity = rsp.getEntity(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); Header[] headers = rsp.getAllHeaders(); for (int i = 0; i<headers.length; i++) { System.out.println(headers[i]); } System.out.println("----------------------------------------"); if (entity != null) { System.out.println(EntityUtils.toString(entity)); } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/client/ClientExecuteProxy.java
Java
gpl3
3,142
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.examples.conn; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.conn.ClientConnectionManager; import org.apache.ogt.http.conn.routing.HttpRoute; import org.apache.ogt.http.conn.scheme.PlainSocketFactory; import org.apache.ogt.http.conn.scheme.Scheme; import org.apache.ogt.http.conn.scheme.SchemeRegistry; import org.apache.ogt.http.conn.scheme.SchemeSocketFactory; import org.apache.ogt.http.conn.ClientConnectionRequest; import org.apache.ogt.http.conn.ManagedClientConnection; import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.ogt.http.message.BasicHttpRequest; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.params.HttpProtocolParams; import org.apache.ogt.http.params.SyncBasicHttpParams; import org.apache.ogt.http.protocol.HttpContext; import org.apache.ogt.http.protocol.BasicHttpContext; /** * How to open a direct connection using * {@link ClientConnectionManager ClientConnectionManager}. * This exemplifies the <i>opening</i> of the connection only. * The subsequent message exchange in this example should not * be used as a template. * * @since 4.0 */ public class ManagerConnectDirect { /** * Main entry point to this example. * * @param args ignored */ public final static void main(String[] args) throws Exception { HttpHost target = new HttpHost("www.apache.org", 80, "http"); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. SchemeRegistry supportedSchemes = new SchemeRegistry(); SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", 80, sf)); // Prepare parameters. // Since this example doesn't use the full core framework, // only few parameters are actually required. HttpParams params = new SyncBasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setUseExpectContinue(params, false); ClientConnectionManager clcm = new ThreadSafeClientConnManager(supportedSchemes); HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1); req.addHeader("Host", target.getHostName()); HttpContext ctx = new BasicHttpContext(); System.out.println("preparing route to " + target); HttpRoute route = new HttpRoute (target, null, supportedSchemes.getScheme(target).isLayered()); System.out.println("requesting connection for " + route); ClientConnectionRequest connRequest = clcm.requestConnection(route, null); ManagedClientConnection conn = connRequest.getConnection(0, null); try { System.out.println("opening connection"); conn.open(route, ctx, params); System.out.println("sending request"); conn.sendRequestHeader(req); // there is no request entity conn.flush(); System.out.println("receiving response header"); HttpResponse rsp = conn.receiveResponseHeader(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); Header[] headers = rsp.getAllHeaders(); for (int i=0; i<headers.length; i++) { System.out.println(headers[i]); } System.out.println("----------------------------------------"); System.out.println("closing connection"); conn.close(); } finally { if (conn.isOpen()) { System.out.println("shutting down connection"); try { conn.shutdown(); } catch (Exception ex) { System.out.println("problem during shutdown"); ex.printStackTrace(); } } System.out.println("releasing connection"); clcm.releaseConnection(conn, -1, null); } } }
zzy157-running
OpenGPSTracker/external_sources/httpclient-4.1.1/httpclient/src/examples/org/apache/http/examples/conn/ManagerConnectDirect.java
Java
gpl3
5,487