code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.appengine.server;
import com.google.api.client.googleapis.xml.atom.GoogleAtom;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.util.List;
/**
* Generic Atom Feed.
*
* @author Yaniv Inbar
*/
public class Feed {
@Key("link")
List<Link> links;
String getNextLink() {
return Link.find(links, "next");
}
String getBatchLink() {
return Link.find(links, "http://schemas.google.com/g/2005#batch");
}
static Feed executeGet(HttpTransport transport, CalendarUrl url, Class<? extends Feed> feedClass)
throws IOException {
url.fields = GoogleAtom.getFieldsFor(feedClass);
HttpRequest request = transport.buildGetRequest();
request.url = url;
return Auth.execute(request).parseAs(feedClass);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.appengine.server;
import com.google.api.client.auth.RsaSha;
import com.google.api.client.auth.oauth.AbstractOAuthGetToken;
import com.google.api.client.auth.oauth.OAuthCredentialsResponse;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.auth.oauth.OAuthRsaSigner;
import com.google.api.client.auth.oauth.OAuthSigner;
import com.google.api.client.extensions.appengine.http.urlfetch.UrlFetchTransport;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleUtils;
import com.google.api.client.http.HttpExecuteIntercepter;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.sample.calendar.v2.appengine.server.Constants.ConstantsForHMAC;
import com.google.api.client.sample.calendar.v2.appengine.server.Constants.ConstantsForRSA;
import com.google.api.client.sample.calendar.v2.appengine.server.Constants.SignatureMethod;
import com.google.api.client.sample.calendar.v2.appengine.shared.AuthenticationException;
import com.google.api.client.xml.atom.AtomParser;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import javax.servlet.http.HttpServletRequest;
/**
* Manages OAuth authentication.
*
* @author Yaniv Inbar
*/
class Auth {
private static PrivateKey privateKey;
/** Sets up the HTTP transport. */
static HttpTransport setUpTransport() throws IOException {
HttpTransport result = newHttpTransport();
GoogleUtils.useMethodOverride(result);
GoogleHeaders headers = newHeaders(result);
headers.gdataVersion = "2";
AtomParser parser = new AtomParser();
parser.namespaceDictionary = Namespace.DICTIONARY;
result.addParser(parser);
return result;
}
/** Sets up the HTTP transport to use for Authentication. */
static HttpTransport setUpAuthTransport() throws IOException {
HttpTransport result = newHttpTransport();
newHeaders(result);
return result;
}
private static HttpTransport newHttpTransport() throws IOException {
HttpTransport result = new UrlFetchTransport();
OAuthParameters parameters = new OAuthParameters();
parameters.consumerKey = Constants.ENTER_DOMAIN;
UserCredentials userCredentials = UserCredentials.forCurrentUser();
parameters.signer = createSigner(userCredentials);
if (userCredentials != null) {
parameters.token = userCredentials.token;
}
parameters.signRequestsUsingAuthorizationHeader(result);
return result;
}
private static GoogleHeaders newHeaders(HttpTransport transport) {
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-CalendarAppEngineSample/1.0");
transport.defaultHeaders = headers;
return headers;
}
static OAuthSigner createSigner(UserCredentials cred) throws IOException {
if (Constants.SIGNATURE_METHOD == SignatureMethod.RSA) {
OAuthRsaSigner result = new OAuthRsaSigner();
result.privateKey = getPrivateKey();
return result;
}
OAuthHmacSigner result = new OAuthHmacSigner();
result.clientSharedSecret = ConstantsForHMAC.ENTER_OAUTH_CONSUMER_KEY;
if (cred != null) {
result.tokenSharedSecret = cred.tokenSecret;
}
return result;
}
private static PrivateKey getPrivateKey() throws IOException {
if (privateKey == null) {
try {
privateKey =
RsaSha.getPrivateKeyFromKeystore(
new FileInputStream(ConstantsForRSA.ENTER_PATH_TO_KEY_STORE_FILE),
ConstantsForRSA.ENTER_KEY_STORE_PASSWORD,
ConstantsForRSA.ENTER_ALIAS_FOR_PRIVATE_KEY,
ConstantsForRSA.ENTER_PRIVATE_KEY_PASSWORD);
} catch (GeneralSecurityException e) {
throw new IOException(e);
}
}
return privateKey;
}
/**
* Returns the full URL of the request including the query parameters.
*/
static String getFullURL(HttpServletRequest request) {
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null) {
buf.append('?').append(request.getQueryString());
}
return buf.toString();
}
static UserCredentials executeGetToken(
AbstractOAuthGetToken request, UserCredentials currentCredentials) throws IOException {
HttpTransport transport = Auth.setUpTransport();
request.transport = transport;
OAuthCredentialsResponse response = request.execute();
UserCredentials result = currentCredentials;
if (result == null) {
result = new UserCredentials();
result.userId = UserCredentials.getCurrentUserId();
}
result.token = response.token;
result.tokenSecret = response.tokenSecret;
result.temporary = response.callbackConfirmed != null;
return result.makePersistent();
}
static HttpResponse execute(HttpRequest request) throws IOException {
try {
return request.execute();
} catch (HttpResponseException e) {
switch (e.response.statusCode) {
case 302:
// redirect
CalendarUrl locationUrl = new CalendarUrl(e.response.headers.location);
UserCredentials credentials = UserCredentials.forCurrentUser();
credentials.gsessionid = locationUrl.gsessionid;
credentials.makePersistent();
request.url = locationUrl;
new SessionIntercepter(request.transport, locationUrl.gsessionid);
e.response.ignore(); // force the connection to close
return request.execute();
case 401:
// check for an authentication error (e.g. if user revoked token)
if (e.response.headers.authenticate != null) {
UserCredentials.deleteCurrentUserFromStore();
throw new AuthenticationException();
}
}
throw e;
}
}
/**
* See <a href="http://code.google.com/apis/calendar/faq.html#redirect_handling">How do I handle
* redirects...?</a>.
*/
static class SessionIntercepter implements HttpExecuteIntercepter {
private String gsessionid;
SessionIntercepter(HttpTransport transport, String gsessionid) {
this.gsessionid = gsessionid;
transport.removeIntercepters(SessionIntercepter.class);
transport.intercepters.add(0, this); // must be first
}
public void intercept(HttpRequest request) {
request.url.set("gsessionid", gsessionid);
}
}
static IOException newIOException(HttpResponseException e) throws IOException {
return new IOException(e.response.parseAsString());
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.appengine.server;
import com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.util.Key;
/**
* Calendar URL.
*
* @author Yaniv Inbar
*/
public class CalendarUrl extends GoogleUrl {
static final String ROOT_URL = "https://www.google.com/calendar/feeds";
@Key
String gsessionid;
CalendarUrl(String url) {
super(url);
// set to true only if you want pretty-printed JSON result for debugging
prettyprint = true;
}
static CalendarUrl forOwnCalendarsFeed() {
CalendarUrl result = new CalendarUrl(ROOT_URL);
result.pathParts.add("default");
result.pathParts.add("owncalendars");
result.pathParts.add("full");
return result;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.appengine.server;
import com.google.api.client.googleapis.xml.atom.AtomPatchRelativeToOriginalContent;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.DataUtil;
import com.google.api.client.util.Key;
import com.google.api.client.xml.atom.AtomContent;
import java.io.IOException;
import java.util.List;
/**
* Generic Atom Entry.
*
* @author Yaniv Inbar
*/
public class Entry implements Cloneable {
@Key
String summary;
@Key
String title;
@Key
String updated;
@Key("link")
List<Link> links;
@Override
protected Entry clone() {
return DataUtil.clone(this);
}
void executeDelete(HttpTransport transport) throws IOException {
HttpRequest request = transport.buildDeleteRequest();
request.setUrl(getEditLink());
Auth.execute(request).ignore();
}
Entry executeInsert(HttpTransport transport, CalendarUrl url) throws IOException {
HttpRequest request = transport.buildPostRequest();
request.url = url;
AtomContent content = new AtomContent();
content.namespaceDictionary = Namespace.DICTIONARY;
content.entry = this;
request.content = content;
return Auth.execute(request).parseAs(getClass());
}
Entry executePatchRelativeToOriginal(HttpTransport transport, Entry original) throws IOException {
HttpRequest request = transport.buildPatchRequest();
request.setUrl(getEditLink());
AtomPatchRelativeToOriginalContent content = new AtomPatchRelativeToOriginalContent();
content.namespaceDictionary = Namespace.DICTIONARY;
content.originalEntry = original;
content.patchedEntry = this;
request.content = content;
return Auth.execute(request).parseAs(getClass());
}
String getEditLink() {
return Link.find(links, "edit");
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.appengine.server;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.sample.calendar.v2.appengine.shared.GwtCalendar;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Calendar feed.
*
* @author Yaniv Inbar
*/
public class CalendarFeed extends Feed {
@Key("entry")
List<CalendarEntry> calendars = new ArrayList<CalendarEntry>();
void appendCalendars(List<GwtCalendar> result) {
for (CalendarEntry entry : calendars) {
result.add(entry.toCalendar());
}
}
static CalendarFeed executeGet(HttpTransport transport, CalendarUrl url) throws IOException {
return (CalendarFeed) Feed.executeGet(transport, url, CalendarFeed.class);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.appengine.server;
/**
* Constants.
*
* @author Yaniv Inbar
*/
class Constants {
/**
* OAuth signature method.
* <p>
* A real deployed application normally uses only one of them. However, anonymous HMAC is the only
* option when debugging on a local server.
* </p>
*/
enum SignatureMethod {
/** Sign requests using {@code "RSA-SHA1"}. */
RSA,
/** Sign requests using {@code "HMAC-SHA1"}. */
HMAC,
}
static final SignatureMethod SIGNATURE_METHOD = SignatureMethod.HMAC;
/** Domain this web application is running on or {@code "anonymous"} by default. */
static final String ENTER_DOMAIN = "anonymous";
static class ConstantsForHMAC {
/**
* OAuth Consumer Key obtained from the <a
* href="https://www.google.com/accounts/ManageDomains">Manage your domains</a> page or {@code
* "anonymous"} by default.
*/
static final String ENTER_OAUTH_CONSUMER_KEY = "anonymous";
}
static class ConstantsForRSA {
static final String ENTER_PATH_TO_KEY_STORE_FILE = "WEB-INF/calendar.jks";
static final String ENTER_KEY_STORE_PASSWORD = "calendar2store";
static final String ENTER_ALIAS_FOR_PRIVATE_KEY = "calendar";
static final String ENTER_PRIVATE_KEY_PASSWORD = "calendar2key";
}
static final String APP_NAME = "Google Calendar Data API Sample Web Client";
static final String GWT_MODULE_NAME = "calendar";
private Constants() {
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.appengine.server;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.sample.calendar.v2.appengine.client.CalendarService;
import com.google.api.client.sample.calendar.v2.appengine.shared.GwtCalendar;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Calendar GWT RPC service implementation.
*
* @author Yaniv Inbar
*/
@SuppressWarnings("serial")
public class CalendarGwtRpcSample extends RemoteServiceServlet implements CalendarService {
@Override
public List<GwtCalendar> getCalendars() throws IOException {
try {
HttpTransport transport = Auth.setUpTransport();
CalendarUrl url = CalendarUrl.forOwnCalendarsFeed();
ArrayList<GwtCalendar> result = new ArrayList<GwtCalendar>();
// iterate through all pages via next links
CalendarFeed feed = CalendarFeed.executeGet(transport, url);
feed.appendCalendars(result);
while (feed.getNextLink() != null) {
feed = CalendarFeed.executeGet(transport, new CalendarUrl(feed.getNextLink()));
feed.appendCalendars(result);
}
return result;
} catch (HttpResponseException e) {
throw Auth.newIOException(e);
}
}
@Override
public void delete(GwtCalendar calendar) throws IOException {
try {
HttpTransport transport = Auth.setUpTransport();
CalendarEntry entry = new CalendarEntry(calendar);
entry.executeDelete(transport);
} catch (HttpResponseException e) {
throw Auth.newIOException(e);
}
}
@Override
public GwtCalendar insert(GwtCalendar calendar) throws IOException {
try {
HttpTransport transport = Auth.setUpTransport();
CalendarEntry entry = new CalendarEntry(calendar);
CalendarUrl url = CalendarUrl.forOwnCalendarsFeed();
CalendarEntry responseEntry = entry.executeInsert(transport, url);
return responseEntry.toCalendar();
} catch (HttpResponseException e) {
throw Auth.newIOException(e);
}
}
@Override
public GwtCalendar update(GwtCalendar original, GwtCalendar updated) throws IOException {
try {
HttpTransport transport = Auth.setUpTransport();
CalendarEntry originalEntry = new CalendarEntry(original);
CalendarEntry updatedEntry = new CalendarEntry(updated);
CalendarEntry responseEntry =
updatedEntry.executePatchRelativeToOriginal(transport, originalEntry);
return responseEntry.toCalendar();
} catch (HttpResponseException e) {
throw Auth.newIOException(e);
}
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.appengine.server;
import com.google.api.client.auth.oauth.OAuthCallbackUrl;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken;
import com.google.api.client.http.HttpResponseException;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* HTTP servlet to process access granted from user.
*
* @author Yaniv Inbar
*/
@SuppressWarnings("serial")
public class AccessGrantedServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
try {
OAuthCallbackUrl url = new OAuthCallbackUrl(Auth.getFullURL(request));
UserCredentials temporaryCredentials = UserCredentials.forCurrentUser();
if (!url.token.equals(temporaryCredentials.token)) {
// OAuth token belongs to a different user from the logged-in user
String fullUrl = Auth.getFullURL(request);
UserService userService = UserServiceFactory.getUserService();
response.sendRedirect(userService.createLogoutURL(fullUrl));
return;
}
// gets an access OAuth token upgraded from a temporary token
GoogleOAuthGetAccessToken accessToken = new GoogleOAuthGetAccessToken();
accessToken.signer = Auth.createSigner(temporaryCredentials);
accessToken.consumerKey = Constants.ENTER_DOMAIN;
accessToken.temporaryToken = temporaryCredentials.token;
accessToken.verifier = url.verifier;
Auth.executeGetToken(accessToken, temporaryCredentials);
// redirect back to application, but clear token and verifier query parameters
url.setRawPath("/");
url.verifier = null;
url.token = null;
response.sendRedirect(url.build());
} catch (HttpResponseException e) {
Auth.newIOException(e);
}
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.discovery.appengine.client;
import com.google.api.client.sample.discovery.appengine.shared.KnownGoogleApis;
import com.google.api.client.sample.discovery.appengine.shared.MethodDetails;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import java.util.ArrayList;
/**
* @author Yaniv Inbar
*/
public class DiscoveryAppEngineSample implements EntryPoint {
ListBox apiListBox = new ListBox();
DecoratorPanel decoratorPanel = new DecoratorPanel();
FlexTable methodsTable = new FlexTable();
static final DiscoveryServiceAsync service = GWT.create(DiscoveryService.class);
public void onModuleLoad() {
VerticalPanel mainPanel = new VerticalPanel();
mainPanel.setSpacing(5);
Label title = new Label("Google Discovery API Web Client");
title.addStyleName("header");
HorizontalPanel addPanel = new HorizontalPanel();
Label label = new Label("Select a Google API:");
addPanel.add(label);
for (KnownGoogleApis api : KnownGoogleApis.values()) {
apiListBox.addItem(api.displayName, api.name());
}
addPanel.add(apiListBox);
mainPanel.add(title);
mainPanel.add(addPanel);
methodsTable.setCellPadding(3);
methodsTable.setStyleName("methodsTable");
decoratorPanel.add(methodsTable);
mainPanel.add(decoratorPanel);
mainPanel
.add(
new Anchor(
"See Source Code",
"http://samples.google-api-java-client.googlecode.com/hg/discovery-appengine-sample/instructions.html?r=default"));
RootPanel.get("main").add(mainPanel);
apiListBox.setFocus(true);
discover();
apiListBox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
discover();
}
});
}
void discover() {
String apiName = apiListBox.getValue(apiListBox.getSelectedIndex());
apiListBox.setFocus(true);
service.getMethods(apiName, new AsyncCallback<ArrayList<MethodDetails>>() {
@Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
Window.alert("ERROR: " + caught.getMessage());
}
@Override
public void onSuccess(ArrayList<MethodDetails> result) {
methodsTable.removeAllRows();
methodsTable.setText(0, 0, "method");
methodsTable.setText(0, 1, "required parameters");
methodsTable.setText(0, 2, "optional parameters");
methodsTable.getCellFormatter().addStyleName(0, 0, "methodsHeaderRow");
methodsTable.getCellFormatter().addStyleName(0, 1, "methodParametersHeaderRow");
methodsTable.getCellFormatter().addStyleName(0, 2, "methodParametersHeaderRow");
for (int i = 0; i < result.size(); i++) {
MethodDetails methodDetails = result.get(i);
methodsTable.setText(i + 1, 0, methodDetails.name);
methodsTable.setText(i + 1, 1, showParams(methodDetails.requiredParameters));
methodsTable.getCellFormatter().addStyleName(i + 1, 1, "parametersColumn");
methodsTable.setText(i + 1, 2, showParams(methodDetails.optionalParameters));
methodsTable.getCellFormatter().addStyleName(i + 1, 2, "parametersColumn");
}
}
});
}
static String showParams(ArrayList<String> params) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < params.size(); i++) {
if (i != 0) {
buf.append(", ");
}
buf.append(params.get(i));
}
return buf.toString();
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.discovery.appengine.client;
import com.google.api.client.sample.discovery.appengine.shared.MethodDetails;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.ArrayList;
/**
* @author Yaniv Inbar
*/
public interface DiscoveryServiceAsync {
void getMethods(String apiName, AsyncCallback<ArrayList<MethodDetails>> callback);
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.discovery.appengine.client;
import com.google.api.client.sample.discovery.appengine.shared.MethodDetails;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import java.io.IOException;
import java.util.ArrayList;
/**
* @author Yaniv Inbar
*/
@RemoteServiceRelativePath("discoveryService")
public interface DiscoveryService extends RemoteService {
ArrayList<MethodDetails> getMethods(String apiName) throws IOException, IllegalArgumentException;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.discovery.appengine.shared;
/**
* Details of known Google API's.
*
* @author Yaniv Inbar
*/
public enum KnownGoogleApis {
BIG_QUERY("BigQuery", "bigquery", "v1"),
DISCOVERY("Discovery", "discovery", "0.1"),
BUZZ("Google Buzz API", "buzz", "v1"),
LATITUDE("Google Latitude API", "latitude", "v1"),
MODERATOR("Google Moderator API", "moderator", "v1"),
PREDICTION("Google Prediction API", "prediction", "v1");
public final String displayName;
public final String apiName;
public final String version;
KnownGoogleApis(String displayName, String apiName, String version) {
this.displayName = displayName;
this.apiName = apiName;
this.version = version;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.discovery.appengine.shared;
import java.io.Serializable;
import java.util.ArrayList;
/**
* @author Yaniv Inbar
*/
public class MethodDetails implements Serializable, Comparable<MethodDetails> {
private static final long serialVersionUID = 1L;
public String name;
public ArrayList<String> requiredParameters = new ArrayList<String>();
public ArrayList<String> optionalParameters = new ArrayList<String>();
@Override
public int compareTo(MethodDetails o) {
if (o == this) {
return 0;
}
return name.compareTo(o.name);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.discovery.appengine.server;
import com.google.api.client.extensions.appengine.http.urlfetch.UrlFetchTransport;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.json.DiscoveryDocument.ServiceDefinition;
import com.google.api.client.googleapis.json.DiscoveryDocument.ServiceMethod;
import com.google.api.client.googleapis.json.DiscoveryDocument.ServiceParameter;
import com.google.api.client.googleapis.json.DiscoveryDocument.ServiceResource;
import com.google.api.client.googleapis.json.GoogleApi;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.sample.discovery.appengine.client.DiscoveryService;
import com.google.api.client.sample.discovery.appengine.shared.KnownGoogleApis;
import com.google.api.client.sample.discovery.appengine.shared.MethodDetails;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* @author Yaniv Inbar
*/
public class DiscoveryServiceImpl extends RemoteServiceServlet implements DiscoveryService {
private static final long serialVersionUID = 1L;
static final HashMap<String, ServiceDefinition> CACHED = Maps.newHashMap();
static HttpTransport newTransport() {
HttpTransport result = new UrlFetchTransport();
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-DiscoverySample/1.0");
result.defaultHeaders = headers;
return result;
}
@Override
public ArrayList<MethodDetails> getMethods(String apiName)
throws IOException, IllegalArgumentException {
KnownGoogleApis knownApi = KnownGoogleApis.valueOf(apiName);
ServiceDefinition def = CACHED.get(apiName);
if (def == null) {
try {
GoogleApi api = new GoogleApi();
api.name = knownApi.apiName;
api.version = knownApi.version;
api.jsonFactory = new JacksonFactory();
api.discoveryTransport = newTransport();
api.load();
def = api.serviceDefinition;
CACHED.put(apiName, def);
} catch (HttpResponseException e) {
e.response.ignore();
throw e;
}
}
ArrayList<MethodDetails> result = Lists.newArrayList();
Map<String, ServiceResource> resources = def.resources;
if (resources != null) {
for (Map.Entry<String, ServiceResource> resourceEntry : resources.entrySet()) {
String resourceName = knownApi.apiName + "." + resourceEntry.getKey();
Map<String, ServiceMethod> methods = resourceEntry.getValue().methods;
if (methods != null) {
for (Map.Entry<String, ServiceMethod> methodEntry : methods.entrySet()) {
MethodDetails details = new MethodDetails();
details.name = resourceName + "." + methodEntry.getKey();
Map<String, ServiceParameter> parameters = methodEntry.getValue().parameters;
if (parameters != null) {
for (Map.Entry<String, ServiceParameter> parameterEntry : parameters.entrySet()) {
String parameterName = parameterEntry.getKey();
if (parameterEntry.getValue().required) {
details.requiredParameters.add(parameterName);
} else {
details.optionalParameters.add(parameterName);
}
}
Collections.sort(details.requiredParameters);
Collections.sort(details.optionalParameters);
result.add(details);
}
}
}
}
}
Collections.sort(result);
return result;
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.sample.books;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.books.v1.Books;
import com.google.api.services.books.v1.Books.Volumes.List;
import com.google.api.services.books.v1.model.Volume;
import com.google.api.services.books.v1.model.VolumeSaleInfo;
import com.google.api.services.books.v1.model.VolumeVolumeInfo;
import com.google.api.services.books.v1.model.Volumes;
import java.net.URLEncoder;
import java.text.NumberFormat;
/**
* A sample application that demonstrates how Goole Books Client Library for
* Java can be used to query Google Books. It accepts queries in the command
* line, and prints the results to the console.
*
* $ java com.google.sample.books.BooksSample [--author|--isbn|--title] "<query>"
*
* Please start by reviewing the Google Books API documentation at:
* http://code.google.com/apis/books/docs/getting_started.html
*/
public class BooksSample {
// Sign up for your API Key at https://code.google.com/apis/console
// Only limited requests can be made without an API key for development.
// Production apps should use an API key to for higher production quota.
// You can also request for even higher quota, but only with an API Key.
private static final String API_KEY = null;
private static final NumberFormat CURRENCY_FORMATTER = NumberFormat.getCurrencyInstance();
private static final NumberFormat PERCENT_FORMATTER = NumberFormat.getPercentInstance();
private static void queryGoogleBooks(JsonFactory jsonFactory, String query) throws Exception {
// Set up Books client.
final Books books = new Books(new NetHttpTransport(), jsonFactory);
books.setApplicationName("Google-BooksSample/1.0");
if (API_KEY != null && API_KEY.length() > 0) {
books.accessKey = API_KEY;
}
// Set query string and filter only Google eBooks.
System.out.println("Query: [" + query + "]");
List volumesList = books.volumes.list(query);
volumesList.filter = "ebooks";
// Execute the query.
Volumes volumes = volumesList.execute();
if (volumes.totalItems == 0 || volumes.items == null) {
System.out.println("No matches found.");
return;
}
// Output results.
for (Volume volume : volumes.items) {
VolumeVolumeInfo volumeInfo = volume.volumeInfo;
VolumeSaleInfo saleInfo = volume.saleInfo;
System.out.println("==========");
// Title.
System.out.println("Title: " + volumeInfo.title);
// Author(s).
java.util.List<String> authors = volumeInfo.authors;
if (authors != null && !authors.isEmpty()) {
System.out.print("Author(s): ");
for (int i = 0; i < authors.size(); ++i) {
System.out.print(authors.get(i));
if (i < authors.size() - 1) {
System.out.print(", ");
}
}
System.out.println();
}
// Description (if any).
if (volumeInfo.description != null && volumeInfo.description.length() > 0) {
System.out.println("Description: " + volumeInfo.description);
}
// Ratings (if any).
if (volumeInfo.ratingsCount != null && volumeInfo.ratingsCount > 0) {
int fullRating = (int) Math.round(volumeInfo.averageRating.doubleValue());
System.out.print("User Rating: ");
for (int i = 0; i < fullRating; ++i) {
System.out.print("*");
}
System.out.println(" (" + volumeInfo.ratingsCount + " rating(s))");
}
// Price (if any).
if ("FOR_SALE".equals(saleInfo.saleability)) {
double save = saleInfo.listPrice.amount - saleInfo.retailPrice.amount;
if (save > 0.0) {
System.out.print("List: " + CURRENCY_FORMATTER.format(saleInfo.listPrice.amount)
+ " ");
}
System.out.print("Google eBooks Price: "
+ CURRENCY_FORMATTER.format(saleInfo.retailPrice.amount));
if (save > 0.0) {
System.out.print(" You Save: " + CURRENCY_FORMATTER.format(save) + " ("
+ PERCENT_FORMATTER.format(save / saleInfo.listPrice.amount) + ")");
}
System.out.println();
}
// Access status.
String accessViewStatus = volume.accessInfo.accessViewStatus;
String message = "Additional information about this book is available from Google eBooks at:";
if ("FULL_PUBLIC_DOMAIN".equals(accessViewStatus)) {
message = "This public domain book is available for free from Google eBooks at:";
} else if ("SAMPLE".equals(accessViewStatus)) {
message = "A preview of this book is available from Google eBooks at:";
}
System.out.println(message);
// Link to Google eBooks.
System.out.println(volumeInfo.infoLink);
}
System.out.println("==========");
System.out.println(volumes.totalItems + " total results at http://books.google.com/ebooks?q="
+ URLEncoder.encode(query, "UTF-8"));
}
public static void main(String[] args) {
JsonFactory jsonFactory = new JacksonFactory();
try {
// Verify command line parameters.
if (args.length == 0) {
System.err.println("Usage: BooksSample [--author|--isbn|--title] \"<query>\"");
System.exit(1);
}
// Parse command line parameters into a query.
// Query format: "[<author|isbn|intitle>:]<query>"
String prefix = null;
String query = "";
for (String arg : args) {
if ("--author".equals(arg)) {
prefix = "inauthor:";
} else if ("--isbn".equals(arg)) {
prefix = "isbn:";
} else if ("--title".equals(arg)) {
prefix = "intitle:";
} else if (arg.startsWith("--")) {
System.err.println("Unknown argument: " + arg);
System.exit(1);
} else {
query = arg;
}
}
if (prefix != null) {
query = prefix + query;
}
try {
queryGoogleBooks(jsonFactory, query);
// Success!
return;
} catch (HttpResponseException e) {
if (!e.response.contentType.equals(Json.CONTENT_TYPE)) {
System.err.println(e.response.parseAsString());
} else {
GoogleJsonError errorResponse = GoogleJsonError.parse(jsonFactory, e.response);
System.err.println(errorResponse.code + " Error: " + errorResponse.message);
for (ErrorInfo error : errorResponse.errors) {
System.err.println(jsonFactory.toString(error));
}
}
}
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(0);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator;
import com.google.api.client.repackaged.com.google.common.base.Preconditions;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Class that runs a Jetty server on a free port, waiting for OAuth to redirect
* to it with the one-time authorization token.
* <p>
* Mostly copied from oacurl by phopkins@google.com.
*
* @author Yaniv Inbar
*/
public class LoginCallbackServer {
private static final String CALLBACK_PATH = "/OAuthCallback";
private int port;
private Server server;
private Map<String, String> verifierMap = new HashMap<String, String>();
public void start() {
if (server != null) {
throw new IllegalStateException("Server is already started");
}
try {
port = getUnusedPort();
server = new Server(port);
for (Connector c : server.getConnectors()) {
c.setHost("localhost");
}
server.addHandler(new CallbackHandler());
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void stop() throws Exception {
if (server != null) {
server.stop();
server = null;
}
}
public String getCallbackUrl() {
Preconditions.checkArgument(port != 0, "Server is not yet started");
return "http://localhost:" + port + CALLBACK_PATH;
}
private static int getUnusedPort() throws IOException {
Socket s = new Socket();
s.bind(null);
try {
return s.getLocalPort();
} finally {
s.close();
}
}
/**
* Call that blocks until the OAuth provider redirects back here with the
* verifier token.
*
* @param requestToken request token
* @return The verifier token, or null if there was a timeout.
*/
public String waitForVerifier(String requestToken) {
synchronized (verifierMap) {
while (!verifierMap.containsKey(requestToken)) {
try {
verifierMap.wait(3000);
} catch (InterruptedException e) {
return null;
}
}
return verifierMap.remove(requestToken);
}
}
/**
* Jetty handler that takes the verifier token passed over from the OAuth
* provider and stashes it where {@link LoginCallbackServer#waitForVerifier}
* will find it.
*/
public class CallbackHandler extends AbstractHandler {
public void handle(String target, HttpServletRequest request,
HttpServletResponse response, int dispatch) throws IOException {
if (!CALLBACK_PATH.equals(target)) {
return;
}
writeLandingHtml(response);
response.flushBuffer();
((Request) request).setHandled(true);
String requestToken = request.getParameter("oauth_token");
String verifier = request.getParameter("oauth_verifier");
synchronized (verifierMap) {
verifierMap.put(requestToken, verifier);
verifierMap.notifyAll();
}
}
private void writeLandingHtml(HttpServletResponse response)
throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html");
PrintWriter doc = response.getWriter();
doc.println("<html>");
doc.println(
"<head><title>OAuth Authentication Token Recieved</title></head>");
doc.println("<body>");
doc.println("Received verifier token. Closing...");
doc.println("<script type='text/javascript'>");
// We open "" in the same window to trigger JS ownership of it, which lets
// us then close it via JS, at least in Chrome.
doc.println("window.setTimeout(function() {");
doc.println(
" window.open('', '_self', ''); window.close(); }, 1000);");
doc.println("if (window.opener) { window.opener.checkToken(); }");
doc.println("</script>");
doc.println("</body>");
doc.println("</HTML>");
doc.flush();
}
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.sample.moderator.model.Attribution;
import com.google.api.client.sample.moderator.model.Debug;
import com.google.api.client.sample.moderator.model.SeriesResource;
import com.google.api.client.sample.moderator.model.SubmissionResource;
import com.google.api.client.sample.moderator.model.TopicResource;
import com.google.api.client.sample.moderator.model.VoteResource;
import java.io.IOException;
/**
* @author Yaniv Inbar
*/
public class ModeratorSample {
public static void main(String[] args) {
Debug.enableLogging();
HttpTransport transport = setUpTransport();
try {
try {
Auth.authorize(transport);
SeriesResource series = createSeries(transport);
TopicResource topic = createTopic(transport, series);
SubmissionResource submission = createSubmission(transport, topic);
VoteResource vote = createVote(transport, submission);
updateVote(transport, vote);
Auth.revoke();
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
throw e;
}
} catch (Throwable t) {
t.printStackTrace();
Auth.revoke();
System.exit(1);
}
}
private static HttpTransport setUpTransport() {
HttpTransport transport = GoogleTransport.create();
GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders;
headers.setApplicationName("Google-ModeratorSample/1.0");
transport.addParser(new JsonCParser());
return transport;
}
private static SeriesResource createSeries(HttpTransport transport)
throws IOException {
SeriesResource resource = new SeriesResource();
resource.description =
"Share and rank tips for eating healthily on the cheaps!";
resource.name = "Eating Healthy & Cheap";
SeriesResource result = resource.executeInsert(transport);
System.out.println(result);
return result;
}
private static TopicResource createTopic(
HttpTransport transport, SeriesResource series) throws IOException {
TopicResource topic = new TopicResource();
topic.description = "Share your ideas on eating healthy!";
topic.name = "Ideas";
topic.presenter = "liz";
TopicResource result = topic.executeInsert(transport, series.id.seriesId);
System.out.println(result);
return result;
}
private static SubmissionResource createSubmission(
HttpTransport transport, TopicResource topic) throws IOException {
SubmissionResource submission = new SubmissionResource();
submission.attachmentUrl = "http://www.youtube.com/watch?v=1a1wyc5Xxpg";
submission.text = "Charlie Ayers @ Google";
Attribution attribution = new Attribution();
attribution.displayName = "Bashan";
attribution.location = "Bainbridge Island, WA";
SubmissionResource result = submission.executeInsert(
transport, topic.id.seriesId, topic.id.topicId);
System.out.println(result);
return result;
}
private static VoteResource createVote(
HttpTransport transport, SubmissionResource submission)
throws IOException {
VoteResource vote = new VoteResource();
vote.vote = "PLUS";
VoteResource result = vote.executeInsert(
transport, submission.id.seriesId, submission.id.submissionId);
System.out.println(result);
return result;
}
private static VoteResource updateVote(
HttpTransport transport, VoteResource vote) throws IOException {
vote.vote = "MINUS";
VoteResource result = vote.executeUpdate(transport);
System.out.println(result);
return result;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator;
import com.google.api.client.auth.oauth.OAuthCredentialsResponse;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthAuthorizeTemporaryTokenUrl;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken;
import com.google.api.client.http.HttpTransport;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.net.URI;
/**
* Implements OAuth authentication.
*
* @author Yaniv Inbar
*/
public class Auth {
private static final String APP_NAME = "Google Moderator API Java Client";
private static OAuthHmacSigner signer;
private static OAuthCredentialsResponse credentials;
static void authorize(HttpTransport transport) throws Exception {
// callback server
LoginCallbackServer callbackServer = null;
String verifier = null;
String tempToken = null;
try {
callbackServer = new LoginCallbackServer();
callbackServer.start();
// temporary token
GoogleOAuthGetTemporaryToken temporaryToken =
new GoogleOAuthGetTemporaryToken();
signer = new OAuthHmacSigner();
signer.clientSharedSecret = "anonymous";
temporaryToken.signer = signer;
temporaryToken.consumerKey = "anonymous";
temporaryToken.scope = "https://www.googleapis.com/auth/moderator";
temporaryToken.displayName = APP_NAME;
temporaryToken.callback = callbackServer.getCallbackUrl();
OAuthCredentialsResponse tempCredentials = temporaryToken.execute();
signer.tokenSharedSecret = tempCredentials.tokenSecret;
// authorization URL
GoogleOAuthAuthorizeTemporaryTokenUrl authorizeUrl =
new GoogleOAuthAuthorizeTemporaryTokenUrl();
authorizeUrl.temporaryToken = tempToken = tempCredentials.token;
String authorizationUrl = authorizeUrl.build();
// launch in browser
boolean browsed = false;
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Action.BROWSE)) {
desktop.browse(URI.create(authorizationUrl));
browsed = true;
}
}
if (!browsed) {
String browser = "google-chrome";
Runtime.getRuntime().exec(new String[] {browser, authorizationUrl});
}
verifier = callbackServer.waitForVerifier(tempToken);
} finally {
if (callbackServer != null) {
callbackServer.stop();
}
}
GoogleOAuthGetAccessToken accessToken = new GoogleOAuthGetAccessToken();
accessToken.temporaryToken = tempToken;
accessToken.signer = signer;
accessToken.consumerKey = "anonymous";
accessToken.verifier = verifier;
credentials = accessToken.execute();
signer.tokenSharedSecret = credentials.tokenSecret;
createOAuthParameters().signRequestsUsingAuthorizationHeader(transport);
}
static void revoke() {
if (credentials != null) {
try {
GoogleOAuthGetAccessToken.revokeAccessToken(createOAuthParameters());
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
private static OAuthParameters createOAuthParameters() {
OAuthParameters authorizer = new OAuthParameters();
authorizer.consumerKey = "anonymous";
authorizer.signer = signer;
authorizer.token = credentials.token;
return authorizer;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.googleapis.json.JsonCContent;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class Resource extends GenericJson {
@Key
public Id id;
JsonCContent toContent() {
JsonCContent content = new JsonCContent();
content.data = this;
return content;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class Attribution extends GenericJson {
@Key
public String displayName;
@Key
public String location;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class TopicResource extends Resource {
@Key
public String name;
@Key
public String description;
@Key
public String presenter;
@Key
public Counters counters;
@Key
public List<SubmissionResource> submissions;
/**
* @param url URL built using {@link ModeratorUrl#forTopics(String)}
*/
public static List<TopicResource> executeList(
HttpTransport transport, ModeratorUrl url) throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = url;
return request.execute().parseAs(TopicList.class).items;
}
public static TopicResource executeGet(
HttpTransport transport, String seriesId, String topicId)
throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = ModeratorUrl.forTopic(seriesId, topicId);
return request.execute().parseAs(TopicResource.class);
}
public TopicResource executeInsert(HttpTransport transport, String seriesId)
throws IOException {
HttpRequest request = transport.buildPostRequest();
request.content = toContent();
request.url = ModeratorUrl.forTopics(seriesId);
return request.execute().parseAs(TopicResource.class);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class Id {
@Key
public String seriesId;
@Key
public String topicId;
@Key
public String submissionId;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.util.Key;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class TopicList {
@Key
public List<TopicResource> items = new ArrayList<TopicResource>();
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.util.Key;
/**
* Moderator URL builder.
*
* @author Yaniv Inbar
*/
public final class ModeratorUrl extends GoogleUrl {
@Key("start-index")
public Integer startIndex;
@Key("max-results")
public Integer maxResults;
@Key
public String sort;
@Key
public Boolean hasAttachedVideo;
@Key
public String author;
@Key
public String q;
/** Constructs a new Moderator URL from the given encoded URI. */
public ModeratorUrl(String encodedUrl) {
super(encodedUrl);
if (Debug.ENABLED) {
prettyprint = true;
}
}
public static ModeratorUrl forSeries() {
return new ModeratorUrl("https://www.googleapis.com/moderator/v1/series");
}
public static ModeratorUrl forSeries(String seriesId) {
ModeratorUrl result = forSeries();
result.pathParts.add(seriesId);
return result;
}
public static ModeratorUrl forTopics(String seriesId) {
ModeratorUrl result = forSeries(seriesId);
result.pathParts.add("topics");
return result;
}
public static ModeratorUrl forTopic(String seriesId, String topicId) {
ModeratorUrl result = forTopics(seriesId);
result.pathParts.add(topicId);
return result;
}
public static ModeratorUrl forSubmissions(String seriesId) {
ModeratorUrl result = forSeries(seriesId);
result.pathParts.add("submissions");
return result;
}
public static ModeratorUrl forSubmissions(String seriesId, String topicId) {
ModeratorUrl result = forTopic(seriesId, topicId);
result.pathParts.add("submissions");
return result;
}
public static ModeratorUrl forSubmission(
String seriesId, String submissionId) {
ModeratorUrl result = forSubmissions(seriesId);
result.pathParts.add(submissionId);
return result;
}
public static ModeratorUrl forMyVotes(String seriesId) {
ModeratorUrl result = forSeries(seriesId);
result.pathParts.add("votes");
result.pathParts.add("@me");
return result;
}
public static ModeratorUrl forMyVote(
String seriesId, String submissionId) {
ModeratorUrl result = forSubmission(seriesId, submissionId);
result.pathParts.add("votes");
result.pathParts.add("@me");
return result;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.Key;
import java.io.IOException;
/**
* @author Yaniv Inbar
*/
public class SeriesResource extends Resource {
@Key
public String name;
@Key
public String description;
@Key
public Integer numTopics;
@Key
public Counters counters;
@Key
public Boolean videoSubmissionAllowed;
public static SeriesResource executeGet(
HttpTransport transport, String seriesId) throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = ModeratorUrl.forSeries(seriesId);
return request.execute().parseAs(SeriesResource.class);
}
public SeriesResource executeInsert(HttpTransport transport)
throws IOException {
HttpRequest request = transport.buildPostRequest();
request.content = toContent();
request.url = ModeratorUrl.forSeries();
return request.execute().parseAs(SeriesResource.class);
}
public SeriesResource executeUpdate(HttpTransport transport)
throws IOException {
HttpRequest request = transport.buildPutRequest();
request.content = toContent();
request.url = ModeratorUrl.forSeries(id.seriesId);
return request.execute().parseAs(SeriesResource.class);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* @author Yaniv Inbar
*/
public class Debug {
public static final boolean ENABLED = false;
public static void enableLogging() {
if (ENABLED) {
Logger logger = Logger.getLogger("com.google.api.client");
logger.setLevel(Level.CONFIG);
logger.addHandler(new Handler() {
@Override
public void close() throws SecurityException {
}
@Override
public void flush() {
}
@Override
public void publish(LogRecord record) {
// default ConsoleHandler will take care of >= INFO
if (record.getLevel().intValue() < Level.INFO.intValue()) {
System.out.println(record.getMessage());
}
}
});
}
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class Counters {
@Key
public int plusVotes;
@Key
public int minusVotes;
@Key
public int noneVotes;
@Key
public int users;
@Key
public int submissions;
@Key
public int videoSubmissions;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.util.Key;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class VoteList {
@Key
public List<VoteResource> items = new ArrayList<VoteResource>();
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class SubmissionResource extends Resource {
@Key
public String text;
@Key
public Counters counters;
@Key
public Attribution attribution;
@Key
public Long created;
@Key
public String attachmentUrl;
/**
* @param url URL built using {@link ModeratorUrl#forSubmissions(String)} or
* {@link ModeratorUrl#forSubmissions(String, String)}.
*/
public static List<SubmissionResource> executeList(
HttpTransport transport, ModeratorUrl url) throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = url;
return request.execute().parseAs(SubmissionList.class).items;
}
public static SubmissionResource executeGet(
HttpTransport transport, String seriesId, String submissionId)
throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = ModeratorUrl.forSubmission(seriesId, submissionId);
return request.execute().parseAs(SubmissionResource.class);
}
public SubmissionResource executeInsert(
HttpTransport transport, String seriesId, String topicId)
throws IOException {
HttpRequest request = transport.buildPostRequest();
request.content = toContent();
request.url = ModeratorUrl.forSubmissions(seriesId, topicId);
return request.execute().parseAs(SubmissionResource.class);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class VoteResource extends Resource {
@Key
public String vote;
@Key
public String flag;
/** @param url URL built using {@link ModeratorUrl#forMyVotes(String)}. */
public static List<VoteResource> executeList(
HttpTransport transport, ModeratorUrl url) throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = url;
return request.execute().parseAs(VoteList.class).items;
}
public static VoteResource executeGet(
HttpTransport transport, String seriesId, String submissionId)
throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = ModeratorUrl.forMyVote(seriesId, submissionId);
return request.execute().parseAs(VoteResource.class);
}
public VoteResource executeInsert(
HttpTransport transport, String seriesId, String submissionId)
throws IOException {
HttpRequest request = transport.buildPostRequest();
request.content = toContent();
request.url = ModeratorUrl.forMyVote(seriesId, submissionId);
return request.execute().parseAs(VoteResource.class);
}
public VoteResource executeUpdate(HttpTransport transport)
throws IOException {
HttpRequest request = transport.buildPutRequest();
// hack around moderator bug
Id id = this.id;
this.id = null;
request.content = toContent();
request.url = ModeratorUrl.forMyVote(id.seriesId, id.submissionId);
return request.execute().parseAs(VoteResource.class);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.moderator.model;
import com.google.api.client.util.Key;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class SubmissionList {
@Key
public List<SubmissionResource> items = new ArrayList<SubmissionResource>();
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2;
import com.google.api.client.sample.calendar.v2.model.Entry;
import com.google.api.client.sample.calendar.v2.model.EventEntry;
import com.google.api.client.sample.calendar.v2.model.Feed;
/**
* @author Yaniv Inbar
*/
public class View {
static void header(String name) {
System.out.println();
System.out.println("============== " + name + " ==============");
System.out.println();
}
static void display(Feed feed) {
for (Entry entry : feed.getEntries()) {
System.out.println();
System.out.println("-----------------------------------------------");
display(entry);
}
}
static void display(Entry entry) {
System.out.println("Title: " + entry.title);
System.out.println("Updated: " + entry.updated);
if (entry.summary != null) {
System.out.println("Summary: " + entry.summary);
}
if (entry instanceof EventEntry) {
EventEntry event = (EventEntry) entry;
if (event.when != null) {
if (event.when.startTime != null) {
System.out.println("Start Time: " + event.when.startTime);
}
if (event.when.endTime != null) {
System.out.println("End Time: " + event.when.startTime);
}
}
}
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2;
/**
* @author Yaniv Inbar
*/
public class ClientCredentials {
/**
* OAuth Consumer Key obtained from the <a
* href="https://www.google.com/accounts/ManageDomains">Manage your domains</a> page or {@code
* anonymous} by default.
*/
static final String ENTER_OAUTH_CONSUMER_KEY = "anonymous";
/**
* OAuth Consumer Secret obtained from the <a
* href="https://www.google.com/accounts/ManageDomains">Manage your domains</a> page or {@code
* anonymous} by default.
*/
static final String ENTER_OAUTH_CONSUMER_SECRET = "anonymous";
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.sample.calendar.v2.model.BatchOperation;
import com.google.api.client.sample.calendar.v2.model.BatchStatus;
import com.google.api.client.sample.calendar.v2.model.CalendarClient;
import com.google.api.client.sample.calendar.v2.model.CalendarEntry;
import com.google.api.client.sample.calendar.v2.model.CalendarFeed;
import com.google.api.client.sample.calendar.v2.model.CalendarUrl;
import com.google.api.client.sample.calendar.v2.model.EventEntry;
import com.google.api.client.sample.calendar.v2.model.EventFeed;
import com.google.api.client.sample.calendar.v2.model.Util;
import com.google.api.client.sample.calendar.v2.model.When;
import com.google.api.client.util.DateTime;
import java.io.IOException;
import java.util.Date;
/**
* @author Yaniv Inbar
*/
public class CalendarSample {
public static void main(String[] args) {
Util.enableLogging();
CalendarClient client = new CalendarClient(
ClientCredentials.ENTER_OAUTH_CONSUMER_KEY, ClientCredentials.ENTER_OAUTH_CONSUMER_SECRET);
try {
try {
client.authorize();
showCalendars(client);
CalendarEntry calendar = addCalendar(client);
calendar = updateCalendar(client, calendar);
addEvent(client, calendar);
batchAddEvents(client, calendar);
showEvents(client, calendar);
deleteCalendar(client, calendar);
shutdown(client);
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
throw e;
}
} catch (Throwable t) {
t.printStackTrace();
shutdown(client);
System.exit(1);
}
}
private static void shutdown(CalendarClient client) {
try {
client.shutdown();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void showCalendars(CalendarClient client) throws IOException {
View.header("Show Calendars");
CalendarUrl url = CalendarUrl.forAllCalendarsFeed();
CalendarFeed feed = client.executeGetCalendarFeed(url);
View.display(feed);
}
private static CalendarEntry addCalendar(CalendarClient client) throws IOException {
View.header("Add Calendar");
CalendarUrl url = CalendarUrl.forOwnCalendarsFeed();
CalendarEntry entry = new CalendarEntry();
entry.title = "Calendar for Testing";
CalendarEntry result = client.executeInsertCalendar(entry, url);
View.display(result);
return result;
}
public static CalendarEntry updateCalendar(CalendarClient client, CalendarEntry calendar)
throws IOException {
View.header("Update Calendar");
CalendarEntry original = calendar.clone();
calendar.title = "Updated Calendar for Testing";
CalendarEntry result = client.executePatchCalendarRelativeToOriginal(calendar, original);
View.display(result);
return result;
}
private static void addEvent(CalendarClient client, CalendarEntry calendar) throws IOException {
View.header("Add Event");
CalendarUrl url = new CalendarUrl(calendar.getEventFeedLink());
EventEntry event = newEvent();
EventEntry result = client.executeInsertEvent(event, url);
View.display(result);
}
private static EventEntry newEvent() {
EventEntry event = new EventEntry();
event.title = "New Event";
When when = new When();
when.startTime = new DateTime(new Date());
event.when = when;
return event;
}
private static void batchAddEvents(CalendarClient client, CalendarEntry calendar)
throws IOException {
View.header("Batch Add Events");
EventFeed feed = new EventFeed();
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
EventEntry event = newEvent();
event.batchId = Integer.toString(i);
event.batchOperation = BatchOperation.INSERT;
feed.events.add(event);
}
EventFeed result = client.executeBatchEventFeed(feed, calendar);
for (EventEntry event : result.events) {
BatchStatus batchStatus = event.batchStatus;
if (batchStatus != null && !HttpResponse.isSuccessStatusCode(batchStatus.code)) {
System.err.println("Error posting event: " + batchStatus.reason);
}
}
View.display(result);
}
private static void showEvents(CalendarClient client, CalendarEntry calendar) throws IOException {
View.header("Show Events");
CalendarUrl url = new CalendarUrl(calendar.getEventFeedLink());
EventFeed feed = client.executeGetEventFeed(url);
View.display(feed);
}
public static void deleteCalendar(CalendarClient client, CalendarEntry calendar)
throws IOException {
View.header("Delete Calendar");
client.executeDelete(calendar);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class EventEntry extends Entry {
@Key("gd:when")
public When when;
@Key("batch:id")
public String batchId;
@Key("batch:status")
public BatchStatus batchStatus;
@Key("batch:operation")
public BatchOperation batchOperation;
@Override
public EventEntry clone() {
return (EventEntry) super.clone();
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.common.base.Preconditions;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Class that runs a Jetty server on a free port, waiting for OAuth to redirect
* to it with the one-time authorization token.
* <p>
* Mostly copied from oacurl by phopkins@google.com.
*
* @author Yaniv Inbar
*/
public class LoginCallbackServer {
private static final String CALLBACK_PATH = "/OAuthCallback";
private int port;
private Server server;
private Map<String, String> verifierMap = new HashMap<String, String>();
public void start() {
if (server != null) {
throw new IllegalStateException("Server is already started");
}
try {
port = getUnusedPort();
server = new Server(port);
for (Connector c : server.getConnectors()) {
c.setHost("localhost");
}
server.addHandler(new CallbackHandler());
server.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void stop() throws Exception {
if (server != null) {
server.stop();
server = null;
}
}
public String getCallbackUrl() {
Preconditions.checkArgument(port != 0, "Server is not yet started");
return "http://localhost:" + port + CALLBACK_PATH;
}
private static int getUnusedPort() throws IOException {
Socket s = new Socket();
s.bind(null);
try {
return s.getLocalPort();
} finally {
s.close();
}
}
/**
* Call that blocks until the OAuth provider redirects back here with the
* verifier token.
*
* @param requestToken request token
* @return The verifier token, or null if there was a timeout.
*/
public String waitForVerifier(String requestToken) {
synchronized (verifierMap) {
while (!verifierMap.containsKey(requestToken)) {
try {
verifierMap.wait(3000);
} catch (InterruptedException e) {
return null;
}
}
return verifierMap.remove(requestToken);
}
}
/**
* Jetty handler that takes the verifier token passed over from the OAuth
* provider and stashes it where {@link LoginCallbackServer#waitForVerifier}
* will find it.
*/
public class CallbackHandler extends AbstractHandler {
public void handle(String target, HttpServletRequest request,
HttpServletResponse response, int dispatch) throws IOException {
if (!CALLBACK_PATH.equals(target)) {
return;
}
writeLandingHtml(response);
response.flushBuffer();
((Request) request).setHandled(true);
String requestToken = request.getParameter("oauth_token");
String verifier = request.getParameter("oauth_verifier");
synchronized (verifierMap) {
verifierMap.put(requestToken, verifier);
verifierMap.notifyAll();
}
}
private void writeLandingHtml(HttpServletResponse response)
throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/html");
PrintWriter doc = response.getWriter();
doc.println("<html>");
doc.println(
"<head><title>OAuth Authentication Token Recieved</title></head>");
doc.println("<body>");
doc.println("Received verifier token. Closing...");
doc.println("<script type='text/javascript'>");
// We open "" in the same window to trigger JS ownership of it, which lets
// us then close it via JS, at least in Chrome.
doc.println("window.setTimeout(function() {");
doc.println(
" window.open('', '_self', ''); window.close(); }, 1000);");
doc.println("if (window.opener) { window.opener.checkToken(); }");
doc.println("</script>");
doc.println("</body>");
doc.println("</HTML>");
doc.flush();
}
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
/**
* @author Yaniv Inbar
*/
public class CalendarEntry extends Entry {
public String getEventFeedLink() {
return Link.find(links, "http://schemas.google.com/gCal/2005#eventFeed");
}
@Override
public CalendarEntry clone() {
return (CalendarEntry) super.clone();
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.util.Key;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class Link {
@Key("@href")
public String href;
@Key("@rel")
public String rel;
public static String find(List<Link> links, String rel) {
if (links != null) {
for (Link link : links) {
if (rel.equals(link.rel)) {
return link.href;
}
}
}
return null;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.util.Key;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class EventFeed extends Feed {
@Key("entry")
public List<EventEntry> events = new ArrayList<EventEntry>();
@Override
public List<EventEntry> getEntries() {
return events;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* @author Yaniv Inbar
*/
public class Util {
public static final boolean DEBUG = true;
public static void enableLogging() {
if (DEBUG) {
Logger logger = Logger.getLogger("com.google.api.client");
logger.setLevel(Level.CONFIG);
logger.addHandler(new Handler() {
@Override
public void close() throws SecurityException {
}
@Override
public void flush() {
}
@Override
public void publish(LogRecord record) {
// default ConsoleHandler will take care of >= INFO
if (record.getLevel().intValue() < Level.INFO.intValue()) {
System.out.println(record.getMessage());
}
}
});
}
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class BatchOperation {
public static final BatchOperation INSERT = BatchOperation.of("insert");
public static final BatchOperation QUERY = BatchOperation.of("query");
public static final BatchOperation UPDATE = BatchOperation.of("update");
public static final BatchOperation DELETE = BatchOperation.of("delete");
@Key("@type")
public String type;
public BatchOperation() {
}
public static BatchOperation of(String type) {
BatchOperation result = new BatchOperation();
result.type = type;
return result;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.util.Key;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public abstract class Feed {
@Key("link")
public List<Link> links;
public String getBatchLink() {
return Link.find(links, "http://schemas.google.com/g/2005#batch");
}
public abstract List<? extends Entry> getEntries();
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.auth.oauth.OAuthCredentialsResponse;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthAuthorizeTemporaryTokenUrl;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetAccessToken;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken;
import com.google.api.client.http.HttpTransport;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.net.URI;
/**
* Implements OAuth authentication.
*
* @author Yaniv Inbar
*/
public class Auth {
private static final String APP_NAME = "Google Calendar Data API Java Client Sample";
private static OAuthHmacSigner signer;
private static OAuthCredentialsResponse credentials;
static OAuthParameters authorize(
HttpTransport transport, String consumerKey, String consumerSecret) throws Exception {
// callback server
LoginCallbackServer callbackServer = null;
String verifier = null;
String tempToken = null;
try {
callbackServer = new LoginCallbackServer();
callbackServer.start();
// temporary token
GoogleOAuthGetTemporaryToken temporaryToken = new GoogleOAuthGetTemporaryToken();
temporaryToken.transport = transport;
signer = new OAuthHmacSigner();
signer.clientSharedSecret = consumerSecret;
temporaryToken.signer = signer;
temporaryToken.consumerKey = consumerKey;
temporaryToken.scope = CalendarUrl.ROOT_URL;
temporaryToken.displayName = APP_NAME;
temporaryToken.callback = callbackServer.getCallbackUrl();
OAuthCredentialsResponse tempCredentials = temporaryToken.execute();
signer.tokenSharedSecret = tempCredentials.tokenSecret;
// authorization URL
GoogleOAuthAuthorizeTemporaryTokenUrl authorizeUrl =
new GoogleOAuthAuthorizeTemporaryTokenUrl();
authorizeUrl.temporaryToken = tempToken = tempCredentials.token;
String authorizationUrl = authorizeUrl.build();
// launch in browser
boolean browsed = false;
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Action.BROWSE)) {
desktop.browse(URI.create(authorizationUrl));
browsed = true;
}
}
if (!browsed) {
String browser = "google-chrome";
Runtime.getRuntime().exec(new String[] {browser, authorizationUrl});
}
verifier = callbackServer.waitForVerifier(tempToken);
} finally {
if (callbackServer != null) {
callbackServer.stop();
}
}
GoogleOAuthGetAccessToken accessToken = new GoogleOAuthGetAccessToken();
accessToken.transport = transport;
accessToken.temporaryToken = tempToken;
accessToken.signer = signer;
accessToken.consumerKey = consumerKey;
accessToken.verifier = verifier;
credentials = accessToken.execute();
signer.tokenSharedSecret = credentials.tokenSecret;
return createOAuthParameters(consumerKey);
}
static void revoke(HttpTransport transport, String consumerKey) {
if (credentials != null) {
try {
GoogleOAuthGetAccessToken.revokeAccessToken(transport, createOAuthParameters(consumerKey));
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
private static OAuthParameters createOAuthParameters(String consumerKey) {
OAuthParameters authorizer = new OAuthParameters();
authorizer.consumerKey = consumerKey;
authorizer.signer = signer;
authorizer.token = credentials.token;
return authorizer;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class CalendarUrl extends GoogleUrl {
public static final String ROOT_URL = "https://www.google.com/calendar/feeds";
@Key("max-results")
public Integer maxResults;
public CalendarUrl(String url) {
super(url);
if (Util.DEBUG) {
this.prettyprint = true;
}
}
private static CalendarUrl forRoot() {
return new CalendarUrl(ROOT_URL);
}
public static CalendarUrl forCalendarMetafeed() {
CalendarUrl result = forRoot();
result.pathParts.add("default");
return result;
}
public static CalendarUrl forAllCalendarsFeed() {
CalendarUrl result = forCalendarMetafeed();
result.pathParts.add("allcalendars");
result.pathParts.add("full");
return result;
}
public static CalendarUrl forOwnCalendarsFeed() {
CalendarUrl result = forCalendarMetafeed();
result.pathParts.add("owncalendars");
result.pathParts.add("full");
return result;
}
public static CalendarUrl forEventFeed(
String userId, String visibility, String projection) {
CalendarUrl result = forRoot();
result.pathParts.add(userId);
result.pathParts.add(visibility);
result.pathParts.add(projection);
return result;
}
public static CalendarUrl forDefaultPrivateFullEventFeed() {
return forEventFeed("default", "private", "full");
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.util.Data;
import com.google.api.client.util.Key;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class Entry implements Cloneable {
@Key
public String summary;
@Key
public String title;
@Key
public String updated;
@Key("link")
public List<Link> links;
@Override
protected Entry clone() {
try {
@SuppressWarnings("unchecked")
Entry result = (Entry) super.clone();
Data.deepCopy(this, result);
return result;
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
String getEditLink() {
return Link.find(links, "edit");
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class BatchStatus {
@Key("@code")
public int code;
@Key("text()")
public String content;
@Key("@content-type")
public String contentType;
@Key("@reason")
public String reason;
public BatchStatus() {
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class When {
@Key("@startTime")
public DateTime startTime;
@Key("@endTime")
public DateTime endTime;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.util.Key;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class CalendarFeed extends Feed {
@Key("entry")
public List<CalendarEntry> calendars = new ArrayList<CalendarEntry>();
@Override
public List<CalendarEntry> getEntries() {
return calendars;
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.calendar.v2.model;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.googleapis.MethodOverride;
import com.google.api.client.googleapis.xml.atom.AtomPatchRelativeToOriginalContent;
import com.google.api.client.googleapis.xml.atom.GoogleAtom;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.xml.atom.AtomContent;
import com.google.api.client.http.xml.atom.AtomFeedContent;
import com.google.api.client.http.xml.atom.AtomParser;
import com.google.api.client.xml.XmlNamespaceDictionary;
import java.io.IOException;
/**
* @author Yaniv Inbar
*/
public class CalendarClient {
static final XmlNamespaceDictionary DICTIONARY =
new XmlNamespaceDictionary().set("", "http://www.w3.org/2005/Atom").set(
"batch", "http://schemas.google.com/gdata/batch").set(
"gd", "http://schemas.google.com/g/2005");
private final HttpTransport transport = new NetHttpTransport();
private HttpRequestFactory requestFactory;
private final String consumerKey;
private final String consumerSecret;
public CalendarClient(String consumerKey, String consumerSecret) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
}
public void authorize() throws Exception {
final OAuthParameters oauthParameters =
Auth.authorize(transport, consumerKey, consumerSecret); // OAuth
final MethodOverride override = new MethodOverride(); // needed for PATCH
requestFactory = transport.createRequestFactory(new HttpRequestInitializer() {
String gsessionid;
@Override
public void initialize(HttpRequest request) {
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-CalendarSample/1.0");
headers.gdataVersion = "2";
request.headers = headers;
AtomParser parser = new AtomParser();
parser.namespaceDictionary = DICTIONARY;
request.addParser(parser);
request.interceptor = new HttpExecuteInterceptor() {
@Override
public void intercept(HttpRequest request) throws IOException {
request.url.set("gsessionid", gsessionid);
override.intercept(request);
oauthParameters.intercept(request);
}
};
request.unsuccessfulResponseHandler = new HttpUnsuccessfulResponseHandler() {
@Override
public boolean handleResponse(
HttpRequest request, HttpResponse response, boolean retrySupported) {
if (response.statusCode == 302) {
GoogleUrl url = new GoogleUrl(response.headers.location);
gsessionid = (String) url.getFirst("gsessionid");
return true;
}
return false;
}
};
}
});
}
public void shutdown() throws IOException {
transport.shutdown();
Auth.revoke(transport, consumerKey);
}
public void executeDelete(Entry entry) throws IOException {
HttpRequest request = requestFactory.buildDeleteRequest(new GenericUrl(entry.getEditLink()));
request.execute().ignore();
}
Entry executeInsert(Entry entry, CalendarUrl url) throws IOException {
AtomContent content = new AtomContent();
content.namespaceDictionary = DICTIONARY;
content.entry = entry;
HttpRequest request = requestFactory.buildPostRequest(url, content);
return request.execute().parseAs(entry.getClass());
}
Entry executePatchRelativeToOriginal(Entry updated, Entry original) throws IOException {
AtomPatchRelativeToOriginalContent content = new AtomPatchRelativeToOriginalContent();
content.namespaceDictionary = DICTIONARY;
content.originalEntry = original;
content.patchedEntry = updated;
HttpRequest request =
requestFactory.buildPatchRequest(new GenericUrl(updated.getEditLink()), content);
return request.execute().parseAs(updated.getClass());
}
<F extends Feed> F executeGetFeed(CalendarUrl url, Class<F> feedClass) throws IOException {
url.fields = GoogleAtom.getFieldsFor(feedClass);
HttpRequest request = requestFactory.buildGetRequest(url);
return request.execute().parseAs(feedClass);
}
public EventFeed executeGetEventFeed(CalendarUrl url) throws IOException {
return executeGetFeed(url, EventFeed.class);
}
public EventFeed executeBatchEventFeed(EventFeed eventFeed, CalendarEntry calendar)
throws IOException {
// batch link
CalendarUrl eventFeedUrl = new CalendarUrl(calendar.getEventFeedLink());
eventFeedUrl.maxResults = 0;
CalendarUrl url = new CalendarUrl(executeGetEventFeed(eventFeedUrl).getBatchLink());
AtomFeedContent content = new AtomFeedContent();
content.namespaceDictionary = DICTIONARY;
content.feed = eventFeed;
// execute request
HttpRequest request = requestFactory.buildPostRequest(url, content);
return request.execute().parseAs(EventFeed.class);
}
public CalendarEntry executeInsertCalendar(CalendarEntry entry, CalendarUrl url)
throws IOException {
return (CalendarEntry) executeInsert(entry, url);
}
public CalendarEntry executePatchCalendarRelativeToOriginal(
CalendarEntry updated, CalendarEntry original) throws IOException {
return (CalendarEntry) executePatchRelativeToOriginal(updated, original);
}
public CalendarFeed executeGetCalendarFeed(CalendarUrl url) throws IOException {
return executeGetFeed(url, CalendarFeed.class);
}
public EventEntry executeInsertEvent(EventEntry event, CalendarUrl url) throws IOException {
return (EventEntry) executeInsert(event, url);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.bigquery;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.sample.bigquery.model.BigQueryUrl;
import com.google.api.client.sample.bigquery.model.QueryData;
import com.google.api.client.sample.bigquery.model.QueryRow;
import com.google.api.client.sample.bigquery.model.QueryValue;
import com.google.api.client.sample.bigquery.model.SchemaData;
import com.google.api.client.sample.bigquery.model.SchemaField;
import com.google.api.client.sample.bigquery.model.Util;
import java.io.IOException;
/**
* @author Yaniv Inbar
*/
public class BigQuerySample {
public static void main(String[] args) {
Util.enableLogging();
try {
try {
Auth.authorize();
executeSchema("bigquery/samples/shakespeare");
executeQuery("select count(*) from [bigquery/samples/shakespeare];");
executeQuery(
"select corpus, word, word_count from [bigquery/samples/shakespeare]"
+ " where word_count > 600 order by word_count desc;");
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
throw e;
}
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
static QueryData executeQuery(String query) throws IOException {
header("Query: " + query);
HttpRequest request = Util.TRANSPORT.buildGetRequest();
BigQueryUrl url = BigQueryUrl.fromRelativePath("query");
url.q = query;
request.url = url;
QueryData result = request.execute().parseAs(QueryData.class);
if (result.fields == null) {
System.out.println("No fields");
} else {
for (SchemaField field : result.fields) {
System.out.print(field.id + "\t");
}
System.out.println();
for (QueryRow row : result.rows) {
for (QueryValue value : row.f) {
System.out.print(value.value + "\t");
}
System.out.println();
}
}
return result;
}
static SchemaData executeSchema(String tableName) throws IOException {
header("Schema: " + tableName);
HttpRequest request = Util.TRANSPORT.buildGetRequest();
BigQueryUrl url = BigQueryUrl.fromRelativePath("tables");
url.pathParts.add(tableName);
request.url = url;
SchemaData result = request.execute().parseAs(SchemaData.class);
if (result.fields == null) {
System.out.println("No fields");
} else {
System.out.println(result.fields.size() + " fields:");
for (SchemaField field : result.fields) {
System.out.println(field.type + " " + field.id);
}
}
return result;
}
private static void header(String name) {
System.out.println();
System.out.println("============== " + name + " ==============");
System.out.println();
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.bigquery;
/**
* @author Yaniv Inbar
*/
public class ClientLoginCredentials {
static final String ENTER_USERNAME = "enter_username";
static final String ENTER_PASSWORD = "enter_password";
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.bigquery;
import com.google.api.client.googleapis.auth.clientlogin.ClientLogin;
import com.google.api.client.sample.bigquery.model.Util;
import java.io.IOException;
/**
* @author Yaniv Inbar
*/
class Auth {
static void authorize() throws IOException {
ClientLogin authenticator = new ClientLogin();
authenticator.transport = Util.AUTH_TRANSPORT;
authenticator.authTokenType = "ndev";
authenticator.username = ClientLoginCredentials.ENTER_USERNAME;
authenticator.password = ClientLoginCredentials.ENTER_PASSWORD;
authenticator.authenticate().setAuthorizationHeader(Util.TRANSPORT);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.bigquery.model;
import com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.util.Key;
/**
* BigQuery URL builder.
*
* @author Yaniv Inbar
*/
public final class BigQueryUrl extends GoogleUrl {
private static final String ROOT_URL = "https://www.googleapis.com/bigquery/v1/";
@Key
public String q;
/** Constructs a new BigQuery URL from the given encoded URL. */
public BigQueryUrl(String encodedUrl) {
super(encodedUrl);
if (Util.DEBUG) {
prettyprint = true;
}
}
/**
* Constructs a new BigQuery URL based on the given relative path.
*
* @param relativePath encoded path relative to the {@link #ROOT_URL}
* @return new BigQuery URL
*/
public static BigQueryUrl fromRelativePath(String relativePath) {
return new BigQueryUrl(ROOT_URL + relativePath);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.bigquery.model;
import com.google.api.client.util.Key;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class SchemaData {
@Key
public List<SchemaField> fields;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.bigquery.model;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class SchemaField {
@Key
public String id;
@Key
public String type;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.bigquery.model;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleUtils;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* @author Yaniv Inbar
*/
public class Util {
public static final boolean DEBUG = false;
public static final HttpTransport TRANSPORT = newTransport(false);
public static final HttpTransport AUTH_TRANSPORT = newTransport(true);
static HttpTransport newTransport(boolean forAuth) {
HttpTransport result = new NetHttpTransport();
GoogleUtils.useMethodOverride(result);
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-BigQuerySample/1.0");
result.defaultHeaders = headers;
if (!forAuth) {
JsonCParser parser = new JsonCParser();
parser.jsonFactory = new JacksonFactory();
result.addParser(parser);
}
return result;
}
public static void enableLogging() {
if (DEBUG) {
Logger logger = Logger.getLogger("com.google.api.client");
logger.setLevel(Level.CONFIG);
logger.addHandler(new Handler() {
@Override
public void close() throws SecurityException {
}
@Override
public void flush() {
}
@Override
public void publish(LogRecord record) {
// default ConsoleHandler will take care of >= INFO
if (record.getLevel().intValue() < Level.INFO.intValue()) {
System.out.println(record.getMessage());
}
}
});
}
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.bigquery.model;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class QueryValue {
@Key("v")
public String value;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.bigquery.model;
import com.google.api.client.util.Key;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class QueryRow {
@Key
public List<QueryValue> f;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.bigquery.model;
import com.google.api.client.util.Key;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class QueryData {
@Key
public List<SchemaField> fields;
@Key
public List<QueryRow> rows;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.chrome.licensing;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonHttpParser;
import com.google.api.client.sample.chrome.licensing.model.ChromeLicensingUrl;
import com.google.api.client.sample.chrome.licensing.model.ClientCredentials;
import com.google.api.client.sample.chrome.licensing.model.Debug;
import com.google.api.client.sample.chrome.licensing.model.License;
import java.io.IOException;
import java.util.Scanner;
/**
* @author Yaniv Inbar
*/
public class ChromeLicensingSample {
public static void main(String[] args) {
Debug.enableLogging();
try {
try {
HttpTransport transport = setUpTransport();
authorize(transport);
showLicense(transport);
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
throw e;
}
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
private static HttpTransport setUpTransport() {
HttpTransport transport = GoogleTransport.create();
GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders;
headers.setApplicationName("Google-ChromeLicensingSample/1.0");
transport.addParser(new JsonHttpParser());
return transport;
}
private static void authorize(HttpTransport transport) {
OAuthParameters authorizer = new OAuthParameters();
authorizer.consumerKey = ClientCredentials.ENTER_DOMAIN;
authorizer.token = ClientCredentials.ENTER_OAUTH_TOKEN;
OAuthHmacSigner signer = new OAuthHmacSigner();
signer.clientSharedSecret = ClientCredentials.ENTER_CLIENT_SHARED_SECRET;
signer.tokenSharedSecret = ClientCredentials.ENTER_OAUTH_TOKEN_SECRET;
authorizer.signer = signer;
authorizer.signRequestsUsingAuthorizationHeader(transport);
}
private static void showLicense(HttpTransport transport) throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = ChromeLicensingUrl.forUser(inputUsername());
License license = request.execute().parseAs(License.class);
System.out.print("YES".equals(license.result)
? "FULL".equals(license.accessLevel) ? "Full" : "Free" : "No");
System.out.println(" License.");
}
private static String inputUsername() {
System.out.print("Username to check license for: ");
Scanner scanner = new Scanner(System.in);
return scanner.next();
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.chrome.licensing.model;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class License {
@Key
public String result;
@Key
public String accessLevel;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.chrome.licensing.model;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* @author Yaniv Inbar
*/
public class Debug {
public static final boolean ENABLED = false;
public static void enableLogging() {
if (ENABLED) {
Logger logger = Logger.getLogger("com.google.api.client");
logger.setLevel(Level.CONFIG);
logger.addHandler(new Handler() {
@Override
public void close() throws SecurityException {
}
@Override
public void flush() {
}
@Override
public void publish(LogRecord record) {
// default ConsoleHandler will take care of >= INFO
if (record.getLevel().intValue() < Level.INFO.intValue()) {
System.out.println(record.getMessage());
}
}
});
}
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.chrome.licensing.model;
import com.google.api.client.googleapis.GoogleUrl;
/**
* @author Yaniv Inbar
*/
public class ChromeLicensingUrl extends GoogleUrl {
public ChromeLicensingUrl(String url) {
super(url);
if (Debug.ENABLED) {
this.prettyprint = true;
}
}
public static ChromeLicensingUrl forUser(String userId) {
ChromeLicensingUrl result = new ChromeLicensingUrl(
"https://www.googleapis.com/chromewebstore/v1/licenses");
result.pathParts.add(ClientCredentials.ENTER_APP_ID);
result.pathParts.add(userId);
return result;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.chrome.licensing.model;
/**
* See the instructions at <a
* href="http://code.google.com/chrome/webstore/docs/get_started.html">Tutorial:
* Getting Started</a>.
*
* @author Yaniv Inbar
*/
public class ClientCredentials {
public static final String ENTER_APP_ID = "enter_app_id";
public static final String ENTER_OAUTH_TOKEN = "enter_oauth_token";
public static final String ENTER_OAUTH_TOKEN_SECRET =
"enter_oauth_token_secret";
public static final String ENTER_DOMAIN = "anonymous";
public static final String ENTER_CLIENT_SHARED_SECRET = "anonymous";
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.youtube;
import com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class YouTubeUrl extends GoogleUrl {
/** Whether to pretty print HTTP requests and responses. */
private static final boolean PRETTY_PRINT = true;
static final String ROOT_URL = "https://gdata.youtube.com/feeds/api";
@Key
String author;
@Key("max-results")
Integer maxResults = 2;
YouTubeUrl(String encodedUrl) {
super(encodedUrl);
this.alt = "jsonc";
this.prettyprint = PRETTY_PRINT;
}
private static YouTubeUrl root() {
return new YouTubeUrl(ROOT_URL);
}
static YouTubeUrl forVideosFeed() {
YouTubeUrl result = root();
result.pathParts.add("videos");
return result;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.youtube;
/**
* @author Yaniv Inbar
*/
class View {
static void header(String name) {
System.out.println();
System.out.println("============== " + name + " ==============");
System.out.println();
}
static void display(Feed<? extends Item> feed) {
System.out.println(
"Showing first " + feed.items.size() + " of " + feed.totalItems + " videos: ");
for (Item item : feed.items) {
System.out.println();
System.out.println("-----------------------------------------------");
display(item);
}
}
static void display(Item item) {
System.out.println("Title: " + item.title);
System.out.println("Updated: " + item.updated);
if (item instanceof Video) {
Video video = (Video) item;
if (video.description != null) {
System.out.println("Description: " + video.description);
}
if (!video.tags.isEmpty()) {
System.out.println("Tags: " + video.tags);
}
if (video.player != null) {
System.out.println("Play URL: " + video.player.defaultUrl);
}
}
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.youtube;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import java.io.IOException;
/**
* @author Yaniv Inbar
*/
public class YouTubeClient {
private final JsonFactory jsonFactory = new JacksonFactory();
private final HttpTransport transport = new NetHttpTransport();
private final HttpRequestFactory requestFactory;
public YouTubeClient() {
final JsonCParser parser = new JsonCParser();
parser.jsonFactory = jsonFactory;
requestFactory = transport.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) {
// headers
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-YouTubeSample/1.0");
headers.gdataVersion = "2";
request.headers = headers;
request.addParser(parser);
}
});
}
public VideoFeed executeGetVideoFeed(YouTubeUrl url) throws IOException {
return executeGetFeed(url, VideoFeed.class);
}
private <F extends Feed<? extends Item>> F executeGetFeed(YouTubeUrl url, Class<F> feedClass)
throws IOException {
HttpRequest request = requestFactory.buildGetRequest(url);
return request.execute().parseAs(feedClass);
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.youtube;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.Key;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class Feed<T extends Item> {
@Key
List<T> items;
@Key
int itemsPerPage;
@Key
int startIndex;
@Key
int totalItems;
@Key
DateTime updated;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.youtube;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class Player {
// "default" is a Java keyword, so need to specify the JSON key manually
@Key("default")
String defaultUrl;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.youtube;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.Key;
/**
* @author Yaniv Inbar
*/
public class Item {
@Key
String id;
@Key
String title;
@Key
DateTime updated;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.youtube;
import com.google.api.client.util.Key;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yaniv Inbar
*/
public class Video extends Item {
@Key
String description;
@Key
List<String> tags = new ArrayList<String>();
@Key
Player player;
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.youtube;
import com.google.api.client.http.HttpResponseException;
import java.io.IOException;
/**
* @author Yaniv Inbar
*/
public class YouTubeSample {
private static void run() throws IOException {
YouTubeClient client = new YouTubeClient();
showVideos(client);
}
public static void main(String[] args) {
try {
try {
run();
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
}
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
private static VideoFeed showVideos(YouTubeClient client) throws IOException {
View.header("Get Videos");
// build URL for the video feed for "search stories"
YouTubeUrl url = YouTubeUrl.forVideosFeed();
url.author = "searchstories";
// execute GData request for the feed
VideoFeed feed = client.executeGetVideoFeed(url);
View.display(feed);
return feed;
}
}
| Java |
/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.sample.youtube;
/**
* @author Yaniv Inbar
*/
public class VideoFeed extends Feed<Video> {
}
| Java |
/*------------------------------------------------------------------------------
** 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;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.utils.GraphCanvas;
import nl.sogeti.android.gpstracker.actions.utils.StatisticsCalulator;
import nl.sogeti.android.gpstracker.actions.utils.StatisticsDelegate;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.util.UnitsI18n;
import nl.sogeti.android.gpstracker.viewer.TrackList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ViewFlipper;
/**
* Display some calulations based on a track
*
* @version $Id$
* @author rene (c) Oct 19, 2009, Sogeti B.V.
*/
public class Statistics extends Activity implements StatisticsDelegate
{
private static final int DIALOG_GRAPHTYPE = 3;
private static final int MENU_GRAPHTYPE = 11;
private static final int MENU_TRACKLIST = 12;
private static final int MENU_SHARE = 41;
private static final String TRACKURI = "TRACKURI";
private static final String TAG = "OGT.Statistics";
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private Uri mTrackUri = null;
private boolean calculating;
private TextView overallavgSpeedView;
private TextView avgSpeedView;
private TextView distanceView;
private TextView endtimeView;
private TextView starttimeView;
private TextView maxSpeedView;
private TextView waypointsView;
private TextView mAscensionView;
private TextView mElapsedTimeView;
private UnitsI18n mUnits;
private GraphCanvas mGraphTimeSpeed;
private ViewFlipper mViewFlipper;
private Animation mSlideLeftIn;
private Animation mSlideLeftOut;
private Animation mSlideRightIn;
private Animation mSlideRightOut;
private GestureDetector mGestureDetector;
private GraphCanvas mGraphDistanceSpeed;
private GraphCanvas mGraphTimeAltitude;
private GraphCanvas mGraphDistanceAltitude;
private final ContentObserver mTrackObserver = new ContentObserver( new Handler() )
{
@Override
public void onChange( boolean selfUpdate )
{
if( !calculating )
{
Statistics.this.drawTrackingStatistics();
}
}
};
private OnClickListener mGraphControlListener = new View.OnClickListener()
{
@Override
public void onClick( View v )
{
int id = v.getId();
switch( id )
{
case R.id.graphtype_timespeed:
mViewFlipper.setDisplayedChild( 0 );
break;
case R.id.graphtype_distancespeed:
mViewFlipper.setDisplayedChild( 1 );
break;
case R.id.graphtype_timealtitude:
mViewFlipper.setDisplayedChild( 2 );
break;
case R.id.graphtype_distancealtitude:
mViewFlipper.setDisplayedChild( 3 );
break;
default:
break;
}
dismissDialog( DIALOG_GRAPHTYPE );
}
};
class MyGestureDetector extends SimpleOnGestureListener
{
@Override
public boolean onFling( MotionEvent e1, MotionEvent e2, float velocityX, float velocityY )
{
if( Math.abs( e1.getY() - e2.getY() ) > SWIPE_MAX_OFF_PATH )
return false;
// right to left swipe
if( e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY )
{
mViewFlipper.setInAnimation( mSlideLeftIn );
mViewFlipper.setOutAnimation( mSlideLeftOut );
mViewFlipper.showNext();
}
else if( e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs( velocityX ) > SWIPE_THRESHOLD_VELOCITY )
{
mViewFlipper.setInAnimation( mSlideRightIn );
mViewFlipper.setOutAnimation( mSlideRightOut );
mViewFlipper.showPrevious();
}
return false;
}
}
/**
* Called when the activity is first created.
*/
@Override
protected void onCreate( Bundle load )
{
super.onCreate( load );
mUnits = new UnitsI18n( this, new UnitsI18n.UnitsChangeListener()
{
@Override
public void onUnitsChange()
{
drawTrackingStatistics();
}
} );
setContentView( R.layout.statistics );
mViewFlipper = (ViewFlipper) findViewById( R.id.flipper );
mViewFlipper.setDrawingCacheEnabled(true);
mSlideLeftIn = AnimationUtils.loadAnimation( this, R.anim.slide_left_in );
mSlideLeftOut = AnimationUtils.loadAnimation( this, R.anim.slide_left_out );
mSlideRightIn = AnimationUtils.loadAnimation( this, R.anim.slide_right_in );
mSlideRightOut = AnimationUtils.loadAnimation( this, R.anim.slide_right_out );
mGraphTimeSpeed = (GraphCanvas) mViewFlipper.getChildAt( 0 );
mGraphDistanceSpeed = (GraphCanvas) mViewFlipper.getChildAt( 1 );
mGraphTimeAltitude = (GraphCanvas) mViewFlipper.getChildAt( 2 );
mGraphDistanceAltitude = (GraphCanvas) mViewFlipper.getChildAt( 3 );
mGraphTimeSpeed.setType( GraphCanvas.TIMESPEEDGRAPH );
mGraphDistanceSpeed.setType( GraphCanvas.DISTANCESPEEDGRAPH );
mGraphTimeAltitude.setType( GraphCanvas.TIMEALTITUDEGRAPH );
mGraphDistanceAltitude.setType( GraphCanvas.DISTANCEALTITUDEGRAPH );
mGestureDetector = new GestureDetector( new MyGestureDetector() );
maxSpeedView = (TextView) findViewById( R.id.stat_maximumspeed );
mAscensionView = (TextView) findViewById( R.id.stat_ascension );
mElapsedTimeView = (TextView) findViewById( R.id.stat_elapsedtime );
overallavgSpeedView = (TextView) findViewById( R.id.stat_overallaveragespeed );
avgSpeedView = (TextView) findViewById( R.id.stat_averagespeed );
distanceView = (TextView) findViewById( R.id.stat_distance );
starttimeView = (TextView) findViewById( R.id.stat_starttime );
endtimeView = (TextView) findViewById( R.id.stat_endtime );
waypointsView = (TextView) findViewById( R.id.stat_waypoints );
if( load != null && load.containsKey( TRACKURI ) )
{
mTrackUri = Uri.withAppendedPath( Tracks.CONTENT_URI, load.getString( TRACKURI ) );
}
else
{
mTrackUri = this.getIntent().getData();
}
}
@Override
protected void onRestoreInstanceState( Bundle load )
{
if( load != null )
{
super.onRestoreInstanceState( load );
}
if( load != null && load.containsKey( TRACKURI ) )
{
mTrackUri = Uri.withAppendedPath( Tracks.CONTENT_URI, load.getString( TRACKURI ) );
}
if( load != null && load.containsKey( "FLIP" ) )
{
mViewFlipper.setDisplayedChild( load.getInt( "FLIP" ) );
}
}
@Override
protected void onSaveInstanceState( Bundle save )
{
super.onSaveInstanceState( save );
save.putString( TRACKURI, mTrackUri.getLastPathSegment() );
save.putInt( "FLIP" , mViewFlipper.getDisplayedChild() );
}
/*
* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause()
{
super.onPause();
mViewFlipper.stopFlipping();
mGraphTimeSpeed.clearData();
mGraphDistanceSpeed.clearData();
mGraphTimeAltitude.clearData();
mGraphDistanceAltitude.clearData();
ContentResolver resolver = this.getContentResolver();
resolver.unregisterContentObserver( this.mTrackObserver );
}
/*
* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume()
{
super.onResume();
drawTrackingStatistics();
ContentResolver resolver = this.getContentResolver();
resolver.registerContentObserver( mTrackUri, true, this.mTrackObserver );
}
@Override
public boolean onCreateOptionsMenu( Menu menu )
{
boolean result = super.onCreateOptionsMenu( menu );
menu.add( ContextMenu.NONE, MENU_GRAPHTYPE, ContextMenu.NONE, R.string.menu_graphtype ).setIcon( R.drawable.ic_menu_picture ).setAlphabeticShortcut( 't' );
menu.add( ContextMenu.NONE, MENU_TRACKLIST, ContextMenu.NONE, R.string.menu_tracklist ).setIcon( R.drawable.ic_menu_show_list ).setAlphabeticShortcut( 'l' );
menu.add( ContextMenu.NONE, MENU_SHARE, ContextMenu.NONE, R.string.menu_shareTrack ).setIcon( R.drawable.ic_menu_share ).setAlphabeticShortcut( 's' );
return result;
}
@Override
public boolean onOptionsItemSelected( MenuItem item )
{
boolean handled = false;
Intent intent;
switch( item.getItemId() )
{
case MENU_GRAPHTYPE:
showDialog( DIALOG_GRAPHTYPE );
handled = true;
break;
case MENU_TRACKLIST:
intent = new Intent( this, TrackList.class );
intent.putExtra( Tracks._ID, mTrackUri.getLastPathSegment() );
startActivityForResult( intent, MENU_TRACKLIST );
break;
case MENU_SHARE:
intent = new Intent( Intent.ACTION_RUN );
intent.setDataAndType( mTrackUri, Tracks.CONTENT_ITEM_TYPE );
intent.addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION );
Bitmap bm = mViewFlipper.getDrawingCache();
Uri screenStreamUri = ShareTrack.storeScreenBitmap(bm);
intent.putExtra(Intent.EXTRA_STREAM, screenStreamUri);
startActivityForResult(Intent.createChooser( intent, getString( R.string.share_track ) ), MENU_SHARE);
handled = true;
break;
default:
handled = super.onOptionsItemSelected( item );
}
return handled;
}
@Override
public boolean onTouchEvent( MotionEvent event )
{
if( mGestureDetector.onTouchEvent( event ) )
return true;
else
return false;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent intent )
{
super.onActivityResult( requestCode, resultCode, intent );
switch( requestCode )
{
case MENU_TRACKLIST:
if( resultCode == RESULT_OK )
{
mTrackUri = intent.getData();
drawTrackingStatistics();
}
break;
case MENU_SHARE:
ShareTrack.clearScreenBitmap();
break;
default:
Log.w( TAG, "Unknown activity result request code" );
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog( int id )
{
Dialog dialog = null;
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch( id )
{
case DIALOG_GRAPHTYPE:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.graphtype, null );
builder.setTitle( R.string.dialog_graphtype_title ).setIcon( android.R.drawable.ic_dialog_alert ).setNegativeButton( R.string.btn_cancel, null ).setView( view );
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 )
{
switch( id )
{
case DIALOG_GRAPHTYPE:
Button speedtime = (Button) dialog.findViewById( R.id.graphtype_timespeed );
Button speeddistance = (Button) dialog.findViewById( R.id.graphtype_distancespeed );
Button altitudetime = (Button) dialog.findViewById( R.id.graphtype_timealtitude );
Button altitudedistance = (Button) dialog.findViewById( R.id.graphtype_distancealtitude );
speedtime.setOnClickListener( mGraphControlListener );
speeddistance.setOnClickListener( mGraphControlListener );
altitudetime.setOnClickListener( mGraphControlListener );
altitudedistance.setOnClickListener( mGraphControlListener );
default:
break;
}
super.onPrepareDialog( id, dialog );
}
private void drawTrackingStatistics()
{
calculating = true;
StatisticsCalulator calculator = new StatisticsCalulator( this, mUnits, this );
calculator.execute(mTrackUri);
}
@Override
public void finishedCalculations(StatisticsCalulator calculated)
{
mGraphTimeSpeed.setData ( mTrackUri, calculated );
mGraphDistanceSpeed.setData ( mTrackUri, calculated );
mGraphTimeAltitude.setData ( mTrackUri, calculated );
mGraphDistanceAltitude.setData( mTrackUri, calculated );
mViewFlipper.postInvalidate();
maxSpeedView.setText( calculated.getMaxSpeedText() );
mElapsedTimeView.setText( calculated.getDurationText() );
mAscensionView.setText( calculated.getAscensionText() );
overallavgSpeedView.setText( calculated.getOverallavgSpeedText() );
avgSpeedView.setText( calculated.getAvgSpeedText() );
distanceView.setText( calculated.getDistanceText() );
starttimeView.setText( Long.toString( calculated.getStarttime() ) );
endtimeView.setText( Long.toString( calculated.getEndtime() ) );
String titleFormat = getString( R.string.stat_title );
setTitle( String.format( titleFormat, calculated.getTracknameText() ) );
waypointsView.setText( calculated.getWaypointsText() );
calculating = false;
}
}
| Java |
/*------------------------------------------------------------------------------
** 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;
import java.util.Calendar;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
/**
* Empty Activity that pops up the dialog to name the track
*
* @version $Id$
* @author rene (c) Jul 27, 2010, Sogeti B.V.
*/
public class NameTrack extends Activity
{
private static final int DIALOG_TRACKNAME = 23;
protected static final String TAG = "OGT.NameTrack";
private EditText mTrackNameView;
private boolean paused;
Uri mTrackUri;
private final DialogInterface.OnClickListener mTrackNameDialogListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick( DialogInterface dialog, int which )
{
String trackName = null;
switch( which )
{
case DialogInterface.BUTTON_POSITIVE:
trackName = mTrackNameView.getText().toString();
ContentValues values = new ContentValues();
values.put( Tracks.NAME, trackName );
getContentResolver().update( mTrackUri, values, null, null );
clearNotification();
break;
case DialogInterface.BUTTON_NEUTRAL:
startDelayNotification();
break;
case DialogInterface.BUTTON_NEGATIVE:
clearNotification();
break;
default:
Log.e( TAG, "Unknown option ending dialog:"+which );
break;
}
finish();
}
};
private void clearNotification()
{
NotificationManager noticationManager = (NotificationManager) this.getSystemService( Context.NOTIFICATION_SERVICE );;
noticationManager.cancel( R.layout.namedialog );
}
private void startDelayNotification()
{
int resId = R.string.dialog_routename_title;
int icon = R.drawable.ic_maps_indicator_current_position;
CharSequence tickerText = getResources().getString( resId );
long when = System.currentTimeMillis();
Notification nameNotification = new Notification( icon, tickerText, when );
nameNotification.flags |= Notification.FLAG_AUTO_CANCEL;
CharSequence contentTitle = getResources().getString( R.string.app_name );
CharSequence contentText = getResources().getString( resId );
Intent notificationIntent = new Intent( this, NameTrack.class );
notificationIntent.setData( mTrackUri );
PendingIntent contentIntent = PendingIntent.getActivity( this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK );
nameNotification.setLatestEventInfo( this, contentTitle, contentText, contentIntent );
NotificationManager noticationManager = (NotificationManager) this.getSystemService( Context.NOTIFICATION_SERVICE );
noticationManager.notify( R.layout.namedialog, nameNotification );
}
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
this.setVisible( false );
paused = false;
mTrackUri = this.getIntent().getData();
}
@Override
protected void onPause()
{
super.onPause();
paused = true;
}
/*
* (non-Javadoc)
* @see com.google.android.maps.MapActivity#onPause()
*/
@Override
protected void onResume()
{
super.onResume();
if( mTrackUri != null )
{
showDialog( DIALOG_TRACKNAME );
}
else
{
Log.e(TAG, "Naming track without a track URI supplied." );
finish();
}
}
@Override
protected Dialog onCreateDialog( int id )
{
Dialog dialog = null;
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch (id)
{
case DIALOG_TRACKNAME:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.namedialog, null );
mTrackNameView = (EditText) view.findViewById( R.id.nameField );
builder
.setTitle( R.string.dialog_routename_title )
.setMessage( R.string.dialog_routename_message )
.setIcon( android.R.drawable.ic_dialog_alert )
.setPositiveButton( R.string.btn_okay, mTrackNameDialogListener )
.setNeutralButton( R.string.btn_skip, mTrackNameDialogListener )
.setNegativeButton( R.string.btn_cancel, mTrackNameDialogListener )
.setView( view );
dialog = builder.create();
dialog.setOnDismissListener( new OnDismissListener()
{
@Override
public void onDismiss( DialogInterface dialog )
{
if( !paused )
{
finish();
}
}
});
return dialog;
default:
return super.onCreateDialog( id );
}
}
@Override
protected void onPrepareDialog( int id, Dialog dialog )
{
switch (id)
{
case DIALOG_TRACKNAME:
String trackName;
Calendar c = Calendar.getInstance();
trackName = String.format( getString( R.string.dialog_routename_default ), c, c, c, c, c );
mTrackNameView.setText( trackName );
mTrackNameView.setSelection( 0, trackName.length() );
break;
default:
super.onPrepareDialog( id, dialog );
break;
}
}
}
| Java |
package nl.sogeti.android.gpstracker.actions.utils;
public interface StatisticsDelegate
{
void finishedCalculations(StatisticsCalulator calculated);
} | Java |
/*------------------------------------------------------------------------------
** 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);
}
| Java |
/*------------------------------------------------------------------------------
** 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);
}
}
}
| Java |
/*------------------------------------------------------------------------------
** 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 );
}
}
| Java |
/*------------------------------------------------------------------------------
** 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();
}
}
}
| Java |
/*------------------------------------------------------------------------------
** 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);
}
}
}
| Java |
/*------------------------------------------------------------------------------
** 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.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.channels.FileChannel;
import java.util.Date;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executor;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import nl.sogeti.android.gpstracker.actions.utils.ProgressListener;
import nl.sogeti.android.gpstracker.db.GPStracking.Media;
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.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.Window;
/**
* Async XML creation task Execute without parameters (Void) Update posted with
* single Integer And result is a filename in a String
*
* @version $Id$
* @author rene (c) May 29, 2011, Sogeti B.V.
*/
public abstract class XmlCreator extends AsyncTask<Void, Integer, Uri>
{
private String TAG = "OGT.XmlCreator";
private String mExportDirectoryPath;
private boolean mNeedsBundling;
String mChosenName;
private ProgressListener mProgressListener;
protected Context mContext;
protected Uri mTrackUri;
String mFileName;
private String mErrorText;
private Exception mException;
private String mTask;
public ProgressAdmin mProgressAdmin;
XmlCreator(Context context, Uri trackUri, String chosenFileName, ProgressListener listener)
{
mChosenName = chosenFileName;
mContext = context;
mTrackUri = trackUri;
mProgressListener = listener;
mProgressAdmin = new ProgressAdmin();
String trackName = extractCleanTrackName();
mFileName = cleanFilename(mChosenName, trackName);
}
public void executeOn(Executor executor)
{
if (Build.VERSION.SDK_INT >= 11)
{
executeOnExecutor(executor);
}
else
{
execute();
}
}
private String extractCleanTrackName()
{
Cursor trackCursor = null;
ContentResolver resolver = mContext.getContentResolver();
String trackName = "Untitled";
try
{
trackCursor = resolver.query(mTrackUri, new String[] { Tracks.NAME }, null, null, null);
if (trackCursor.moveToLast())
{
trackName = cleanFilename(trackCursor.getString(0), trackName);
}
}
finally
{
if (trackCursor != null)
{
trackCursor.close();
}
}
return trackName;
}
/**
* Calculated the total progress sum expected from a export to file This is
* the sum of the number of waypoints and media entries times 100. The whole
* number is doubled when compression is needed.
*/
public void determineProgressGoal()
{
if (mProgressListener != null)
{
Uri allWaypointsUri = Uri.withAppendedPath(mTrackUri, "waypoints");
Uri allMediaUri = Uri.withAppendedPath(mTrackUri, "media");
Cursor cursor = null;
ContentResolver resolver = mContext.getContentResolver();
try
{
cursor = resolver.query(allWaypointsUri, new String[] { "count(" + Waypoints.TABLE + "." + Waypoints._ID + ")" }, null, null, null);
if (cursor.moveToLast())
{
mProgressAdmin.setWaypointCount(cursor.getInt(0));
}
cursor.close();
cursor = resolver.query(allMediaUri, new String[] { "count(" + Media.TABLE + "." + Media._ID + ")" }, null, null, null);
if (cursor.moveToLast())
{
mProgressAdmin.setMediaCount(cursor.getInt(0));
}
cursor.close();
cursor = resolver.query(allMediaUri, new String[] { "count(" + Tracks._ID + ")" }, Media.URI + " LIKE ? and " + Media.URI + " NOT LIKE ?",
new String[] { "file://%", "%txt" }, null);
if (cursor.moveToLast())
{
mProgressAdmin.setCompress( cursor.getInt(0) > 0 );
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
else
{
Log.w(TAG, "Exporting " + mTrackUri + " without progress!");
}
}
/**
* Removes all non-word chars (\W) from the text
*
* @param fileName
* @param defaultName
* @return a string larger then 0 with either word chars remaining from the
* input or the default provided
*/
public static String cleanFilename(String fileName, String defaultName)
{
if (fileName == null || "".equals(fileName))
{
fileName = defaultName;
}
else
{
fileName = fileName.replaceAll("\\W", "");
fileName = (fileName.length() > 0) ? fileName : defaultName;
}
return fileName;
}
/**
* Includes media into the export directory and returns the relative path of
* the media
*
* @param inputFilePath
* @return file path relative to the export dir
* @throws IOException
*/
protected String includeMediaFile(String inputFilePath) throws IOException
{
mNeedsBundling = true;
File source = new File(inputFilePath);
File target = new File(mExportDirectoryPath + "/" + source.getName());
// Log.d( TAG, String.format( "Copy %s to %s", source, target ) );
if (source.exists())
{
FileInputStream fileInputStream = new FileInputStream(source);
FileChannel inChannel = fileInputStream.getChannel();
FileOutputStream fileOutputStream = new FileOutputStream(target);
FileChannel outChannel = fileOutputStream.getChannel();
try
{
inChannel.transferTo(0, inChannel.size(), outChannel);
}
finally
{
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
if (fileInputStream != null) fileInputStream.close();
if (fileOutputStream != null) fileOutputStream.close();
}
}
else
{
Log.w( TAG, "Failed to add file to new XML export. Missing: "+inputFilePath );
}
mProgressAdmin.addMediaProgress();
return target.getName();
}
/**
* Just to start failing early
*
* @throws IOException
*/
protected void verifySdCardAvailibility() throws IOException
{
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state))
{
throw new IOException("The ExternalStorage is not mounted, unable to export files for sharing.");
}
}
/**
* Create a zip of the export directory based on the given filename
*
* @param fileName The directory to be replaced by a zipped file of the same
* name
* @param extension
* @return full path of the build zip file
* @throws IOException
*/
protected String bundlingMediaAndXml(String fileName, String extension) throws IOException
{
String zipFilePath;
if (fileName.endsWith(".zip") || fileName.endsWith(extension))
{
zipFilePath = Constants.getSdCardDirectory(mContext) + fileName;
}
else
{
zipFilePath = Constants.getSdCardDirectory(mContext) + fileName + extension;
}
String[] filenames = new File(mExportDirectoryPath).list();
byte[] buf = new byte[1024];
ZipOutputStream zos = null;
try
{
zos = new ZipOutputStream(new FileOutputStream(zipFilePath));
for (int i = 0; i < filenames.length; i++)
{
String entryFilePath = mExportDirectoryPath + "/" + filenames[i];
FileInputStream in = new FileInputStream(entryFilePath);
zos.putNextEntry(new ZipEntry(filenames[i]));
int len;
while ((len = in.read(buf)) >= 0)
{
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
mProgressAdmin.addCompressProgress();
}
}
finally
{
if (zos != null)
{
zos.close();
}
}
deleteRecursive(new File(mExportDirectoryPath));
return zipFilePath;
}
public static boolean deleteRecursive(File file)
{
if (file.isDirectory())
{
String[] children = file.list();
for (int i = 0; i < children.length; i++)
{
boolean success = deleteRecursive(new File(file, children[i]));
if (!success)
{
return false;
}
}
}
return file.delete();
}
public void setExportDirectoryPath(String exportDirectoryPath)
{
this.mExportDirectoryPath = exportDirectoryPath;
}
public String getExportDirectoryPath()
{
return mExportDirectoryPath;
}
public void quickTag(XmlSerializer serializer, String ns, String tag, String content) throws IllegalArgumentException, IllegalStateException, IOException
{
if( tag == null)
{
tag = "";
}
if( content == null)
{
content = "";
}
serializer.text("\n");
serializer.startTag(ns, tag);
serializer.text(content);
serializer.endTag(ns, tag);
}
public boolean needsBundling()
{
return mNeedsBundling;
}
public static String convertStreamToString(InputStream is) throws IOException
{
String result = "";
/*
* To convert the InputStream to String we use the Reader.read(char[]
* buffer) method. We iterate until the Reader return -1 which means
* there's no more data to read. We use the StringWriter class to produce
* the string.
*/
if (is != null)
{
Writer writer = new StringWriter();
char[] buffer = new char[8192];
try
{
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
}
finally
{
is.close();
}
result = writer.toString();
}
return result;
}
public static InputStream convertStreamToLoggedStream(String tag, InputStream is) throws IOException
{
String result = "";
/*
* To convert the InputStream to String we use the Reader.read(char[]
* buffer) method. We iterate until the Reader return -1 which means
* there's no more data to read. We use the StringWriter class to produce
* the string.
*/
if (is != null)
{
Writer writer = new StringWriter();
char[] buffer = new char[8192];
try
{
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
}
finally
{
is.close();
}
result = writer.toString();
}
InputStream in = new ByteArrayInputStream(result.getBytes("UTF-8"));
return in;
}
protected abstract String getContentType();
protected void handleError(String task, Exception e, String text)
{
Log.e(TAG, "Unable to save ", e);
mTask = task;
mException = e;
mErrorText = text;
cancel(false);
throw new CancellationException(text);
}
@Override
protected void onPreExecute()
{
if(mProgressListener!= null)
{
mProgressListener.started();
}
}
@Override
protected void onProgressUpdate(Integer... progress)
{
if(mProgressListener!= null)
{
mProgressListener.setProgress(mProgressAdmin.getProgress());
}
}
@Override
protected void onPostExecute(Uri resultFilename)
{
if(mProgressListener!= null)
{
mProgressListener.finished(resultFilename);
}
}
@Override
protected void onCancelled()
{
if(mProgressListener!= null)
{
mProgressListener.finished(null);
mProgressListener.showError(mTask, mErrorText, mException);
}
}
public class ProgressAdmin
{
long lastUpdate;
private boolean compressCount;
private boolean compressProgress;
private boolean uploadCount;
private boolean uploadProgress;
private int mediaCount;
private int mediaProgress;
private int waypointCount;
private int waypointProgress;
private long photoUploadCount ;
private long photoUploadProgress ;
public void addMediaProgress()
{
mediaProgress ++;
}
public void addCompressProgress()
{
compressProgress = true;
}
public void addUploadProgress()
{
uploadProgress = true;
}
public void addPhotoUploadProgress(long length)
{
photoUploadProgress += length;
}
/**
* Get the progress on scale 0 ... Window.PROGRESS_END
*
* @return Returns the progress as a int.
*/
public int getProgress()
{
int blocks = 0;
if( waypointCount > 0 ){ blocks++; }
if( mediaCount > 0 ){ blocks++; }
if( compressCount ){ blocks++; }
if( uploadCount ){ blocks++; }
if( photoUploadCount > 0 ){ blocks++; }
int progress;
if( blocks > 0 )
{
int blockSize = Window.PROGRESS_END / blocks;
progress = waypointCount > 0 ? blockSize * waypointProgress / waypointCount : 0;
progress += mediaCount > 0 ? blockSize * mediaProgress / mediaCount : 0;
progress += compressProgress ? blockSize : 0;
progress += uploadProgress ? blockSize : 0;
progress += photoUploadCount > 0 ? blockSize * photoUploadProgress / photoUploadCount : 0;
}
else
{
progress = 0;
}
//Log.d( TAG, "Progress updated to "+progress);
return progress;
}
public void setWaypointCount(int waypoint)
{
waypointCount = waypoint;
considerPublishProgress();
}
public void setMediaCount(int media)
{
mediaCount = media;
considerPublishProgress();
}
public void setCompress( boolean compress)
{
compressCount = compress;
considerPublishProgress();
}
public void setUpload( boolean upload)
{
uploadCount = upload;
considerPublishProgress();
}
public void setPhotoUpload(long length)
{
photoUploadCount += length;
considerPublishProgress();
}
public void addWaypointProgress(int i)
{
waypointProgress += i;
considerPublishProgress();
}
public void considerPublishProgress()
{
long now = new Date().getTime();
if( now - lastUpdate > 1000 )
{
lastUpdate = now;
publishProgress();
}
}
}
}
| Java |
/*------------------------------------------------------------------------------
** 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";
}
} | Java |
/*------------------------------------------------------------------------------
** 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();
}
}
}
}; | Java |
/*------------------------------------------------------------------------------
** 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());
}
}
| Java |
/*------------------------------------------------------------------------------
** 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>
* <Folder>
* <Placemark>
* serializeSegmentToTimespan()
* <LineString>
* serializeWaypoints()
* </LineString>
* </Placemark>
* <Placemark/>
* <Placemark/>
* </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();
}
}
}
/**
* <TimeSpan><begin>...</begin><end>...</end></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();
}
}
}
/**
* <coordinates>...</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();
}
}
/**
* <Point>...</Point> <shape>rectangle</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;
}
} | Java |
/*------------------------------------------------------------------------------
** 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);
}
}
| Java |
/*------------------------------------------------------------------------------
** 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());
}
}
| Java |
/*------------------------------------------------------------------------------
** 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;
import java.util.List;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService.LocalBinder;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsTracks;
import nl.sogeti.android.gpstracker.db.GPStracking.MetaData;
import nl.sogeti.android.gpstracker.util.Constants;
import nl.sogeti.android.gpstracker.util.Pair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
/**
* Empty Activity that pops up the dialog to describe the track
*
* @version $Id: NameTrack.java 888 2011-03-14 19:44:44Z rcgroot@gmail.com $
* @author rene (c) Jul 27, 2010, Sogeti B.V.
*/
public class DescribeTrack extends Activity
{
private static final int DIALOG_TRACKDESCRIPTION = 42;
protected static final String TAG = "OGT.DescribeTrack";
private static final String ACTIVITY_ID = "ACTIVITY_ID";
private static final String BUNDLE_ID = "BUNDLE_ID";
private Spinner mActivitySpinner;
private Spinner mBundleSpinner;
private EditText mDescriptionText;
private CheckBox mPublicCheck;
private Button mOkayButton;
private boolean paused;
private Uri mTrackUri;
private ProgressBar mProgressSpinner;
private AlertDialog mDialog;
private BreadcrumbsService mService;
boolean mBound = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setVisible(false);
paused = false;
mTrackUri = this.getIntent().getData();
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);
}
/*
* (non-Javadoc)
* @see com.google.android.maps.MapActivity#onPause()
*/
@Override
protected void onResume()
{
super.onResume();
if (mTrackUri != null)
{
showDialog(DIALOG_TRACKDESCRIPTION);
}
else
{
Log.e(TAG, "Describing track without a track URI supplied.");
finish();
}
}
@Override
protected void onPause()
{
super.onPause();
paused = true;
}
@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);
}
super.onDestroy();
}
@Override
protected Dialog onCreateDialog(int id)
{
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch (id)
{
case DIALOG_TRACKDESCRIPTION:
builder = new AlertDialog.Builder(this);
factory = LayoutInflater.from(this);
view = factory.inflate(R.layout.describedialog, null);
mActivitySpinner = (Spinner) view.findViewById(R.id.activity);
mBundleSpinner = (Spinner) view.findViewById(R.id.bundle);
mDescriptionText = (EditText) view.findViewById(R.id.description);
mPublicCheck = (CheckBox) view.findViewById(R.id.public_checkbox);
mProgressSpinner = (ProgressBar) view.findViewById(R.id.progressSpinner);
builder.setTitle(R.string.dialog_description_title).setMessage(R.string.dialog_description_message).setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_okay, mTrackDescriptionDialogListener).setNegativeButton(R.string.btn_cancel, mTrackDescriptionDialogListener).setView(view);
mDialog = builder.create();
setUiEnabled();
mDialog.setOnDismissListener(new OnDismissListener()
{
@Override
public void onDismiss(DialogInterface dialog)
{
if (!paused)
{
finish();
}
}
});
return mDialog;
default:
return super.onCreateDialog(id);
}
}
@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
switch (id)
{
case DIALOG_TRACKDESCRIPTION:
setUiEnabled();
connectBreadcrumbs();
break;
default:
super.onPrepareDialog(id, dialog);
break;
}
}
private void connectBreadcrumbs()
{
if (mService != null && !mService.isAuthorized())
{
mService.collectBreadcrumbsOauthToken();
}
}
private void saveBreadcrumbsPreference(int activityPosition, int bundlePosition)
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putInt(ACTIVITY_ID, activityPosition);
editor.putInt(BUNDLE_ID, bundlePosition);
editor.commit();
}
private void loadBreadcrumbsPreference()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int activityPos = prefs.getInt(ACTIVITY_ID, 0);
activityPos = activityPos < mActivitySpinner.getCount() ? activityPos : 0;
mActivitySpinner.setSelection(activityPos);
int bundlePos = prefs.getInt(BUNDLE_ID, 0);
bundlePos = bundlePos < mBundleSpinner.getCount() ? bundlePos : 0;
mBundleSpinner.setSelection(bundlePos);
}
private ContentValues buildContentValues(String key, String value)
{
ContentValues contentValues = new ContentValues();
contentValues.put(MetaData.KEY, key);
contentValues.put(MetaData.VALUE, value);
return contentValues;
}
private void setUiEnabled()
{
boolean enabled = mService != null && mService.isAuthorized();
if (mProgressSpinner != null)
{
if (enabled)
{
mProgressSpinner.setVisibility(View.GONE);
}
else
{
mProgressSpinner.setVisibility(View.VISIBLE);
}
}
if (mDialog != null)
{
mOkayButton = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
}
for (View view : new View[] { mActivitySpinner, mBundleSpinner, mDescriptionText, mPublicCheck, mOkayButton })
{
if (view != null)
{
view.setEnabled(enabled);
}
}
if (enabled)
{
mActivitySpinner.setAdapter(getActivityAdapter());
mBundleSpinner.setAdapter(getBundleAdapter());
loadBreadcrumbsPreference();
}
}
public SpinnerAdapter getActivityAdapter()
{
List<Pair<Integer, Integer>> activities = mService.getActivityList();
ArrayAdapter<Pair<Integer, Integer>> adapter = new ArrayAdapter<Pair<Integer, Integer>>(this, android.R.layout.simple_spinner_item, activities);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return adapter;
}
public SpinnerAdapter getBundleAdapter()
{
List<Pair<Integer, Integer>> bundles = mService.getBundleList();
ArrayAdapter<Pair<Integer, Integer>> adapter = new ArrayAdapter<Pair<Integer, Integer>>(this, android.R.layout.simple_spinner_item, bundles);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return adapter;
}
private ServiceConnection mConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName className, IBinder service)
{
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
setUiEnabled();
}
@Override
public void onServiceDisconnected(ComponentName arg0)
{
mService = null;
mBound = false;
}
};
private final DialogInterface.OnClickListener mTrackDescriptionDialogListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata");
Integer activityId = ((Pair<Integer, Integer>)mActivitySpinner.getSelectedItem()).second;
Integer bundleId = ((Pair<Integer, Integer>)mBundleSpinner.getSelectedItem()).second;
saveBreadcrumbsPreference(mActivitySpinner.getSelectedItemPosition(), mBundleSpinner.getSelectedItemPosition());
String description = mDescriptionText.getText().toString();
String isPublic = Boolean.toString(mPublicCheck.isChecked());
ContentValues[] metaValues = { buildContentValues(BreadcrumbsTracks.ACTIVITY_ID, activityId.toString()), buildContentValues(BreadcrumbsTracks.BUNDLE_ID, bundleId.toString()),
buildContentValues(BreadcrumbsTracks.DESCRIPTION, description), buildContentValues(BreadcrumbsTracks.ISPUBLIC, isPublic), };
getContentResolver().bulkInsert(metadataUri, metaValues);
Intent data = new Intent();
data.setData(mTrackUri);
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(Constants.NAME))
{
data.putExtra(Constants.NAME, getIntent().getExtras().getString(Constants.NAME));
}
setResult(RESULT_OK, data);
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
default:
Log.e(TAG, "Unknown option ending dialog:" + which);
break;
}
finish();
}
};
}
| Java |
/*------------------------------------------------------------------------------
** 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;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager;
import nl.sogeti.android.gpstracker.util.Constants;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
/**
* Empty Activity that pops up the dialog to name the track
*
* @version $Id$
* @author rene (c) Jul 27, 2010, Sogeti B.V.
*/
public class ControlTracking extends Activity
{
private static final int DIALOG_LOGCONTROL = 26;
private static final String TAG = "OGT.ControlTracking";
private GPSLoggerServiceManager mLoggerServiceManager;
private Button start;
private Button pause;
private Button resume;
private Button stop;
private boolean paused;
private final View.OnClickListener mLoggingControlListener = new View.OnClickListener()
{
@Override
public void onClick( View v )
{
int id = v.getId();
Intent intent = new Intent();
switch( id )
{
case R.id.logcontrol_start:
long loggerTrackId = mLoggerServiceManager.startGPSLogging( null );
// Start a naming of the track
Intent namingIntent = new Intent( ControlTracking.this, NameTrack.class );
namingIntent.setData( ContentUris.withAppendedId( Tracks.CONTENT_URI, loggerTrackId ) );
startActivity( namingIntent );
// Create data for the caller that a new track has been started
ComponentName caller = ControlTracking.this.getCallingActivity();
if( caller != null )
{
intent.setData( ContentUris.withAppendedId( Tracks.CONTENT_URI, loggerTrackId ) );
setResult( RESULT_OK, intent );
}
break;
case R.id.logcontrol_pause:
mLoggerServiceManager.pauseGPSLogging();
setResult( RESULT_OK, intent );
break;
case R.id.logcontrol_resume:
mLoggerServiceManager.resumeGPSLogging();
setResult( RESULT_OK, intent );
break;
case R.id.logcontrol_stop:
mLoggerServiceManager.stopGPSLogging();
setResult( RESULT_OK, intent );
break;
default:
setResult( RESULT_CANCELED, intent );
break;
}
finish();
}
};
private OnClickListener mDialogClickListener = new OnClickListener()
{
@Override
public void onClick( DialogInterface dialog, int which )
{
setResult( RESULT_CANCELED, new Intent() );
finish();
}
};
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
this.setVisible( false );
paused = false;
mLoggerServiceManager = new GPSLoggerServiceManager( this );
}
@Override
protected void onResume()
{
super.onResume();
mLoggerServiceManager.startup( this, new Runnable()
{
@Override
public void run()
{
showDialog( DIALOG_LOGCONTROL );
}
} );
}
@Override
protected void onPause()
{
super.onPause();
mLoggerServiceManager.shutdown( this );
paused = true;
}
@Override
protected Dialog onCreateDialog( int id )
{
Dialog dialog = null;
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch( id )
{
case DIALOG_LOGCONTROL:
builder = new AlertDialog.Builder( this );
factory = LayoutInflater.from( this );
view = factory.inflate( R.layout.logcontrol, null );
builder.setTitle( R.string.dialog_tracking_title ).
setIcon( android.R.drawable.ic_dialog_alert ).
setNegativeButton( R.string.btn_cancel, mDialogClickListener ).
setView( view );
dialog = builder.create();
start = (Button) view.findViewById( R.id.logcontrol_start );
pause = (Button) view.findViewById( R.id.logcontrol_pause );
resume = (Button) view.findViewById( R.id.logcontrol_resume );
stop = (Button) view.findViewById( R.id.logcontrol_stop );
start.setOnClickListener( mLoggingControlListener );
pause.setOnClickListener( mLoggingControlListener );
resume.setOnClickListener( mLoggingControlListener );
stop.setOnClickListener( mLoggingControlListener );
dialog.setOnDismissListener( new OnDismissListener()
{
@Override
public void onDismiss( DialogInterface dialog )
{
if( !paused )
{
finish();
}
}
});
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 )
{
switch( id )
{
case DIALOG_LOGCONTROL:
updateDialogState( mLoggerServiceManager.getLoggingState() );
break;
default:
break;
}
super.onPrepareDialog( id, dialog );
}
private void updateDialogState( int state )
{
switch( state )
{
case Constants.STOPPED:
start.setEnabled( true );
pause.setEnabled( false );
resume.setEnabled( false );
stop.setEnabled( false );
break;
case Constants.LOGGING:
start.setEnabled( false );
pause.setEnabled( true );
resume.setEnabled( false );
stop.setEnabled( true );
break;
case Constants.PAUSED:
start.setEnabled( false );
pause.setEnabled( false );
resume.setEnabled( true );
stop.setEnabled( true );
break;
default:
Log.w( TAG, String.format( "State %d of logging, enabling and hope for the best....", state ) );
start.setEnabled( false );
pause.setEnabled( false );
resume.setEnabled( false );
stop.setEnabled( false );
break;
}
}
}
| Java |
/*------------------------------------------------------------------------------
** 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;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager;
import nl.sogeti.android.gpstracker.util.Constants;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Empty Activity that pops up the dialog to add a note to the most current
* point in the logger service
*
* @version $Id$
* @author rene (c) Jul 27, 2010, Sogeti B.V.
*/
public class InsertNote extends Activity
{
private static final int DIALOG_INSERTNOTE = 27;
private static final String TAG = "OGT.InsertNote";
private static final int MENU_PICTURE = 9;
private static final int MENU_VOICE = 11;
private static final int MENU_VIDEO = 12;
private static final int DIALOG_TEXT = 32;
private static final int DIALOG_NAME = 33;
private GPSLoggerServiceManager mLoggerServiceManager;
/**
* Action to take when the LoggerService is bound
*/
private Runnable mServiceBindAction;
private boolean paused;
private Button name;
private Button text;
private Button voice;
private Button picture;
private Button video;
private EditText mNoteNameView;
private EditText mNoteTextView;
private final OnClickListener mNoteTextDialogListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
String noteText = mNoteTextView.getText().toString();
Calendar c = Calendar.getInstance();
String newName = String.format("Textnote_%tY-%tm-%td_%tH%tM%tS.txt", c, c, c, c, c, c);
File file = new File(Constants.getSdCardDirectory(InsertNote.this) + newName);
FileWriter filewriter = null;
try
{
file.getParentFile().mkdirs();
file.createNewFile();
filewriter = new FileWriter(file);
filewriter.append(noteText);
filewriter.flush();
}
catch (IOException e)
{
Log.e(TAG, "Note storing failed", e);
CharSequence text = e.getLocalizedMessage();
Toast toast = Toast.makeText(InsertNote.this, text, Toast.LENGTH_LONG);
toast.show();
}
finally
{
if (filewriter != null)
{
try
{
filewriter.close();
}
catch (IOException e)
{ /* */
}
}
}
InsertNote.this.mLoggerServiceManager.storeMediaUri(Uri.fromFile(file));
setResult(RESULT_CANCELED, new Intent());
finish();
}
};
private final OnClickListener mNoteNameDialogListener = new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
String name = mNoteNameView.getText().toString();
Uri media = Uri.withAppendedPath(Constants.NAME_URI, Uri.encode(name));
InsertNote.this.mLoggerServiceManager.storeMediaUri(media);
setResult(RESULT_CANCELED, new Intent());
finish();
}
};
private final View.OnClickListener mNoteInsertListener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
int id = v.getId();
switch (id)
{
case R.id.noteinsert_picture:
addPicture();
break;
case R.id.noteinsert_video:
addVideo();
break;
case R.id.noteinsert_voice:
addVoice();
break;
case R.id.noteinsert_text:
showDialog(DIALOG_TEXT);
break;
case R.id.noteinsert_name:
showDialog(DIALOG_NAME);
break;
default:
setResult(RESULT_CANCELED, new Intent());
finish();
break;
}
}
};
private OnClickListener mDialogClickListener = new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
setResult(RESULT_CANCELED, new Intent());
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setVisible(false);
paused = false;
mLoggerServiceManager = new GPSLoggerServiceManager(this);
}
@Override
protected void onResume()
{
super.onResume();
if (mServiceBindAction == null)
{
mServiceBindAction = new Runnable()
{
@Override
public void run()
{
showDialog(DIALOG_INSERTNOTE);
}
};
}
;
mLoggerServiceManager.startup(this, mServiceBindAction);
}
@Override
protected void onPause()
{
super.onPause();
mLoggerServiceManager.shutdown(this);
paused = true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int,
* android.content.Intent)
*/
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
mServiceBindAction = new Runnable()
{
@Override
public void run()
{
if (resultCode != RESULT_CANCELED)
{
File file;
Uri uri;
File newFile;
String newName;
Uri fileUri;
android.net.Uri.Builder builder;
boolean isLocal = false;
switch (requestCode)
{
case MENU_PICTURE:
file = new File(Constants.getSdCardTmpFile(InsertNote.this));
Calendar c = Calendar.getInstance();
newName = String.format("Picture_%tY-%tm-%td_%tH%tM%tS.jpg", c, c, c, c, c, c);
newFile = new File(Constants.getSdCardDirectory(InsertNote.this) + newName);
file.getParentFile().mkdirs();
isLocal = file.renameTo(newFile); //
if (!isLocal)
{
Log.w(TAG, "Failed rename will try copy image: " + file.getAbsolutePath());
isLocal = copyFile(file, newFile);
}
if (isLocal)
{
System.gc();
Options opts = new Options();
opts.inJustDecodeBounds = true;
Bitmap bm = BitmapFactory.decodeFile(newFile.getAbsolutePath(), opts);
String height, width;
if (bm != null)
{
height = Integer.toString(bm.getHeight());
width = Integer.toString(bm.getWidth());
}
else
{
height = Integer.toString(opts.outHeight);
width = Integer.toString(opts.outWidth);
}
bm = null;
builder = new Uri.Builder();
fileUri = builder.scheme("file").appendEncodedPath("/").appendEncodedPath(newFile.getAbsolutePath())
.appendQueryParameter("width", width).appendQueryParameter("height", height).build();
InsertNote.this.mLoggerServiceManager.storeMediaUri(fileUri);
}
else
{
Log.e(TAG, "Failed either rename or copy image: " + file.getAbsolutePath());
}
break;
case MENU_VIDEO:
file = new File(Constants.getSdCardTmpFile(InsertNote.this));
c = Calendar.getInstance();
newName = String.format("Video_%tY%tm%td_%tH%tM%tS.3gp", c, c, c, c, c, c);
newFile = new File(Constants.getSdCardDirectory(InsertNote.this) + newName);
file.getParentFile().mkdirs();
isLocal = file.renameTo(newFile);
if (!isLocal)
{
Log.w(TAG, "Failed rename will try copy video: " + file.getAbsolutePath());
isLocal = copyFile(file, newFile);
}
if (isLocal)
{
builder = new Uri.Builder();
fileUri = builder.scheme("file").appendPath(newFile.getAbsolutePath()).build();
InsertNote.this.mLoggerServiceManager.storeMediaUri(fileUri);
}
else
{
Log.e(TAG, "Failed either rename or copy video: " + file.getAbsolutePath());
}
break;
case MENU_VOICE:
uri = Uri.parse(intent.getDataString());
InsertNote.this.mLoggerServiceManager.storeMediaUri(uri);
break;
default:
Log.e(TAG, "Returned form unknow activity: " + requestCode);
break;
}
}
else
{
Log.w(TAG, "Received unexpected resultcode " + resultCode);
}
setResult(resultCode, new Intent());
finish();
}
};
}
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
LayoutInflater factory = null;
View view = null;
Builder builder = null;
switch (id)
{
case DIALOG_INSERTNOTE:
builder = new AlertDialog.Builder(this);
factory = LayoutInflater.from(this);
view = factory.inflate(R.layout.insertnote, null);
builder.setTitle(R.string.menu_insertnote).setIcon(android.R.drawable.ic_dialog_alert).setNegativeButton(R.string.btn_cancel, mDialogClickListener)
.setView(view);
dialog = builder.create();
name = (Button) view.findViewById(R.id.noteinsert_name);
text = (Button) view.findViewById(R.id.noteinsert_text);
voice = (Button) view.findViewById(R.id.noteinsert_voice);
picture = (Button) view.findViewById(R.id.noteinsert_picture);
video = (Button) view.findViewById(R.id.noteinsert_video);
name.setOnClickListener(mNoteInsertListener);
text.setOnClickListener(mNoteInsertListener);
voice.setOnClickListener(mNoteInsertListener);
picture.setOnClickListener(mNoteInsertListener);
video.setOnClickListener(mNoteInsertListener);
dialog.setOnDismissListener(new OnDismissListener()
{
@Override
public void onDismiss(DialogInterface dialog)
{
if (!paused)
{
finish();
}
}
});
return dialog;
case DIALOG_TEXT:
builder = new AlertDialog.Builder(this);
factory = LayoutInflater.from(this);
view = factory.inflate(R.layout.notetextdialog, null);
mNoteTextView = (EditText) view.findViewById(R.id.notetext);
builder.setTitle(R.string.dialog_notetext_title).setMessage(R.string.dialog_notetext_message).setIcon(android.R.drawable.ic_dialog_map)
.setPositiveButton(R.string.btn_okay, mNoteTextDialogListener).setNegativeButton(R.string.btn_cancel, null).setView(view);
dialog = builder.create();
return dialog;
case DIALOG_NAME:
builder = new AlertDialog.Builder(this);
factory = LayoutInflater.from(this);
view = factory.inflate(R.layout.notenamedialog, null);
mNoteNameView = (EditText) view.findViewById(R.id.notename);
builder.setTitle(R.string.dialog_notename_title).setMessage(R.string.dialog_notename_message).setIcon(android.R.drawable.ic_dialog_map)
.setPositiveButton(R.string.btn_okay, mNoteNameDialogListener).setNegativeButton(R.string.btn_cancel, null).setView(view);
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)
{
switch (id)
{
case DIALOG_INSERTNOTE:
boolean prepared = mLoggerServiceManager.isMediaPrepared() && mLoggerServiceManager.getLoggingState() == Constants.LOGGING;
name = (Button) dialog.findViewById(R.id.noteinsert_name);
text = (Button) dialog.findViewById(R.id.noteinsert_text);
voice = (Button) dialog.findViewById(R.id.noteinsert_voice);
picture = (Button) dialog.findViewById(R.id.noteinsert_picture);
video = (Button) dialog.findViewById(R.id.noteinsert_video);
name.setEnabled(prepared);
text.setEnabled(prepared);
voice.setEnabled(prepared);
picture.setEnabled(prepared);
video.setEnabled(prepared);
break;
default:
break;
}
super.onPrepareDialog(id, dialog);
}
/***
* Collecting additional data
*/
private void addPicture()
{
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Constants.getSdCardTmpFile(this));
// Log.d( TAG, "Picture requested at: " + file );
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
i.putExtra(android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(i, MENU_PICTURE);
}
/***
* Collecting additional data
*/
private void addVideo()
{
Intent i = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
File file = new File(Constants.getSdCardTmpFile(this));
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
i.putExtra(android.provider.MediaStore.EXTRA_VIDEO_QUALITY, 1);
try
{
startActivityForResult(i, MENU_VIDEO);
}
catch (ActivityNotFoundException e)
{
Log.e(TAG, "Unable to start Activity to record video", e);
}
}
private void addVoice()
{
Intent intent = new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION);
try
{
startActivityForResult(intent, MENU_VOICE);
}
catch (ActivityNotFoundException e)
{
Log.e(TAG, "Unable to start Activity to record audio", e);
}
}
private static boolean copyFile(File fileIn, File fileOut)
{
boolean succes = false;
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream(fileIn);
out = new FileOutputStream(fileOut);
byte[] buf = new byte[8192];
int i = 0;
while ((i = in.read(buf)) != -1)
{
out.write(buf, 0, i);
}
succes = true;
}
catch (IOException e)
{
Log.e(TAG, "File copy failed", e);
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
Log.w(TAG, "File close after copy failed", e);
}
}
if (in != null)
{
try
{
out.close();
}
catch (IOException e)
{
Log.w(TAG, "File close after copy failed", e);
}
}
}
return succes;
}
}
| Java |
/*------------------------------------------------------------------------------
** 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;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import nl.sogeti.android.gpstracker.R;
import nl.sogeti.android.gpstracker.actions.tasks.GpxCreator;
import nl.sogeti.android.gpstracker.actions.tasks.GpxSharing;
import nl.sogeti.android.gpstracker.actions.tasks.JogmapSharing;
import nl.sogeti.android.gpstracker.actions.tasks.KmzCreator;
import nl.sogeti.android.gpstracker.actions.tasks.KmzSharing;
import nl.sogeti.android.gpstracker.actions.tasks.OsmSharing;
import nl.sogeti.android.gpstracker.actions.utils.ProgressListener;
import nl.sogeti.android.gpstracker.actions.utils.StatisticsCalulator;
import nl.sogeti.android.gpstracker.actions.utils.StatisticsDelegate;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService;
import nl.sogeti.android.gpstracker.breadcrumbs.BreadcrumbsService.LocalBinder;
import nl.sogeti.android.gpstracker.db.GPStracking.Tracks;
import nl.sogeti.android.gpstracker.util.Constants;
import nl.sogeti.android.gpstracker.util.UnitsI18n;
import nl.sogeti.android.gpstracker.viewer.map.LoggerMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Spinner;
import android.widget.Toast;
public class ShareTrack extends Activity implements StatisticsDelegate
{
private static final String TAG = "OGT.ShareTrack";
private static final int EXPORT_TYPE_KMZ = 0;
private static final int EXPORT_TYPE_GPX = 1;
private static final int EXPORT_TYPE_TEXTLINE = 2;
private static final int EXPORT_TARGET_SAVE = 0;
private static final int EXPORT_TARGET_SEND = 1;
private static final int EXPORT_TARGET_JOGRUN = 2;
private static final int EXPORT_TARGET_OSM = 3;
private static final int EXPORT_TARGET_BREADCRUMBS = 4;
private static final int EXPORT_TARGET_TWITTER = 0;
private static final int EXPORT_TARGET_SMS = 1;
private static final int EXPORT_TARGET_TEXT = 2;
private static final int PROGRESS_STEPS = 10;
private static final int DIALOG_ERROR = Menu.FIRST + 28;
private static final int DIALOG_CONNECTBREADCRUMBS = Menu.FIRST + 29;
private static final int DESCRIBE = 312;
private static File sTempBitmap;
private RemoteViews mContentView;
private int barProgress = 0;
private Notification mNotification;
private NotificationManager mNotificationManager;
private EditText mFileNameView;
private EditText mTweetView;
private Spinner mShareTypeSpinner;
private Spinner mShareTargetSpinner;
private Uri mTrackUri;
private BreadcrumbsService mService;
boolean mBound = false;
private String mErrorDialogMessage;
private Throwable mErrorDialogException;
private ImageView mImageView;
private ImageButton mCloseImageView;
private Uri mImageUri;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedialog);
Intent service = new Intent(this, BreadcrumbsService.class);
startService(service);
mTrackUri = getIntent().getData();
mFileNameView = (EditText) findViewById(R.id.fileNameField);
mTweetView = (EditText) findViewById(R.id.tweetField);
mImageView = (ImageView) findViewById(R.id.imageView);
mCloseImageView = (ImageButton) findViewById(R.id.closeImageView);
mShareTypeSpinner = (Spinner) findViewById(R.id.shareTypeSpinner);
ArrayAdapter<CharSequence> shareTypeAdapter = ArrayAdapter.createFromResource(this, R.array.sharetype_choices, android.R.layout.simple_spinner_item);
shareTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mShareTypeSpinner.setAdapter(shareTypeAdapter);
mShareTargetSpinner = (Spinner) findViewById(R.id.shareTargetSpinner);
mShareTargetSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView< ? > arg0, View arg1, int position, long arg3)
{
if (mShareTypeSpinner.getSelectedItemPosition() == EXPORT_TYPE_GPX && position == EXPORT_TARGET_BREADCRUMBS)
{
boolean authorized = mService.isAuthorized();
if (!authorized)
{
showDialog(DIALOG_CONNECTBREADCRUMBS);
}
}
else if (mShareTypeSpinner.getSelectedItemPosition() == EXPORT_TYPE_TEXTLINE && position != EXPORT_TARGET_SMS)
{
readScreenBitmap();
}
else
{
removeScreenBitmap();
}
}
@Override
public void onNothingSelected(AdapterView< ? > arg0)
{ /* NOOP */
}
});
mShareTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView< ? > arg0, View arg1, int position, long arg3)
{
adjustTargetToType(position);
}
@Override
public void onNothingSelected(AdapterView< ? > arg0)
{ /* NOOP */
}
});
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int lastType = prefs.getInt(Constants.EXPORT_TYPE, EXPORT_TYPE_KMZ);
mShareTypeSpinner.setSelection(lastType);
adjustTargetToType(lastType);
mFileNameView.setText(queryForTrackName(getContentResolver(), mTrackUri));
Button okay = (Button) findViewById(R.id.okayshare_button);
okay.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setEnabled(false);
share();
}
});
Button cancel = (Button) findViewById(R.id.cancelshare_button);
cancel.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
v.setEnabled(false);
ShareTrack.this.finish();
}
});
}
@Override
protected void onStart()
{
super.onStart();
Intent intent = new Intent(this, BreadcrumbsService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onResume()
{
super.onResume();
// Upgrade from stored OSM username/password to OAuth authorization
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.contains(Constants.OSM_USERNAME) || prefs.contains(Constants.OSM_PASSWORD))
{
Editor editor = prefs.edit();
editor.remove(Constants.OSM_USERNAME);
editor.remove(Constants.OSM_PASSWORD);
editor.commit();
}
findViewById(R.id.okayshare_button).setEnabled(true);
findViewById(R.id.cancelshare_button).setEnabled(true);
}
@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);
}
super.onDestroy();
}
/**
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
Builder builder = null;
switch (id)
{
case DIALOG_ERROR:
builder = new AlertDialog.Builder(this);
String exceptionMessage = mErrorDialogException == null ? "" : " (" + mErrorDialogException.getMessage() + ") ";
builder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(android.R.string.dialog_alert_title).setMessage(mErrorDialogMessage + exceptionMessage)
.setNeutralButton(android.R.string.cancel, null);
dialog = builder.create();
return dialog;
case DIALOG_CONNECTBREADCRUMBS:
builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.dialog_breadcrumbsconnect).setMessage(R.string.dialog_breadcrumbsconnect_message).setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_okay, mBreadcrumbsDialogListener).setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
return dialog;
default:
return super.onCreateDialog(id);
}
}
/**
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
*/
@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
super.onPrepareDialog(id, dialog);
AlertDialog alert;
switch (id)
{
case DIALOG_ERROR:
alert = (AlertDialog) dialog;
String exceptionMessage = mErrorDialogException == null ? "" : " (" + mErrorDialogException.getMessage() + ") ";
alert.setMessage(mErrorDialogMessage + exceptionMessage);
break;
}
}
private void setGpxExportTargets()
{
ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharegpxtarget_choices, android.R.layout.simple_spinner_item);
shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mShareTargetSpinner.setAdapter(shareTargetAdapter);
int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_GPXTARGET, EXPORT_TARGET_SEND);
mShareTargetSpinner.setSelection(lastTarget);
removeScreenBitmap();
}
private void setKmzExportTargets()
{
ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharekmztarget_choices, android.R.layout.simple_spinner_item);
shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mShareTargetSpinner.setAdapter(shareTargetAdapter);
int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_KMZTARGET, EXPORT_TARGET_SEND);
mShareTargetSpinner.setSelection(lastTarget);
removeScreenBitmap();
}
private void setTextLineExportTargets()
{
ArrayAdapter<CharSequence> shareTargetAdapter = ArrayAdapter.createFromResource(this, R.array.sharetexttarget_choices, android.R.layout.simple_spinner_item);
shareTargetAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mShareTargetSpinner.setAdapter(shareTargetAdapter);
int lastTarget = PreferenceManager.getDefaultSharedPreferences(this).getInt(Constants.EXPORT_TXTTARGET, EXPORT_TARGET_TWITTER);
mShareTargetSpinner.setSelection(lastTarget);
}
private void share()
{
String chosenFileName = mFileNameView.getText().toString();
String textLine = mTweetView.getText().toString();
int type = (int) mShareTypeSpinner.getSelectedItemId();
int target = (int) mShareTargetSpinner.getSelectedItemId();
Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putInt(Constants.EXPORT_TYPE, type);
switch (type)
{
case EXPORT_TYPE_KMZ:
editor.putInt(Constants.EXPORT_KMZTARGET, target);
editor.commit();
exportKmz(chosenFileName, target);
break;
case EXPORT_TYPE_GPX:
editor.putInt(Constants.EXPORT_GPXTARGET, target);
editor.commit();
exportGpx(chosenFileName, target);
break;
case EXPORT_TYPE_TEXTLINE:
editor.putInt(Constants.EXPORT_TXTTARGET, target);
editor.commit();
exportTextLine(textLine, target);
break;
default:
Log.e(TAG, "Failed to determine sharing type" + type);
break;
}
}
protected void exportKmz(String chosenFileName, int target)
{
switch (target)
{
case EXPORT_TARGET_SEND:
new KmzSharing(this, mTrackUri, chosenFileName, new ShareProgressListener(chosenFileName)).execute();
break;
case EXPORT_TARGET_SAVE:
new KmzCreator(this, mTrackUri, chosenFileName, new ShareProgressListener(chosenFileName)).execute();
break;
default:
Log.e(TAG, "Unable to determine target for sharing KMZ " + target);
break;
}
ShareTrack.this.finish();
}
protected void exportGpx(String chosenFileName, int target)
{
switch (target)
{
case EXPORT_TARGET_SAVE:
new GpxCreator(this, mTrackUri, chosenFileName, true, new ShareProgressListener(chosenFileName)).execute();
ShareTrack.this.finish();
break;
case EXPORT_TARGET_SEND:
new GpxSharing(this, mTrackUri, chosenFileName, true, new ShareProgressListener(chosenFileName)).execute();
ShareTrack.this.finish();
break;
case EXPORT_TARGET_JOGRUN:
new JogmapSharing(this, mTrackUri, chosenFileName, false, new ShareProgressListener(chosenFileName)).execute();
ShareTrack.this.finish();
break;
case EXPORT_TARGET_OSM:
new OsmSharing(this, mTrackUri, false, new ShareProgressListener(OsmSharing.OSM_FILENAME)).execute();
ShareTrack.this.finish();
break;
case EXPORT_TARGET_BREADCRUMBS:
sendToBreadcrumbs(mTrackUri, chosenFileName);
break;
default:
Log.e(TAG, "Unable to determine target for sharing GPX " + target);
break;
}
}
protected void exportTextLine(String message, int target)
{
String subject = "Open GPS Tracker";
switch (target)
{
case EXPORT_TARGET_TWITTER:
sendTweet(message);
break;
case EXPORT_TARGET_SMS:
sendSMS(message);
ShareTrack.this.finish();
break;
case EXPORT_TARGET_TEXT:
sentGenericText(subject, message);
ShareTrack.this.finish();
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != RESULT_CANCELED)
{
String name;
switch (requestCode)
{
case DESCRIBE:
Uri trackUri = data.getData();
if (data.getExtras() != null && data.getExtras().containsKey(Constants.NAME))
{
name = data.getExtras().getString(Constants.NAME);
}
else
{
name = "shareToGobreadcrumbs";
}
mService.startUploadTask(this, new ShareProgressListener(name), trackUri, name);
finish();
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
}
private void sendTweet(String tweet)
{
final Intent intent = findTwitterClient();
intent.putExtra(Intent.EXTRA_TEXT, tweet);
if (mImageUri != null)
{
intent.putExtra(Intent.EXTRA_STREAM, mImageUri);
}
startActivity(intent);
ShareTrack.this.finish();
}
private void sendSMS(String msg)
{
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
intent.putExtra("sms_body", msg);
startActivity(intent);
}
private void sentGenericText(String subject, String msg)
{
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, msg);
if (mImageUri != null)
{
intent.putExtra(Intent.EXTRA_STREAM, mImageUri);
}
startActivity(intent);
}
private void sendToBreadcrumbs(Uri mTrackUri, String chosenFileName)
{
// Start a description of the track
Intent namingIntent = new Intent(this, DescribeTrack.class);
namingIntent.setData(mTrackUri);
namingIntent.putExtra(Constants.NAME, chosenFileName);
startActivityForResult(namingIntent, DESCRIBE);
}
private Intent findTwitterClient()
{
final String[] twitterApps = {
// package // name
"com.twitter.android", // official
"com.twidroid", // twidroyd
"com.handmark.tweetcaster", // Tweecaster
"com.thedeck.android" // TweetDeck
};
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.setType("text/plain");
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (int i = 0; i < twitterApps.length; i++)
{
for (ResolveInfo resolveInfo : list)
{
String p = resolveInfo.activityInfo.packageName;
if (p != null && p.startsWith(twitterApps[i]))
{
tweetIntent.setPackage(p);
}
}
}
return tweetIntent;
}
private void createTweetText()
{
StatisticsCalulator calculator = new StatisticsCalulator(this, new UnitsI18n(this), this);
findViewById(R.id.tweet_progress).setVisibility(View.VISIBLE);
calculator.execute(mTrackUri);
}
@Override
public void finishedCalculations(StatisticsCalulator calculated)
{
String name = queryForTrackName(getContentResolver(), mTrackUri);
String distString = calculated.getDistanceText();
String avgSpeed = calculated.getAvgSpeedText();
String duration = calculated.getDurationText();
String tweetText = String.format(getString(R.string.tweettext, name, distString, avgSpeed, duration));
if (mTweetView.getText().toString().equals(""))
{
mTweetView.setText(tweetText);
}
findViewById(R.id.tweet_progress).setVisibility(View.GONE);
}
private void adjustTargetToType(int position)
{
switch (position)
{
case EXPORT_TYPE_KMZ:
setKmzExportTargets();
mFileNameView.setVisibility(View.VISIBLE);
mTweetView.setVisibility(View.GONE);
break;
case EXPORT_TYPE_GPX:
setGpxExportTargets();
mFileNameView.setVisibility(View.VISIBLE);
mTweetView.setVisibility(View.GONE);
break;
case EXPORT_TYPE_TEXTLINE:
setTextLineExportTargets();
mFileNameView.setVisibility(View.GONE);
mTweetView.setVisibility(View.VISIBLE);
createTweetText();
break;
default:
break;
}
}
public static void sendFile(Context context, Uri fileUri, String fileContentType, String body)
{
Intent sendActionIntent = new Intent(Intent.ACTION_SEND);
sendActionIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.email_subject));
sendActionIntent.putExtra(Intent.EXTRA_TEXT, body);
sendActionIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
sendActionIntent.setType(fileContentType);
context.startActivity(Intent.createChooser(sendActionIntent, context.getString(R.string.sender_chooser)));
}
public static String queryForTrackName(ContentResolver resolver, Uri trackUri)
{
Cursor trackCursor = null;
String name = null;
try
{
trackCursor = resolver.query(trackUri, new String[] { Tracks.NAME }, null, null, null);
if (trackCursor.moveToFirst())
{
name = trackCursor.getString(0);
}
}
finally
{
if (trackCursor != null)
{
trackCursor.close();
}
}
return name;
}
public static Uri storeScreenBitmap(Bitmap bm)
{
Uri fileUri = null;
FileOutputStream stream = null;
try
{
clearScreenBitmap();
sTempBitmap = File.createTempFile("shareimage", ".png");
fileUri = Uri.fromFile(sTempBitmap);
stream = new FileOutputStream(sTempBitmap);
bm.compress(CompressFormat.PNG, 100, stream);
}
catch (IOException e)
{
Log.e(TAG, "Bitmap extra storing failed", e);
}
finally
{
try
{
if (stream != null)
{
stream.close();
}
}
catch (IOException e)
{
Log.e(TAG, "Bitmap extra close failed", e);
}
}
return fileUri;
}
public static void clearScreenBitmap()
{
if (sTempBitmap != null && sTempBitmap.exists())
{
sTempBitmap.delete();
sTempBitmap = null;
}
}
private void readScreenBitmap()
{
mImageView.setVisibility(View.GONE);
mCloseImageView.setVisibility(View.GONE);
if (getIntent().getExtras() != null && getIntent().hasExtra(Intent.EXTRA_STREAM))
{
mImageUri = getIntent().getExtras().getParcelable(Intent.EXTRA_STREAM);
if (mImageUri != null)
{
InputStream is = null;
try
{
is = getContentResolver().openInputStream(mImageUri);
mImageView.setImageBitmap(BitmapFactory.decodeStream(is));
mImageView.setVisibility(View.VISIBLE);
mCloseImageView.setVisibility(View.VISIBLE);
mCloseImageView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
removeScreenBitmap();
}
});
}
catch (FileNotFoundException e)
{
Log.e(TAG, "Failed reading image from file", e);
}
finally
{
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
Log.e(TAG, "Failed close image from file", e);
}
}
}
}
}
}
private void removeScreenBitmap()
{
mImageView.setVisibility(View.GONE);
mCloseImageView.setVisibility(View.GONE);
mImageUri = null;
}
private ServiceConnection mConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName className, IBinder service)
{
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0)
{
mBound = false;
mService = null;
}
};
private OnClickListener mBreadcrumbsDialogListener = new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
mService.collectBreadcrumbsOauthToken();
}
};
public class ShareProgressListener implements ProgressListener
{
private String mFileName;
private int mProgress;
public ShareProgressListener(String sharename)
{
mFileName = sharename;
}
public void startNotification()
{
String ns = Context.NOTIFICATION_SERVICE;
mNotificationManager = (NotificationManager) ShareTrack.this.getSystemService(ns);
int icon = android.R.drawable.ic_menu_save;
CharSequence tickerText = getString(R.string.ticker_saving) + "\"" + mFileName + "\"";
mNotification = new Notification();
PendingIntent contentIntent = PendingIntent.getActivity(ShareTrack.this, 0, new Intent(ShareTrack.this, LoggerMap.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_UPDATE_CURRENT);
mNotification.contentIntent = contentIntent;
mNotification.tickerText = tickerText;
mNotification.icon = icon;
mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
mContentView = new RemoteViews(getPackageName(), R.layout.savenotificationprogress);
mContentView.setImageViewResource(R.id.icon, icon);
mContentView.setTextViewText(R.id.progresstext, tickerText);
mNotification.contentView = mContentView;
}
private void updateNotification()
{
// Log.d( "TAG", "Progress " + progress + " of " + goal );
if (mProgress > 0 && mProgress < Window.PROGRESS_END)
{
if ((mProgress * PROGRESS_STEPS) / Window.PROGRESS_END != barProgress)
{
barProgress = (mProgress * PROGRESS_STEPS) / Window.PROGRESS_END;
mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, false);
mNotificationManager.notify(R.layout.savenotificationprogress, mNotification);
}
}
else if (mProgress == 0)
{
mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, true);
mNotificationManager.notify(R.layout.savenotificationprogress, mNotification);
}
else if (mProgress >= Window.PROGRESS_END)
{
mContentView.setProgressBar(R.id.progress, Window.PROGRESS_END, mProgress, false);
mNotificationManager.notify(R.layout.savenotificationprogress, mNotification);
}
}
public void endNotification(Uri file)
{
mNotificationManager.cancel(R.layout.savenotificationprogress);
}
@Override
public void setIndeterminate(boolean indeterminate)
{
Log.w(TAG, "Unsupported indeterminate progress display");
}
@Override
public void started()
{
startNotification();
}
@Override
public void setProgress(int value)
{
mProgress = value;
updateNotification();
}
@Override
public void finished(Uri result)
{
endNotification(result);
}
@Override
public void showError(String task, String errorDialogMessage, Exception errorDialogException)
{
endNotification(null);
mErrorDialogMessage = errorDialogMessage;
mErrorDialogException = errorDialogException;
if (!isFinishing())
{
showDialog(DIALOG_ERROR);
}
else
{
Toast toast = Toast.makeText(ShareTrack.this, errorDialogMessage, Toast.LENGTH_LONG);
toast.show();
}
}
}
}
| Java |
/*------------------------------------------------------------------------------
** 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);
}
}
} | Java |
/*------------------------------------------------------------------------------
** 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 );
}
}
}
} | Java |
/*------------------------------------------------------------------------------
** 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);
}
}
| Java |
/*------------------------------------------------------------------------------
** 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");
}
}
} | Java |
/*------------------------------------------------------------------------------
** 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);
}
} | Java |
/*------------------------------------------------------------------------------
** 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 + "]";
}
}
| Java |
/*------------------------------------------------------------------------------
** 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);
}
}
} | Java |
/*------------------------------------------------------------------------------
** 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);
}
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.