code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
package il.yrtimid.osm.osmpoi.domain;
/**
* @author yrtimid
*
*/
public class Point {
Double latitude;
Double longitude;
int radius;
public Point(Point point) {
this.latitude = point.latitude;
this.longitude = point.longitude;
}
public Point(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public Double getLatitude() {
return latitude;
}
public Double getLongitude() {
return longitude;
}
/**
* @param latitude the latitude to set
*/
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
/**
* @param longitude the longitude to set
*/
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
}
| Java |
/** Automatically generated file. DO NOT MODIFY */
package il.yrtimid.osm.osmpoi;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
import il.yrtimid.osm.osmpoi.OsmPoiApplication.Config;
import il.yrtimid.osm.osmpoi.dal.DbSearcher;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.searchparameters.BaseSearchParameter;
import il.yrtimid.osm.osmpoi.searchparameters.SearchAround;
import il.yrtimid.osm.osmpoi.searchparameters.SearchById;
import il.yrtimid.osm.osmpoi.searchparameters.SearchByKeyValue;
import il.yrtimid.osm.osmpoi.searchparameters.SearchByParentId;
import android.content.Context;
/**
* @author yrtimid
*
*/
public class DBSearchSource implements ISearchSource {
//private Context context;
private DbSearcher poiDb;
private DbSearcher addressDb;
public static ISearchSource create(Context context){
if (Config.getPoiDbLocation() != null && Config.getAddressDbLocation() != null)
return new DBSearchSource(context);
else
return null;
}
protected DBSearchSource(Context context){
//this.context = context;
poiDb = OsmPoiApplication.databases.getPoiSearcherDb();
addressDb = OsmPoiApplication.databases.getAddressSearcherDb();
}
@Override
public void close(){
/*
if (poiDb != null)
poiDb.close();
if (addressDb != null)
addressDb.close();
*/
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.ISearchSource#search(il.yrtimid.osm.osmpoi.searchparameters.BaseSearchParameter, il.yrtimid.osm.osmpoi.SearchPipe, il.yrtimid.osm.osmpoi.CancelFlag)
*/
@Override
public void search(BaseSearchParameter search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
if (search instanceof SearchByKeyValue){
getByDistanceAndKeyValue((SearchByKeyValue)search, newItemNotifier, cancel);
}else if (search instanceof SearchAround){
getByDistance((SearchAround)search, newItemNotifier, cancel);
}else if (search instanceof SearchByParentId){
getByParentId((SearchByParentId)search, newItemNotifier, cancel);
}else if (search instanceof SearchById){
getById((SearchById)search, newItemNotifier, cancel);
}
}
protected void getByDistanceAndKeyValue(SearchByKeyValue search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
poiDb.findAroundPlaceByTag(search, newItemNotifier, cancel);
}
protected void getByDistance(SearchAround search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
poiDb.findAroundPlace(search, newItemNotifier, cancel);
}
// /* (non-Javadoc)
// * @see il.yrtimid.osm.osmpoi.SearchSource#getSupportsCancel()
// */
// @Override
// public boolean isSupportsCancel() {
// return true;
// }
public String getName(){
return "Offline search";
}
protected void getById(SearchById search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
poiDb.findById(search, newItemNotifier, cancel);
}
protected void getByParentId(SearchByParentId search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
poiDb.findByParentId(search, newItemNotifier, cancel);
}
}
| Java |
package il.yrtimid.osm.osmpoi.xml;
import java.util.ArrayList;
import java.util.List;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
public class EntityListSink implements Sink {
List<Entity> entities = new ArrayList<Entity>();
@Override
public void complete() {
}
@Override
public void release() {
}
@Override
public void process(Entity entity) {
entities.add(entity);
}
public List<Entity> getEntities() {
return entities;
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.xml;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openstreetmap.osmosis.core.OsmosisRuntimeException;
import org.openstreetmap.osmosis.xml.v0_6.impl.MemberTypeParser;
import org.openstreetmap.osmosis.xml.v0_6.impl.XmlConstants;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* Reads the contents of an osm file using a Stax parser.
*
* @author Jiri Klement
* @author Brett Henderson
*/
public class FastXmlParser {
private static final String ELEMENT_NAME_BOUND = "bound";
private static final String ELEMENT_NAME_NODE = "node";
private static final String ELEMENT_NAME_WAY = "way";
private static final String ELEMENT_NAME_RELATION = "relation";
private static final String ELEMENT_NAME_TAG = "tag";
private static final String ELEMENT_NAME_NODE_REFERENCE = "nd";
private static final String ELEMENT_NAME_MEMBER = "member";
private static final String ATTRIBUTE_NAME_ID = "id";
private static final String ATTRIBUTE_NAME_VERSION = "version";
// private static final String ATTRIBUTE_NAME_TIMESTAMP = "timestamp";
// private static final String ATTRIBUTE_NAME_USER_ID = "uid";
// private static final String ATTRIBUTE_NAME_USER = "user";
// private static final String ATTRIBUTE_NAME_CHANGESET_ID = "changeset";
private static final String ATTRIBUTE_NAME_LATITUDE = "lat";
private static final String ATTRIBUTE_NAME_LONGITUDE = "lon";
private static final String ATTRIBUTE_NAME_KEY = "k";
private static final String ATTRIBUTE_NAME_VALUE = "v";
private static final String ATTRIBUTE_NAME_REF = "ref";
private static final String ATTRIBUTE_NAME_TYPE = "type";
private static final String ATTRIBUTE_NAME_ROLE = "role";
// private static final String ATTRIBUTE_NAME_BOX = "box";
// private static final String ATTRIBUTE_NAME_ORIGIN = "origin";
private static final Logger LOG = Logger.getLogger(FastXmlParser.class.getName());
/**
* Creates a new instance.
*
* @param sink
* The sink receiving all output data.
* @throws XmlPullParserException
*/
public FastXmlParser(Sink sink) throws XmlPullParserException {
this.sink = sink;
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
reader = factory.newPullParser();
memberTypeParser = new MemberTypeParser();
}
private final XmlPullParser reader;
private final Sink sink;
private final MemberTypeParser memberTypeParser;
/**
* Reads all data from the file and send it to the sink.
*/
public void parseStream(InputStream inputStream) {
try {
reader.setInput(inputStream, null);
readOsm();
sink.complete();
} catch (Exception e) {
throw new OsmosisRuntimeException("Unable to read XML stream.", e);
} finally {
sink.release();
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
LOG.log(Level.SEVERE, "Unable to close input stream.", e);
}
inputStream = null;
}
}
}
/**
* Reads all data from the file and send it to the sink.
*/
public void parse(String xml) {
try {
reader.setInput(new StringReader(xml));
readOsm();
sink.complete();
} catch (Exception e) {
throw new OsmosisRuntimeException("Unable to read XML stream.", e);
} finally {
sink.release();
}
}
private void readUnknownElement() throws XmlPullParserException, IOException {
int level = 0;
do {
if (reader.getEventType() == XmlPullParser.START_TAG) {
level++;
} else if (reader.getEventType() == XmlPullParser.END_TAG) {
level--;
}
reader.next();
} while (level > 0);
}
private Tag readTag() throws Exception {
Tag tag = new Tag(reader.getAttributeValue(null, ATTRIBUTE_NAME_KEY),
reader.getAttributeValue(null, ATTRIBUTE_NAME_VALUE));
reader.nextTag();
reader.nextTag();
return tag;
}
private Node readNode() throws Exception {
long id;
double latitude;
double longitude;
Node node;
id = Long.parseLong(reader.getAttributeValue(null, ATTRIBUTE_NAME_ID));
latitude = Double.parseDouble(reader.getAttributeValue(null, ATTRIBUTE_NAME_LATITUDE));
longitude = Double.parseDouble(reader.getAttributeValue(null, ATTRIBUTE_NAME_LONGITUDE));
node = new Node(new CommonEntityData(id), latitude, longitude);
reader.nextTag();
while (reader.getEventType() == XmlPullParser.START_TAG) {
if (reader.getName().equals(ELEMENT_NAME_TAG)) {
node.getTags().add(readTag());
} else {
readUnknownElement();
}
}
reader.nextTag();
return node;
}
private WayNode readWayNode() throws Exception {
WayNode node = new WayNode(
Long.parseLong(reader.getAttributeValue(null, ATTRIBUTE_NAME_REF)));
reader.nextTag();
reader.nextTag();
return node;
}
private Way readWay() throws Exception {
long id;
Way way;
id = Long.parseLong(reader.getAttributeValue(null, ATTRIBUTE_NAME_ID));
way = new Way(new CommonEntityData(id));
reader.nextTag();
while (reader.getEventType() == XmlPullParser.START_TAG) {
if (reader.getName().equals(ELEMENT_NAME_TAG)) {
way.getTags().add(readTag());
} else if (reader.getName().equals(ELEMENT_NAME_NODE_REFERENCE)) {
way.getWayNodes().add(readWayNode());
} else {
readUnknownElement();
}
}
reader.nextTag();
return way;
}
private RelationMember readRelationMember() throws Exception {
long id;
EntityType type;
String role;
id = Long.parseLong(reader.getAttributeValue(null, ATTRIBUTE_NAME_REF));
type = memberTypeParser.parse(reader.getAttributeValue(null, ATTRIBUTE_NAME_TYPE));
role = reader.getAttributeValue(null, ATTRIBUTE_NAME_ROLE);
RelationMember relationMember = new RelationMember(id, type, role);
reader.nextTag();
reader.nextTag();
return relationMember;
}
private Relation readRelation() throws Exception {
long id;
Relation relation;
id = Long.parseLong(reader.getAttributeValue(null, ATTRIBUTE_NAME_ID));
relation = new Relation(new CommonEntityData(id));
reader.nextTag();
while (reader.getEventType() == XmlPullParser.START_TAG) {
if (reader.getName().equals(ELEMENT_NAME_TAG)) {
relation.getTags().add(readTag());
} else if (reader.getName().equals(ELEMENT_NAME_MEMBER)) {
relation.getMembers().add(readRelationMember());
} else {
readUnknownElement();
}
}
reader.nextTag();
return relation;
}
/**
* Parses the xml and sends all data to the sink.
*/
public void readOsm() {
try {
if (reader.nextTag() == XmlPullParser.START_TAG && reader.getName().equals("osm")) {
String fileVersion;
fileVersion = reader.getAttributeValue(null, ATTRIBUTE_NAME_VERSION);
if (!XmlConstants.OSM_VERSION.equals(fileVersion)) {
LOG.warning(
"Expected version " + XmlConstants.OSM_VERSION
+ " but received " + fileVersion + "."
);
}
reader.nextTag();
if (reader.getEventType() == XmlPullParser.START_TAG
&& reader.getName().equals(ELEMENT_NAME_BOUND)) {
//sink.process(new BoundContainer(readBound()));
}
while (reader.getEventType() == XmlPullParser.START_TAG) {
// Node, way, relation
if (reader.getName().equals(ELEMENT_NAME_NODE)) {
sink.process(readNode());
} else if (reader.getName().equals(ELEMENT_NAME_WAY)) {
sink.process(readWay());
} else if (reader.getName().equals(ELEMENT_NAME_RELATION)) {
sink.process(readRelation());
} else {
readUnknownElement();
}
if (reader.getEventType() == XmlPullParser.TEXT)
reader.nextTag();
}
} else {
throw new RuntimeException("No osm tag found");
}
} catch (Exception e) {
throw new OsmosisRuntimeException(e);
}
}
}
| Java |
package il.yrtimid.osm.osmpoi.xml;
import il.yrtimid.osm.osmpoi.domain.Entity;
import java.io.InputStream;
import java.util.List;
import org.xmlpull.v1.XmlPullParserException;
public class XmlReader {
public static List<Entity> parseEntitiesFromXMLStream(InputStream inputStream) throws XmlPullParserException {
EntityListSink sink = new EntityListSink();
FastXmlParser parser;
parser = new FastXmlParser(sink);
parser.parseStream(inputStream);
return sink.getEntities();
}
public static List<Entity> parseEntitiesFromXML(String xml) throws XmlPullParserException {
EntityListSink sink = new EntityListSink();
FastXmlParser parser;
parser = new FastXmlParser(sink);
parser.parse(xml);
return sink.getEntities();
}
}
| Java |
package il.yrtimid.osm.osmpoi;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import il.yrtimid.osm.osmpoi.CircleArea;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import il.yrtimid.osm.osmpoi.domain.Node;
import il.yrtimid.osm.osmpoi.domain.Relation;
import il.yrtimid.osm.osmpoi.domain.RelationMember;
import il.yrtimid.osm.osmpoi.domain.Way;
import android.location.Location;
public class Util {
static final float RADIUS = 6372795;// радиус сферы (Земли)
/**
* Calculates distance between two points in meters
*/
public static int getDistance(double lat1, double long1, double lat2, double long2) {
// copied from http://gis-lab.info/qa/great-circles.html
// в радианах
double rlat1 = lat1 * Math.PI / 180.0;
double rlat2 = lat2 * Math.PI / 180.0;
double rlong1 = long1 * Math.PI / 180.0;
double rlong2 = long2 * Math.PI / 180.0;
// косинусы и синусы широт и разницы долгот
double cl1 = Math.cos(rlat1);
double cl2 = Math.cos(rlat2);
double sl1 = Math.sin(rlat1);
double sl2 = Math.sin(rlat2);
double delta = rlong2 - rlong1;
double cdelta = Math.cos(delta);
double sdelta = Math.sin(delta);
// вычисления длины большого круга
double y = Math.sqrt(Math.pow(cl2 * sdelta, 2) + Math.pow(cl1 * sl2 - sl1 * cl2 * cdelta, 2));
double x = sl1 * sl2 + cl1 * cl2 * cdelta;
double ad = Math.atan2(y, x);
int dist = (int) Math.round(ad * RADIUS);
/*
* //вычисление начального азимута double x = (cl1*sl2) -
* (sl1*cl2*cdelta); double y = sdelta*cl2; double z =
* Math.degrees(Math.atan(-y/x));
*
* if (x < 0) z = z+180.0;
*
* double z2 = (z+180.) % 360. - 180.0; double z2 = - Math.radians(z2);
* double anglerad2 = z2 - ((2*Math.PI)*Math.floor((z2/(2*Math.PI))) );
* double angledeg = (anglerad2*180.)/Math.PI; //Initial bearing in
* degrees
*/
return dist;
}
/**
* Calculates bearing between two points in degrees
*/
public static int getBearing(double lat1, double long1, double lat2, double long2) {
// copied from http://gis-lab.info/qa/great-circles.html
// в радианах
double rlat1 = lat1 * Math.PI / 180.0;
double rlat2 = lat2 * Math.PI / 180.0;
double rlong1 = long1 * Math.PI / 180.0;
double rlong2 = long2 * Math.PI / 180.0;
// косинусы и синусы широт и разницы долгот
double cl1 = Math.cos(rlat1);
double cl2 = Math.cos(rlat2);
double sl1 = Math.sin(rlat1);
double sl2 = Math.sin(rlat2);
double delta = rlong2 - rlong1;
double cdelta = Math.cos(delta);
double sdelta = Math.sin(delta);
// вычисление начального азимута
double x = (cl1 * sl2) - (sl1 * cl2 * cdelta);
double y = sdelta * cl2;
double z = Math.toDegrees(Math.atan(-y / x));
if (x < 0)
z = z + 180.0;
double z2 = (z + 180.) % 360. - 180.0;
z2 = -Math.toRadians(z2);
double anglerad2 = z2 - ((2 * Math.PI) * Math.floor((z2 / (2 * Math.PI))));
double angledeg = (anglerad2 * 180.) / Math.PI; // Initial bearing in
// degrees
return (int) angledeg;
}
public static String getPrefixedName(String fileName, String prefix) {
String result;
int dotIndex = fileName.lastIndexOf(".");
if (dotIndex != -1) {
if (dotIndex < fileName.length() - 1) {
result = fileName.substring(0, dotIndex) + "." + prefix + "." + fileName.substring(dotIndex + 1, fileName.length());
} else {
result = fileName + prefix;
}
} else {
result = fileName + "." + prefix;
}
return result;
}
public static int getNodeDistance(Node node, CircleArea area) {
return getDistance(node.getLatitude(), node.getLongitude(), area.getLatitude(), area.getLongitude());
}
private static final int TWO_MINUTES = 1000 * 60 * 2;
/**
* Determines whether one Location reading is better than the current
* Location fix
*
* @param location
* The new Location that you want to evaluate
* @param currentBestLocation
* The current Location fix, to which you want to compare the new
* one
*/
public static boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use
// the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be
// worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and
// accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private static boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
public static String join(String delim, Object... data) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length; i++) {
sb.append(data[i]);
if (i >= data.length - 1) {
break;
}
sb.append(delim);
}
return sb.toString();
}
public static Node getFirstNode(Entity entity){
Node node = null;
switch (entity.getType()){
case Node:
node = (Node) entity;
break;
case Way:
List<Node> wayNodes = ((Way)entity).getNodes();
if (wayNodes.size()>0) node = wayNodes.get(0);
break;
case Relation:
//TODO: Implement returning nearest node from any relation level
List<RelationMember> members = ((Relation)entity).getMembers();
for(RelationMember rm : members){
if (rm.getMemberType() == EntityType.Node){
node = (Node)rm.getMember();
break;
}
}
break;
default:
break;
}
return node;
}
public static String readText(InputStream is, String charset) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
for(int len;(len = is.read(bytes))>0;)
baos.write(bytes, 0, len);
return new String(baos.toByteArray(), charset);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
import java.io.File;
import java.util.List;
import java.util.logging.Logger;
import il.yrtimid.osm.osmpoi.categories.Category;
import il.yrtimid.osm.osmpoi.dal.CachedDbOpenHelper;
import il.yrtimid.osm.osmpoi.dal.DbAnalyzer;
import il.yrtimid.osm.osmpoi.dal.DbSearcher;
import il.yrtimid.osm.osmpoi.dal.DbStarred;
import il.yrtimid.osm.osmpoi.dal.IDbCachedFiller;
import il.yrtimid.osm.osmpoi.formatters.EntityFormatter;
import il.yrtimid.osm.osmpoi.logging.AndroidLogHandler;
import il.yrtimid.osm.osmpoi.logging.Log;
import il.yrtimid.osm.osmpoi.ui.Preferences;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.preference.PreferenceManager;
/**
* @author yrtimid
*
*/
public class OsmPoiApplication extends Application {
public static ISearchSource searchSource;
public static Category mainCategory;
private static Location location;
public static LocationChangeManager locationManager;
public static OrientationChangeManager orientationManager;
public static Databases databases;
public static List<EntityFormatter> formatters;
private static final String POI_DATABASE_NAME = "poi.db";
private static final String ADDRESS_DATABASE_NAME = "address.db";
private static final String STARRED_DATABASE_NAME = "starred.db";
/* (non-Javadoc)
* @see android.app.Application#onCreate()
*/
@Override
public void onCreate() {
super.onCreate();
OsmPoiApplication.locationManager = new LocationChangeManager(getApplicationContext());
OsmPoiApplication.orientationManager = new OrientationChangeManager(getApplicationContext());
OsmPoiApplication.databases = new Databases(getApplicationContext());
Logger logger = Logger.getLogger(Log.TAG);
logger.addHandler(new AndroidLogHandler());
}
public static Boolean hasLocation(){
return location!=null;
}
public static Location getCurrentLocation() {
return location;
}
public static Point getCurrentLocationPoint() {
return new Point(location.getLatitude(), location.getLongitude());
}
public static boolean setCurrentLocation(Location location) {
if (Util.isBetterLocation(location, OsmPoiApplication.location)) {
OsmPoiApplication.location = location;
//currentSearch.setCenter( new Point(location.getLatitude(), location.getLongitude()));
return true;
}
else {
return false;
}
}
public static class Config {
public static void reset(Context context){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = prefs.edit();
editor.clear();
editor.commit();
}
public static void resetIncludeExclude(Context context){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = prefs.edit();
editor.remove(Preferences.NODES_INCLUDE);
editor.remove(Preferences.NODES_EXCLUDE);
editor.remove(Preferences.WAYS_INCLUDE);
editor.remove(Preferences.WAYS_EXCLUDE);
editor.remove(Preferences.RELATIONS_INCLUDE);
editor.remove(Preferences.RELATIONS_EXCLUDE);
editor.commit();
}
public static void reloadConfig(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
searchSourceType = (SearchSourceType) Enum.valueOf(SearchSourceType.class, prefs.getString(Preferences.SEARCH_SOURCE, "NONE"));
resultLanguage = prefs.getString(Preferences.RESULT_LANGUAGE, "");
Boolean isDbOnSdcard = prefs.getBoolean(Preferences.IS_DB_ON_SDCARD, false);
setupDbLocation(context, isDbOnSdcard);
OsmPoiApplication.databases.reset();
tryCreateSearchSource(context);
}
private static Boolean setupDbLocation(Context context, Boolean isDbOnSdcard) {
poiDbLocation = null;
addressDbLocation = null;
if (isDbOnSdcard){
try{
File folder = Preferences.getHomeFolder(context);
if (folder.canWrite()){
poiDbLocation = new File(folder, POI_DATABASE_NAME);
addressDbLocation = new File(folder, ADDRESS_DATABASE_NAME);
starredDbLocation = new File(folder, STARRED_DATABASE_NAME);
}else{
throw new RuntimeException("DB path isn't writable: "+folder.getPath());
}
}catch(Exception e){
Log.wtf("Checking external storage DB", e);
throw new RuntimeException("Can't load databases",e);
}
}else{
poiDbLocation = new File(POI_DATABASE_NAME);
addressDbLocation = new File(ADDRESS_DATABASE_NAME);
starredDbLocation = new File(STARRED_DATABASE_NAME);
}
return (poiDbLocation!=null) && (addressDbLocation!=null);
}
private static SearchSourceType searchSourceType;
private static String resultLanguage;
private static File poiDbLocation;
private static File addressDbLocation;
private static File starredDbLocation;
public static SearchSourceType getSearchSourceType() {
return searchSourceType;
}
public static String getResultLanguage() {
return resultLanguage;
}
public static File getPoiDbLocation() {
return poiDbLocation;
}
public static File getAddressDbLocation() {
return addressDbLocation;
}
public static File getStarredDbLocation() {
return starredDbLocation;
}
public static Boolean tryCreateSearchSource(Context context) {
return tryCreateSearchSource(context, searchSourceType);
}
public static Boolean tryCreateSearchSource(Context context, SearchSourceType type) {
try {
if (OsmPoiApplication.searchSource != null)
OsmPoiApplication.searchSource.close();
switch (type) {
case DB:
OsmPoiApplication.searchSource = DBSearchSource.create(context);
break;
case ONLINE:
OsmPoiApplication.searchSource = OverpassAPISearchSource.create(context);
break;
default:
OsmPoiApplication.searchSource = null;
break;
}
} catch (Exception e) {
e.printStackTrace();
OsmPoiApplication.searchSource = null;
return false;
}
return true;
}
}
public class Databases {
private Context context;
private DbStarred starred;
private DbSearcher poiSearcher;
private DbSearcher addrSearcher;
private DbAnalyzer poiAnalyzer;
private DbAnalyzer addrAnalyzer;
private CachedDbOpenHelper cachedPoiBasic;
private CachedDbOpenHelper cachedAddrBasic;
public Databases(Context context) {
this.context = context;
}
public void reset(){
this.starred = null;
}
public DbStarred getStarredDb(){
if (starred == null) starred = new DbStarred(context, OsmPoiApplication.Config.getStarredDbLocation());
return starred;
}
public DbSearcher getPoiSearcherDb(){
if (poiSearcher == null) poiSearcher = new DbSearcher(context, OsmPoiApplication.Config.getPoiDbLocation());
return poiSearcher;
}
public DbSearcher getAddressSearcherDb(){
if (addrSearcher == null) addrSearcher = new DbSearcher(context, OsmPoiApplication.Config.getAddressDbLocation());
return addrSearcher;
}
public IDbCachedFiller getPoiDb(){
if (cachedPoiBasic == null) cachedPoiBasic = new CachedDbOpenHelper(context, OsmPoiApplication.Config.getPoiDbLocation());
return cachedPoiBasic;
}
public IDbCachedFiller getAddressDb(){
if (cachedAddrBasic == null) cachedAddrBasic = new CachedDbOpenHelper(context, OsmPoiApplication.Config.getAddressDbLocation());
return cachedAddrBasic;
}
public DbAnalyzer getPoiAnalizerDb(){
if (poiAnalyzer == null) poiAnalyzer = new DbAnalyzer(context, OsmPoiApplication.Config.getPoiDbLocation());
return poiAnalyzer;
}
public DbAnalyzer getAddressAnalizerDb(){
if (addrAnalyzer == null) addrAnalyzer = new DbAnalyzer(context, OsmPoiApplication.Config.getAddressDbLocation());
return addrAnalyzer;
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author yrtimid
*
*/
public class CollectionPipe<T> implements SearchPipe<T> {
private Collection<T> items = new ArrayList<T>();
/**
* @return the items
*/
public Collection<T> getItems() {
return items;
}
@Override
public void pushItem(T item) {
items.add(item);
}
@Override
public void pushRadius(int radius) {
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
/**
* @author yrtimid
*
*/
public class OrientationChangeManager implements SensorEventListener {
public interface OrientationChangeListener{
public void OnOrientationChanged(float azimuth);
}
private OrientationChangeListener listener;
private SensorManager sensorManager;
private Sensor orientation;
/**
*
*/
public OrientationChangeManager(Context context) {
sensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
orientation = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
}
public void setOrientationChangeListener(OrientationChangeListener listener){
this.listener = listener;
if (this.listener == null){
sensorManager.unregisterListener(this);
}else {
sensorManager.registerListener(this, orientation, SensorManager.SENSOR_DELAY_UI);
}
}
/* (non-Javadoc)
* @see android.hardware.SensorEventListener#onSensorChanged(android.hardware.SensorEvent)
*/
@Override
public void onSensorChanged(SensorEvent event) {
StringBuilder b = new StringBuilder();
for(float f : event.values){
b.append(f).append(" ");
}
//Log.d(b.toString());
if (listener != null){
listener.OnOrientationChanged(event.values[0]);
}
}
/* (non-Javadoc)
* @see android.hardware.SensorEventListener#onAccuracyChanged(android.hardware.Sensor, int)
*/
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.categories;
import il.yrtimid.osm.osmpoi.searchparameters.*;
import java.util.ArrayList;
import java.util.List;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @author yrtimid
*
*/
public class Category implements Parcelable {
public enum Type {
NONE,
CUSTOM,
STARRED,
SEARCH,
INLINE_SEARCH
}
private List<Category> subCategories = new ArrayList<Category>();
private Type type;
private String name;
private String query;
private String select;
private Boolean localizable = false;
private String icon;
private Boolean subCategoriesFetched = false;
private BaseSearchParameter searchParameter = null;
public Category(Type type) {
this.type = type;
}
/**
* @param source
*/
protected Category(Parcel source) {
this.type = Enum.valueOf(Type.class, source.readString());
source.readTypedList(subCategories, Category.CREATOR);
this.name = source.readString();
this.icon = source.readString();
this.query = source.readString();
this.select = source.readString();
this.localizable = (Boolean) source.readValue(Boolean.class.getClassLoader());
this.subCategoriesFetched = (Boolean) source.readValue(Boolean.class.getClassLoader());
String className = source.readString();
if (className.equals("NULL")){
searchParameter = null;
}else if (className.equals("SearchAround")) {
searchParameter = source.readParcelable(SearchAround.class.getClassLoader());
} else if (className.equals("SearchById")) {
searchParameter = source.readParcelable(SearchById.class.getClassLoader());
} else if (className.equals("SearchByKeyValue")) {
searchParameter = source.readParcelable(SearchByKeyValue.class.getClassLoader());
} else if (className.equals("SearchByParentId")) {
searchParameter = source.readParcelable(SearchByParentId.class.getClassLoader());
}
}
public List<Category> getSubCategories() {
return subCategories;
}
public int getSubCategoriesCount() {
return subCategories.size();
}
public void setType(Type type) {
this.type = type;
}
public Type getType() {
return type;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getIcon() {
return icon;
}
public void setQuery(String query) {
this.query = query;
}
public String getQuery() {
return query;
}
public String getSelect() {
return select;
}
public void setSelect(String select) {
this.select = select;
}
public Boolean isLocalizable() {
return localizable;
}
public void setLocalizable(Boolean isLocalizable) {
this.localizable = isLocalizable;
}
public Boolean isSubCategoriesFetched() {
return subCategoriesFetched;
}
public void setSubCategoriesFetched() {
this.subCategoriesFetched = true;
}
public BaseSearchParameter getSearchParameter() {
return searchParameter;
}
public void setSearchParameter(BaseSearchParameter searchParameter) {
this.searchParameter = searchParameter;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(type.name());
dest.writeTypedList(subCategories);
dest.writeString(name);
dest.writeString(icon);
dest.writeString(query);
dest.writeString(select);
dest.writeValue(localizable);
dest.writeValue(subCategoriesFetched);
if (searchParameter == null) {
dest.writeString("NULL");
} else {
dest.writeString(searchParameter.getClass().getSimpleName());
String className = searchParameter.getClass().getSimpleName();
if (className.equals("SearchAround")) {
dest.writeParcelable((SearchAround) searchParameter, flags);
} else if (className.equals("SearchById")) {
dest.writeParcelable((SearchById) searchParameter, flags);
} else if (className.equals("SearchByKeyValue")) {
dest.writeParcelable((SearchByKeyValue) searchParameter, flags);
} else if (className.equals("SearchByParentId")) {
dest.writeParcelable((SearchByParentId) searchParameter, flags);
}
}
}
public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() {
@Override
public Category createFromParcel(Parcel source) {
return new Category(source);
}
@Override
public Category[] newArray(int size) {
return new Category[size];
}
};
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.categories;
import il.yrtimid.osm.osmpoi.OsmPoiApplication;
import il.yrtimid.osm.osmpoi.categories.Category.Type;
import il.yrtimid.osm.osmpoi.dal.DbAnalyzer;
import il.yrtimid.osm.osmpoi.logging.Log;
import il.yrtimid.osm.osmpoi.searchparameters.SearchByKeyValue;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.content.Context;
/**
* @author yrtimid
*
*/
public class CategoriesLoader {
public static Category load(Context context){
Category cat = null;
InputStream xmlStream = null;
try {
xmlStream = context.getAssets().open("categories.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlStream);
doc.getDocumentElement().normalize();
cat = createSubCategories(context, doc.getDocumentElement());
}catch(SAXException e){
Log.wtf("can't parse categories.xml", e);
}catch (ParserConfigurationException e){
Log.wtf("can't create parser", e);
} catch (IOException e) {
Log.wtf("can't open categories.xml", e);
}finally{
try{
if (xmlStream != null)
xmlStream.close();
}catch (IOException e) {
Log.wtf("Closing categories.xml stream", e);
}
}
return cat;
}
/**
* @param documentElement
* @param cat
*/
private static Category createSubCategories(Context context, Element root) {
Category cat = null;
String elementName = root.getNodeName();
String name = root.getAttribute("name");
String icon = root.getAttribute("icon");
String query = root.getAttribute("query");
String select = root.getAttribute("select");
if (elementName.equals("category")){
cat = new Category(Type.NONE);
}else if (elementName.equals("search")){
cat = new Category(Type.SEARCH);
cat.setSearchParameter(new SearchByKeyValue(query));
}else if (elementName.equals("inline")){
cat = new Category(Type.INLINE_SEARCH);
cat.setQuery(query);
}else if (elementName.equals("starred")){
cat = new Category(Type.STARRED);
}else if (elementName.equals("custom")){
cat = new Category(Type.CUSTOM);
}else if (elementName.equals("categories")){
cat = new Category(Type.NONE);
}else {
Log.d("Unknown category element: "+elementName);
return null;
}
cat.setLocalizable(true);
cat.setName(name);
cat.setIcon(icon);
cat.setSelect(select);
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node instanceof Element){
Category subCat = createSubCategories(context, (Element)node);
if (subCat != null)
cat.getSubCategories().add(subCat);
}
}
return cat;
}
public static void loadInlineCategories(Context context, Category cat){
if (cat.isSubCategoriesFetched()) return;
if (cat.getType() != Category.Type.INLINE_SEARCH) return;
DbAnalyzer dbHelper = null;
try{
dbHelper = OsmPoiApplication.databases.getPoiAnalizerDb();
Long id = dbHelper.getInlineResultsId(cat.getQuery(), cat.getSelect());
if (id == 0L){
id = dbHelper.createInlineResults(cat.getQuery(), cat.getSelect());
}
Collection<String> subs = dbHelper.getInlineResults(id);
for (String inlineCat:subs){
Category subCat = new Category(Type.SEARCH);
subCat.setName(inlineCat);
subCat.setIcon(inlineCat);
subCat.setSearchParameter(new SearchByKeyValue(String.format("%s=%s", cat.getSelect(), inlineCat)));
//subCat.setQuery(String.format("%s=%s", cat.getSelect(), inlineCat));
cat.getSubCategories().add(subCat);
}
cat.setSubCategoriesFetched();
}catch(Exception e){
Log.wtf("loadInlineCategories", e);
}finally{
//if (dbHelper != null) dbHelper.close();
}
return;
}
}
| Java |
package il.yrtimid.osm.osmpoi.logging;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
public class AndroidLogHandler extends Handler {
@Override
public void close() {
}
@Override
public void flush() {
}
@Override
public void publish(LogRecord record) {
Level l = record.getLevel();
//TODO: switch-case for different log levels
Log.d(record.getMessage());
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.logging;
/**
* @author yrtimid
* use setprop log.tag.OsmPoi VERBOSE to enable logging
*/
public class Log {
public static final String TAG = "OsmPoi";
// public static void i(String tag, String string) {
// if (android.util.Log.isLoggable(TAG, android.util.Log.INFO))
// android.util.Log.i(tag, string);
// }
//
// public static void w(String tag, String string) {
// if (android.util.Log.isLoggable(TAG, android.util.Log.WARN))
// android.util.Log.w(tag, string);
// }
//
// public static void e(String tag, String string) {
// if (android.util.Log.isLoggable(TAG, android.util.Log.ERROR))
// android.util.Log.e(tag, string);
// }
//
// public static void d(String tag, String string) {
// if (android.util.Log.isLoggable(TAG, android.util.Log.DEBUG))
// android.util.Log.d(tag, string);
// }
//
// public static void v(String tag, String string) {
// if (android.util.Log.isLoggable(TAG, android.util.Log.VERBOSE))
// android.util.Log.v(tag, string);
// }
//
// public static void wtf(String tag, String message, Throwable throwable) {
// android.util.Log.wtf(tag, message, throwable);
// }
public static void i(String string) {
if (android.util.Log.isLoggable(TAG, android.util.Log.INFO))
android.util.Log.i(TAG, string);
}
public static void w(String string) {
if (android.util.Log.isLoggable(TAG, android.util.Log.WARN))
android.util.Log.w(TAG, string);
}
public static void e(String string) {
if (android.util.Log.isLoggable(TAG, android.util.Log.ERROR))
android.util.Log.e(TAG, string);
}
public static void d(String string) {
if (android.util.Log.isLoggable(TAG, android.util.Log.DEBUG))
android.util.Log.d(TAG, string);
}
public static void v(String string) {
if (android.util.Log.isLoggable(TAG, android.util.Log.VERBOSE))
android.util.Log.v(TAG, string);
}
public static void wtf(String message, Throwable throwable) {
android.util.Log.e(TAG, message, throwable);
}
}
| Java |
package il.yrtimid.osm.osmpoi.searchparameters;
import il.yrtimid.osm.osmpoi.Point;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Search for anything around point
* @author yrtimid
*
*/
public class SearchAround extends BaseSearchParameter implements android.os.Parcelable{
private Point center;
public static final Parcelable.Creator<SearchAround> CREATOR = new Parcelable.Creator<SearchAround>() {
@Override
public SearchAround createFromParcel(Parcel source) {
return new SearchAround(source);
}
@Override
public SearchAround[] newArray(int size) {
return new SearchAround[size];
}
};
public SearchAround(){
this.center = new Point(0,0);
this.maxResults = 0;
}
public SearchAround(Parcel source){
super(source);
this.center = new Point(source.readDouble(), source.readDouble());
}
public void setCenter(Point center) {
this.center = center;
}
public Point getCenter() {
return center;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeDouble(center.getLatitude());
dest.writeDouble(center.getLongitude());
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.searchparameters;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @author yrtimid
*
*/
public class SearchById extends BaseSearchParameter implements android.os.Parcelable {
private long id;
private EntityType type;
public static final Parcelable.Creator<SearchById> CREATOR = new Parcelable.Creator<SearchById>() {
@Override
public SearchById createFromParcel(Parcel source) {
return new SearchById(source);
}
@Override
public SearchById[] newArray(int size) {
return new SearchById[size];
}
};
public SearchById(EntityType entityType, long id){
this.maxResults = 0;
this.id = id;
this.type = entityType;
}
public SearchById(Parcel source){
super(source);
this.id = source.readLong();
this.type = Enum.valueOf(EntityType.class, source.readString());
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setEntityType(EntityType type) {
this.type = type;
}
public EntityType getEntityType() {
return type;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeLong(id);
dest.writeString(type.name());
}
}
| Java |
package il.yrtimid.osm.osmpoi.searchparameters;
import il.yrtimid.osm.osmpoi.Point;
import il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Search around point and filtering by key-value
* @author yrtimid
*
*/
public class SearchByKeyValue extends SearchAround implements android.os.Parcelable{
protected Point center;
protected String expression;
protected TagMatcher matcher = null;
public static final Parcelable.Creator<SearchByKeyValue> CREATOR = new Parcelable.Creator<SearchByKeyValue>() {
@Override
public SearchByKeyValue createFromParcel(Parcel source) {
return new SearchByKeyValue(source);
}
@Override
public SearchByKeyValue[] newArray(int size) {
return new SearchByKeyValue[size];
}
};
public SearchByKeyValue(String expression){
this.center = new Point(0,0);
this.maxResults = 0;
this.expression = expression;
}
public SearchByKeyValue(Parcel source){
super(source);
expression = source.readString();
this.matcher = null;
}
public void setExpression(String expression) {
this.expression = expression;
this.matcher = null;
}
public String getExpression(){
return this.expression;
}
public boolean hasExpression(){
return this.expression != null && this.expression.length()>0;
}
public TagMatcher getMatcher() {
if (matcher == null){
matcher = TagMatcher.parse(expression);
}
return matcher;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(expression);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.searchparameters;
import il.yrtimid.osm.osmpoi.Point;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @author yrtimid
*
*/
public class SearchByParentId extends SearchById implements android.os.Parcelable {
private Point center;
public static final Parcelable.Creator<SearchByParentId> CREATOR = new Parcelable.Creator<SearchByParentId>() {
@Override
public SearchByParentId createFromParcel(Parcel source) {
return new SearchByParentId(source);
}
@Override
public SearchByParentId[] newArray(int size) {
return new SearchByParentId[size];
}
};
public SearchByParentId(EntityType entityType, long id){
super(entityType, id);
this.center = new Point(0,0);
}
public SearchByParentId(Parcel source){
super(source);
this.center = new Point(source.readDouble(), source.readDouble());
}
public Point getCenter() {
return center;
}
public void setCenter(Point center) {
this.center = center;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeDouble(center.getLatitude());
dest.writeDouble(center.getLongitude());
}
}
| Java |
package il.yrtimid.osm.osmpoi.searchparameters;
import android.os.Parcel;
public abstract class BaseSearchParameter implements android.os.Parcelable{
protected Integer maxResults;
public BaseSearchParameter(){
this.maxResults = 0;
}
public BaseSearchParameter(Parcel source){
maxResults = source.readInt();
}
/**
* Limiting results count. Negative or zero values equal to no limit.
* @return
*/
public Integer getMaxResults() {
return maxResults;
}
/**
* Limiting results count. Negative or zero values equal to no limit.
* @param maxResults
*/
public void setMaxResults(int maxResults) {
this.maxResults = maxResults;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(maxResults);
}
@Override
public int describeContents() {
return 0;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
/**
* @author yrtimid
*
*/
public class CancelFlag {
private boolean cancel = false;
public void cancel(){
this.cancel = true;
}
public boolean isCancelled(){
return cancel;
}
public boolean isNotCancelled(){
return !cancel;
}
}
| Java |
///**
// *
// */
//package il.yrtimid.osm.osmpoi;
//
//import java.util.ArrayList;
//import java.util.Collection;
//
//import org.openstreetmap.osmosis.core.domain.v0_6.Entity;
//import org.openstreetmap.osmosis.core.domain.v0_6.Node;
//
//import il.yrtimid.osm.osmpoi.UI.Action;
//import il.yrtimid.osm.osmpoi.UI.ResultsAdapter;
//
///**
// * @author yrtimid
// *
// */
//public class ResultsWrapper {
// ResultsAdapter adapter;
// boolean cancel = false;
// private Action onProgress;
//
// public ResultsWrapper(ResultsAdapter adapter){
// this.adapter = adapter;
// }
//
// public void setOnProgress(Action action){
// this.onProgress = action;
// }
//
// public void setCancel(boolean cancel){
// this.cancel = cancel;
// }
//
// public boolean isCancel(){
// return this.cancel;
// }
//
// public void addItem(Entity entity){
// adapter.addItem(entity);
// if (onProgress!= null)
// onProgress.onAction();
// }
//
// public void addEntities(Collection<Entity> entities){
// adapter.addItems(entities);
// if (onProgress!= null)
// onProgress.onAction();
// }
//
// public void addNodes(Collection<Node> nodes){
// Collection<Entity> entities = new ArrayList<Entity>(nodes);
// addEntities(entities);
// }
//
// public void update(){
// adapter.update();
// }
//
//
//}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
import il.yrtimid.osm.osmpoi.logging.Log;
import java.util.Date;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
/**
* @author yrtimid
*
*/
public class LocationChangeManager implements LocationListener {
public interface LocationChangeListener{
public void OnLocationChanged(Location loc);
}
private LocationManager locationManager;
private LocationChangeListener listener;
/**
*
*/
public LocationChangeManager(Context context) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
public void setLocationChangeListener(LocationChangeListener listener){
this.listener = listener;
if (this.listener == null){
locationManager.removeUpdates(this);
}else {
Location lastLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLoc != null && (new Date().getTime() - lastLoc.getTime()) < 1000 * 60)
onLocationChanged(lastLoc);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 5, this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 5, this);
}
}
@Override
public void onLocationChanged(Location newLoc) {
Log.d(String.format("Got new location: %f %f %f", newLoc.getLatitude(), newLoc.getLongitude(), newLoc.getAccuracy()));
if (OsmPoiApplication.setCurrentLocation(newLoc)) {
if (listener != null){
listener.OnLocationChanged(newLoc);
}
}
}
/* (non-Javadoc)
* @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle)
*/
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
/* (non-Javadoc)
* @see android.location.LocationListener#onProviderEnabled(java.lang.String)
*/
@Override
public void onProviderEnabled(String provider) {
}
/* (non-Javadoc)
* @see android.location.LocationListener#onProviderDisabled(java.lang.String)
*/
@Override
public void onProviderDisabled(String provider) {
}
}
| Java |
package il.yrtimid.osm.osmpoi;
public enum SearchType {
None,
SearchAround,
SearchByKeyValue,
SearchById,
SearchAssociated
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
import il.yrtimid.osm.osmpoi.Pair;
import il.yrtimid.osm.osmpoi.domain.Bound;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.Node;
import il.yrtimid.osm.osmpoi.domain.Relation;
import il.yrtimid.osm.osmpoi.domain.RelationMember;
import il.yrtimid.osm.osmpoi.domain.Tag;
import il.yrtimid.osm.osmpoi.domain.Way;
import il.yrtimid.osm.osmpoi.logging.Log;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* @author yrtimid
*
*/
public class DbFiller extends DbCreator implements IDbFiller {
/**
* @param context
* @param dbLocation
*/
public DbFiller(Context context, File dbLocation) {
super(context, dbLocation);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDatabase#create()
*/
@Override
public void create() throws Exception {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#clearAll()
*/
@Override
public void clearAll() throws Exception {
drop();
SQLiteDatabase db = getWritableDatabase();
db.setLockingEnabled(false);
//dropAllTables(db);
createAllTables(db);
db.setLockingEnabled(true);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#initGrid()
*/
@Override
public void initGrid() throws SQLException {
SQLiteDatabase db = getWritableDatabase();
//db.execSQL("UPDATE "+NODES_TABLE+" SET grid_id=1");
db.execSQL("DROP TABLE IF EXISTS "+Queries.GRID_TABLE);
db.execSQL(Queries.SQL_CREATE_GRID_TABLE);
String sql_generate_grid = "INSERT INTO grid (minLat, minLon, maxLat, maxLon)"
+" SELECT min(lat) minLat, min(lon) minLon, max(lat) maxLat, max(lon) maxLon"
+" FROM nodes";
Log.d(sql_generate_grid);
db.execSQL(sql_generate_grid);
String updateNodesGrid = "UPDATE nodes SET grid_id = 1 WHERE grid_id <> 1";
Log.d(updateNodesGrid);
db.execSQL(updateNodesGrid);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#addEntity(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public void addEntity(Entity entity) throws SQLException {
if (entity instanceof Node)
addNode((Node) entity);
else if (entity instanceof Way)
addWay((Way) entity);
else if (entity instanceof Relation)
addRelation((Relation) entity);
else if (entity instanceof Bound)
addBound((Bound)entity);
}
@Override
public void addBound(Bound bound) throws SQLException {
try {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("top", bound.getTop());
values.put("bottom", bound.getBottom());
values.put("left", bound.getLeft());
values.put("right", bound.getRight());
long id = db.insert(Queries.BOUNDS_TABLE, null, values);
if (id == -1)
throw new SQLException("Bound was not inserted");
} finally{
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#addNode(il.yrtimid.osm.osmpoi.domain.Node)
*/
@Override
public void addNode(Node node) throws SQLException {
try {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", node.getId());
values.put("timestamp", node.getTimestamp());
values.put("lat", node.getLatitude());
values.put("lon", node.getLongitude());
values.put("grid_id", 1);
db.insertWithOnConflict(Queries.NODES_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
addNodeTags(node);
} finally{
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#addNodeTag(long, il.yrtimid.osm.osmpoi.domain.Tag)
*/
@Override
public void addNodeTags(Node node) throws SQLException {
try {
SQLiteDatabase db = getWritableDatabase();
for(Tag tag : node.getTags()){
ContentValues values = new ContentValues();
values.put("node_id", node.getId());
values.put("k", tag.getKey());
values.put("v", tag.getValue());
db.insertWithOnConflict(Queries.NODES_TAGS_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
} finally{
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#addWay(il.yrtimid.osm.osmpoi.domain.Way)
*/
@Override
public void addWay(Way way) throws SQLException {
try {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", way.getId());
values.put("timestamp", way.getTimestamp());
db.insertWithOnConflict(Queries.WAYS_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
addWayTags(way);
addWayNodes(way);
} finally{
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#addWayTag(long, il.yrtimid.osm.osmpoi.domain.Tag)
*/
@Override
public void addWayTags(Way way) throws SQLException {
try {
SQLiteDatabase db = getWritableDatabase();
for(Tag tag : way.getTags()){
ContentValues values = new ContentValues();
values.put("way_id", way.getId());
values.put("k", tag.getKey());
values.put("v", tag.getValue());
db.insertWithOnConflict(Queries.WAY_TAGS_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
} finally{
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#addWayNode(long, int, il.yrtimid.osm.osmpoi.domain.Node)
*/
@Override
public void addWayNodes(Way way) throws SQLException {
try {
SQLiteDatabase db = getWritableDatabase();
for(Node node : way.getNodes()){
ContentValues values = new ContentValues();
values.put("way_id", way.getId());
values.put("node_id", node.getId());
db.insertWithOnConflict(Queries.WAY_NODES_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
} finally{
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#addRelation(il.yrtimid.osm.osmpoi.domain.Relation)
*/
@Override
public void addRelation(Relation rel) throws SQLException {
try {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", rel.getId());
values.put("timestamp", rel.getTimestamp());
db.insertWithOnConflict(Queries.RELATIONS_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
addRelationTags(rel);
addRelationMembers(rel);
} finally{
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#addRelationTag(long, il.yrtimid.osm.osmpoi.domain.Tag)
*/
@Override
public void addRelationTags(Relation rel) throws SQLException {
try {
SQLiteDatabase db = getWritableDatabase();
for(Tag tag : rel.getTags()){
ContentValues values = new ContentValues();
values.put("relation_id", rel.getId());
values.put("k", tag.getKey());
values.put("v", tag.getValue());
db.insertWithOnConflict(Queries.RELATION_TAGS_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
}finally{
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#addRelationMember(long, int, il.yrtimid.osm.osmpoi.domain.RelationMember)
*/
@Override
public void addRelationMembers(Relation rel) throws SQLException {
try {
SQLiteDatabase db = getWritableDatabase();
for(RelationMember mem : rel.getMembers()){
ContentValues values = new ContentValues();
values.put("relation_id", rel.getId());
values.put("type", mem.getMemberType().name());
values.put("ref", mem.getMemberId());
values.put("role", mem.getMemberRole());
db.insertWithOnConflict(Queries.MEMBERS_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
}finally{
}
}
/*
public void updateNodesGrid(){
SQLiteDatabase db = getWritableDatabase();
Double gridStep = 0.1;
db.delete(GRID_TABLE, null, null);
String sql_generate_grid = "INSERT INTO grid (minLat, minLon, maxLat, maxLon)"
+" SELECT minLat, minLon, minLat+? maxLat, minLon+? maxLon FROM ("
+" SELECT DISTINCT CAST(lat/? as INT)*? minLat, CAST(lon/? as INT)*? minLon FROM nodes"
+" )";
Log.d(sql_generate_grid);
Log.d("gridStep="+gridStep);
db.execSQL(sql_generate_grid, new Object[]{gridStep, gridStep, gridStep, gridStep, gridStep, gridStep});
String updateNodesGrid = "UPDATE nodes SET grid_id = (SELECT g.id FROM grid g WHERE lat>=minLat AND lat<maxLat AND lon>=minLon AND lon<maxLon)";
Log.d(updateNodesGrid);
db.execSQL(updateNodesGrid);
}
*/
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbFiller#optimizeGrid(java.lang.Integer)
*/
@Override
public void optimizeGrid(Integer maxItems) throws SQLException {
Collection<Pair<Integer,Integer>> cells = null;
do{
cells = getBigCells(maxItems);
Log.d("OptimizeGrid: "+cells.size()+" cells needs optimization for "+maxItems+" items");
for(Pair<Integer,Integer> cell : cells){
Log.d("OptimizeGrid: cell_id="+cell.getA()+", cell size="+cell.getB());
splitGridCell(cell.getA());
}
}while(cells.size() > 0);
}
/**
* finds cells which have nodes count greater than minItems
* @param minItems
* @return
*/
private Collection<Pair<Integer,Integer>> getBigCells(Integer minItems) throws SQLException{
SQLiteDatabase db = getReadableDatabase();
Cursor cur = null;
Collection<Pair<Integer,Integer>> gridIds = new ArrayList<Pair<Integer,Integer>>();
try{
cur = db.rawQuery("SELECT grid_id, count(id) [count] FROM "+Queries.NODES_TABLE+" GROUP BY grid_id HAVING count(id)>"+minItems.toString(), null);
if (cur.moveToFirst()){
do{
Integer id = cur.getInt(cur.getColumnIndex("grid_id"));
Integer count = cur.getInt(cur.getColumnIndex("count"));
gridIds.add(new Pair<Integer, Integer>(id, count));
}while(cur.moveToNext());
}
}finally{
if (cur != null) cur.close();
}
return gridIds;
}
/**
* Splits cell into 4 pieces and updates theirs nodes with the new split
* @param id ID of the cell to split
*/
private void splitGridCell(Integer id){
SQLiteDatabase db = getWritableDatabase();
try{
Log.d("splitGridCell id:"+id);
//calc new cell size to be 1/2 of the old one
Cursor cur = db.rawQuery("SELECT round((maxLat-minLat)/2,7) dLat, round((maxLon-minLon)/2,7) dLon from "+Queries.GRID_TABLE+" WHERE id=?", new String[]{id.toString()});
cur.moveToFirst();
Double newCellSizeLat = cur.getDouble(0);
Double newCellSizeLon = cur.getDouble(1);
cur.close();
Log.d("newCellSizeLat="+newCellSizeLat+" newCellSizeLon="+newCellSizeLon);
String create4NewCellsSql;
create4NewCellsSql = "INSERT INTO grid (minLat, minLon, maxLat, maxLon) \n"
+" SELECT * FROM (\n"
+" SELECT minLat, minLon, minLat+%1$f, minLon+%2$f FROM grid where id = %3$d\n"
+" union all\n"
+" SELECT minLat+%1$f, minLon, maxLat, minLon+%2$f FROM grid where id = %3$d\n"
+" union all\n"
+" SELECT minLat, minLon+%2$f, minLat+%1$f, maxLon FROM grid where id = %3$d\n"
+" union all\n"
+" SELECT minLat+%1$f, minLon+%2$f, maxLat, maxLon FROM grid where id = %3$d\n"
+" )\n";
create4NewCellsSql = String.format(create4NewCellsSql, newCellSizeLat, newCellSizeLon, id);
Log.d(create4NewCellsSql);
db.execSQL(create4NewCellsSql);
//delete old cell
db.delete(Queries.GRID_TABLE, "id=?", new String[]{id.toString()});
//update nodes to use new cells
String updateNodesSql = "UPDATE nodes SET grid_id = (SELECT g.id FROM "+Queries.GRID_TABLE+" g WHERE lat>=minLat AND lat<=maxLat AND lon>=minLon AND lon<=maxLon limit 1) WHERE grid_id="+id.toString();
Log.d(updateNodesSql);
db.execSQL(updateNodesSql);
}catch (Exception e) {
Log.wtf("splitGridCell", e);
}finally{
//db.endTransaction();q
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.logging.Log;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* @author yrtimiD
*
*/
public class DbCreator extends SQLiteOpenHelper /*implements IDatabase*/{
private static final int DATABASE_VERSION = 3;
private File dbLocation;
protected static final Map<EntityType, String> entityTypeToTableName = new HashMap<EntityType, String>();
protected static final Map<EntityType, String> entityTypeToTagsTableName = new HashMap<EntityType, String>();
protected Context context;
/**
* @param context
* @param name
* @param factory
* @param version
*/
public DbCreator(Context context, File dbLocation) {
super(context, dbLocation.getPath(), null, DATABASE_VERSION);
this.context = context;
this.dbLocation = dbLocation;
entityTypeToTableName.put(EntityType.Node, Queries.NODES_TABLE);
entityTypeToTableName.put(EntityType.Way, Queries.WAYS_TABLE);
entityTypeToTableName.put(EntityType.Relation, Queries.RELATIONS_TABLE);
entityTypeToTagsTableName.put(EntityType.Node, Queries.NODES_TAGS_TABLE);
entityTypeToTagsTableName.put(EntityType.Way, Queries.WAY_TAGS_TABLE);
entityTypeToTagsTableName.put(EntityType.Relation, Queries.RELATION_TAGS_TABLE);
}
/*
* (non-Javadoc)
*
* @see
* android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
* .SQLiteDatabase)
*/
@Override
public void onCreate(SQLiteDatabase db) {
createAllTables(db);
}
/*
* (non-Javadoc)
*
* @see
* android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
* .SQLiteDatabase, int, int)
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1 && newVersion > 1){
db.execSQL(Queries.SQL_CREATE_STARRED_TABLE);
}
if (oldVersion == 2 && newVersion > 2){
db.execSQL(Queries.SQL_CREATE_BOUNDS_TABLE);
}
}
protected void createAllTables(SQLiteDatabase db){
db.execSQL(Queries.SQL_CREATE_BOUNDS_TABLE);
db.execSQL(Queries.SQL_CREATE_NODE_TABLE);
db.execSQL(Queries.SQL_CREATE_NODE_TAGS_TABLE);
db.execSQL(Queries.SQL_NODE_TAGS_IDX);
db.execSQL(Queries.SQL_CREATE_WAYS_TABLE);
db.execSQL(Queries.SQL_CREATE_WAY_TAGS_TABLE);
db.execSQL(Queries.SQL_WAY_TAGS_IDX);
db.execSQL(Queries.SQL_CREATE_WAY_NODES_TABLE);
db.execSQL(Queries.SQL_WAY_NODES_WAY_NODE_IDX);
db.execSQL(Queries.SQL_WAY_NODES_WAY_IDX);
db.execSQL(Queries.SQL_WAY_NODES_NODE_IDX);
db.execSQL(Queries.SQL_CREATE_RELATIONS_TABLE);
db.execSQL(Queries.SQL_CREATE_RELATION_TAGS_TABLE);
db.execSQL(Queries.SQL_RELATION_TAGS_IDX);
db.execSQL(Queries.SQL_CREATE_MEMBERS_TABLE);
db.execSQL(Queries.SQL_RELATION_MEMBERS_IDX);
db.execSQL(Queries.SQL_CREATE_GRID_TABLE);
db.execSQL(Queries.SQL_CREATE_INLINE_QUERIES_TABLE);
db.execSQL(Queries.SQL_CREATE_INLINE_RESULTS_TABLE);
}
protected void dropAllTables(SQLiteDatabase db){
db.beginTransaction();
try{
db.execSQL("DROP TABLE IF EXISTS "+Queries.MEMBERS_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+Queries.RELATION_TAGS_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+Queries.RELATIONS_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+Queries.WAY_NODES_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+Queries.WAY_TAGS_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+Queries.WAYS_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+Queries.NODES_TAGS_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+Queries.NODES_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+Queries.GRID_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+Queries.INLINE_RESULTS_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+Queries.INLINE_QUERIES_TABLE);
db.execSQL("DROP TABLE IF EXISTS "+Queries.BOUNDS_TABLE);
db.setTransactionSuccessful();
}catch(Exception e){
Log.wtf("dropAllTables", e);
}finally{
db.endTransaction();
}
db.execSQL("VACUUM");
}
public void drop(){
context.deleteDatabase(this.dbLocation.getPath());
}
}
| Java |
package il.yrtimid.osm.osmpoi.dal;
import il.yrtimid.osm.osmpoi.Util;
import il.yrtimid.osm.osmpoi.domain.CommonEntityData;
import il.yrtimid.osm.osmpoi.domain.TagCollection;
import il.yrtimid.osm.osmpoi.tagmatchers.AndMatcher;
import il.yrtimid.osm.osmpoi.tagmatchers.KeyValueMatcher;
import il.yrtimid.osm.osmpoi.tagmatchers.OrMatcher;
import il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher;
import il.yrtimid.osm.osmpoi.xml.FastXmlParser;
import il.yrtimid.osm.osmpoi.xml.XmlReader;
import java.io.*;
import java.net.*;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.*;
import java.util.logging.Logger;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import android.app.Application;
public class OsmOverpassAPI {
private static final Logger LOG = Logger.getLogger(OsmOverpassAPI.class.getName());
private static final String OVERPASS_API = "http://www.overpass-api.de/api/interpreter";
private static final String BBOX = "(%f,%f,%f,%f)";//lower latitude, lower longitude, upper latitude, upper longitude
private static final String KV_QUERY = "['%1$s'='%2$s']";//1-k,2-v
//private static final String NODES_AND_WAYS_BY_KV = "node[%s]%s->.n;way[%s]%s->.w;(.n;.w;.w>;);out body;";//query,bbox,query,bbox
private static final String NODES_WAYS_REL_BY_KV = "node%1$s%2$s;way%1$s%2$s;rel%1$s%2$s;";//1-query,2-bbox
private static final String UNION_RECURSIVE = "(%s);(._;>;);out body;";//query
private static String getQuery(Double lat, Double lon, Double radius, TagMatcher matcher) throws Exception {
String bbox = String.format(BBOX, lat-radius, lon-radius, lat+radius, lon+radius);
String query = convertTagMatcher(matcher, bbox);
query = String.format(UNION_RECURSIVE, query);
return query;
}
private static String convertTagMatcher(TagMatcher matcher, String bbox) throws Exception{
if (matcher instanceof OrMatcher){
List<TagMatcher> all = ((OrMatcher) matcher).getAllSiblings();
StringBuilder b = new StringBuilder();
for (TagMatcher tm : all){
if (tm instanceof KeyValueMatcher){
String q = convertKeyValueMatcher((KeyValueMatcher)tm);
b.append(String.format(NODES_WAYS_REL_BY_KV, q, bbox));
}
}
return b.toString();
}else if (matcher instanceof AndMatcher){
List<TagMatcher> all = ((AndMatcher) matcher).getAllSiblings();
StringBuilder b = new StringBuilder();
for (TagMatcher tm : all){
if (tm instanceof KeyValueMatcher){
String q = convertKeyValueMatcher((KeyValueMatcher)tm);
b.append(q);
}
}
return String.format(NODES_WAYS_REL_BY_KV, b.toString(), bbox);
}else if (matcher instanceof KeyValueMatcher){
String q = convertKeyValueMatcher((KeyValueMatcher) matcher);
return String.format(NODES_WAYS_REL_BY_KV, q, bbox);
}else
throw new Exception(matcher.toString()+" is not supported or implemented");
}
private static String convertKeyValueMatcher(KeyValueMatcher matcher){
return String.format(KV_QUERY, matcher.getKey(), matcher.getValue());
}
// /**
// *
// * @param lat center
// * @param lon center
// * @param radius 0.01+
// * @param k
// * @param v
// * @return
// */
// private static String getQueryForKV(Double lat, Double lon, Double radius, String k, String v){
// String bbox = String.format(BBOX, lat-radius, lon-radius, lat+radius, lon+radius);
// String kv = String.format(KV_QUERY, k, v);
// return String.format(NODES_AND_WAYS_BY_KV, kv, bbox, kv, bbox);
// }
/**
// *
// * @param xmlDocument
// * @return a list of OSM entities extracted from xml
// */
// private static List<il.yrtimid.osm.osmpoi.domain.Entity> getEntities(Document xmlDocument) {
// List<il.yrtimid.osm.osmpoi.domain.Entity> osmEntities = new ArrayList<il.yrtimid.osm.osmpoi.domain.Entity>();
//
// Node osmRoot = xmlDocument.getFirstChild();
// NodeList osmXMLNodes = osmRoot.getChildNodes();
// for (int i = 1; i < osmXMLNodes.getLength(); i++) {
// Node item = osmXMLNodes.item(i);
// if (item.getNodeName().equals("node")) {
//
// NamedNodeMap attributes = item.getAttributes();
//
// Node namedItemID = attributes.getNamedItem("id");
// Node namedItemLat = attributes.getNamedItem("lat");
// Node namedItemLon = attributes.getNamedItem("lon");
//
// Long id = Long.valueOf(namedItemID.getNodeValue());
// Double latitude = Double.valueOf(namedItemLat.getNodeValue());
// Double longitude = Double.valueOf(namedItemLon.getNodeValue());
//
// il.yrtimid.osm.osmpoi.domain.CommonEntityData entityData = new CommonEntityData(id, 0);
// il.yrtimid.osm.osmpoi.domain.Node node = new il.yrtimid.osm.osmpoi.domain.Node(entityData, latitude, longitude);
// TagCollection tags = node.getTags();
//
// NodeList tagXMLNodes = item.getChildNodes();
// for (int j = 1; j < tagXMLNodes.getLength(); j++) {
// Node tagItem = tagXMLNodes.item(j);
// NamedNodeMap tagAttributes = tagItem.getAttributes();
// if (tagAttributes != null) {
// String k = tagAttributes.getNamedItem("k").getNodeValue();
// String v = tagAttributes.getNamedItem("v").getNodeValue();
// tags.add(new il.yrtimid.osm.osmpoi.domain.Tag(k, v));
// }
// }
//
// osmEntities.add(node);
// }else if (item.getNodeName().equals("way")) {
////TODO:
// }
//
// }
// return osmEntities;
// }
//
// public static List<il.yrtimid.osm.osmpoi.domain.Node> getOSMNodesInVicinity(double lat, double lon, double vicinityRange) throws IOException, SAXException, ParserConfigurationException {
// return OSMWrapperAPI.getNodes(getXML(lon, lat, vicinityRange));
// }
/**
*
* @param query the overpass query
* @return the nodes in the formulated query
* @throws IOException
* @throws ParserConfigurationException
* @throws SAXException
*/
private static InputStream getDataViaOverpass(String query) throws IOException, ParserConfigurationException, SAXException {
String hostname = OVERPASS_API;
URL osm = new URL(hostname);
HttpURLConnection connection = (HttpURLConnection) osm.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setReadTimeout(2*60*1000);//2 minute timeout
DataOutputStream printout = new DataOutputStream(connection.getOutputStream());
printout.writeBytes("data=" + URLEncoder.encode(query, "utf-8"));
printout.flush();
printout.close();
//DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
//DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
//return docBuilder.parse(connection.getInputStream());
return connection.getInputStream();
}
/**
*
* @param lat
* @param lon
* @param radius
* @param kvQuery only k=v supported
* @return
* @throws IOException
*/
public static List<il.yrtimid.osm.osmpoi.domain.Entity> Search(Double lat, Double lon, Double radius, TagMatcher matcher) throws IOException{
List<il.yrtimid.osm.osmpoi.domain.Entity> result = new ArrayList<il.yrtimid.osm.osmpoi.domain.Entity>();
InputStream inputStream = null;
try {
//String query = getQueryForKV(lat, lon, radius, matcher.getKey(), matcher.getValue());
String query = getQuery(lat, lon, radius, matcher);
//Document doc;
inputStream = getDataViaOverpass(query);
String xml = Util.readText(inputStream, "UTF-8");
//result = getEntities(doc);
//result = XmlReader.parseEntitiesFromXMLStream(inputStream);
LOG.finest(xml);
result = XmlReader.parseEntitiesFromXML(xml);
} catch (Exception e) {
e.printStackTrace();
throw new IOException("Can't get data from Overpass");
}
finally{
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
import java.util.regex.Matcher;
import il.yrtimid.osm.osmpoi.tagmatchers.AndMatcher;
import il.yrtimid.osm.osmpoi.tagmatchers.KeyValueMatcher;
import il.yrtimid.osm.osmpoi.tagmatchers.NotMatcher;
import il.yrtimid.osm.osmpoi.tagmatchers.OrMatcher;
import il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher;
/**
* @author yrtimid
*
*/
public class TagMatcherFormatter {
public static class WhereClause{
public String where;
public WhereClause(String where){
this.where = where;
}
}
public static WhereClause format(TagMatcher matcher, String baseQuery) {
if (matcher instanceof KeyValueMatcher) {
KeyValueMatcher kv = (KeyValueMatcher) matcher;
String kf;
String vf;
if (kv.isKeyExactMatch())
kf = String.format("k='%s'", kv.getKey().replace("'", "''"));
else
kf = String.format("k like '%s'", kv.getKey().replace('*', '%').replace("'", "''"));
if (kv.isValueExactMatch())
vf = String.format("v='%s'", kv.getValue().replace("'", "''"));
else
vf = String.format("v like '%s'", kv.getValue().replace('*', '%').replace("'", "''"));
String where = String.format("(%s) AND (%s)", kf, vf);
return new WhereClause(String.format(baseQuery, where));
} else if (matcher instanceof AndMatcher) {
AndMatcher am = (AndMatcher) matcher;
WhereClause wcLeft = format(am.getLeft(), baseQuery);
WhereClause wcRight = format(am.getRight(), baseQuery);
return new WhereClause(String.format("(%s AND %s)", wcLeft.where, wcRight.where));
} else if (matcher instanceof OrMatcher) {
OrMatcher om = (OrMatcher) matcher;
WhereClause wcLeft = format(om.getLeft(), baseQuery);
WhereClause wcRight = format(om.getRight(), baseQuery);
return new WhereClause(String.format("(%s OR %s)", wcLeft.where, wcRight.where));
} else if (matcher instanceof NotMatcher) {
NotMatcher nm = (NotMatcher) matcher;
WhereClause wc = format(nm.getMatcher(), baseQuery);
return new WhereClause(String.format("(NOT %s)", wc.where));
} else {
throw new IllegalArgumentException("Unknown matcher type "+ Matcher.class.getName());
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import il.yrtimid.osm.osmpoi.logging.Log;
import il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* @author yrtimid
*
*/
public class DbAnalyzer extends DbCreator {
/**
* @param context
*/
public DbAnalyzer(Context context, File dbLocation) {
super(context, dbLocation);
}
public long getNodesCount() {
return getRowsCount(Queries.NODES_TABLE);
}
public long getWaysCount() {
return getRowsCount(Queries.WAYS_TABLE);
}
public long getRelationsCount() {
return getRowsCount(Queries.RELATIONS_TABLE);
}
public long getCellsCount() {
return getRowsCount(Queries.GRID_TABLE);
}
private long getRowsCount(String tableName) {
SQLiteDatabase db = null;
Cursor cur = null;
try {
db = getReadableDatabase();
cur = db.rawQuery("select count(*) from " + tableName, null);
if (cur.moveToFirst()) {
return cur.getLong(0);
}
return 0;
}catch(Exception e){
Log.wtf("getRowsCount for"+tableName, e);
return -1;
} finally {
if (cur != null) cur.close();
//if (db != null) db.close();
}
}
public Long getInlineResultsId(String query, String select){
SQLiteDatabase db;
Cursor cur = null;
try {
db = getReadableDatabase();
cur = db.rawQuery("select id from "+Queries.INLINE_QUERIES_TABLE+" where query=? and [select]=?", new String[]{query, select});
if (cur.moveToFirst()){
long id = cur.getLong(0);
if (id>0) return id;
}
return 0L;
}catch(Exception e){
Log.wtf("isInlineResultsExists", e);
return 0L;
}finally{
if (cur != null) cur.close();
}
}
public Long createInlineResults(String query, String select){
//query="shop=*"
TagMatcher matcher = TagMatcher.parse(query);
SQLiteDatabase db;
try {
db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("query", query);
cv.put("[select]", select);
Long id = db.insert(Queries.INLINE_QUERIES_TABLE, null, cv);
TagMatcherFormatter.WhereClause where = TagMatcherFormatter.format(matcher, "EXISTS (SELECT 1 FROM node_tags WHERE (%s) AND node_tags.node_id=nt.node_id)");
//TODO: add ways and relations
String baseQuery = "INSERT INTO inline_results (query_id, value) SELECT DISTINCT ?, nt.v FROM node_tags nt";
StringBuilder sb = new StringBuilder(baseQuery);
String sql = sb.toString()
+ " WHERE ("+ where.where +") AND nt.k like '"+select.replace('*', '%')+"'"
+ " ORDER BY nt.v"
+ " LIMIT 1000";
Log.d(sql);
db.execSQL(sql, new Object[]{id});
return id;
} catch (Exception e) {
Log.wtf("createInlineResults", e);
return 0L;
}
}
public Collection<String> getInlineResults(Long id){
SQLiteDatabase db = null;
Cursor cur = null;
Collection<String> result = new ArrayList<String>();
try {
db = getReadableDatabase();
cur = db.rawQuery("select value from "+Queries.INLINE_RESULTS_TABLE+" where query_id=?", new String[]{id.toString()});
if (cur.moveToFirst()){
do{
result.add(cur.getString(0));
}while(cur.moveToNext());
}
}catch(Exception e){
Log.wtf("getInlineResults", e);
}finally{
if (cur != null) cur.close();
}
return result;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
import il.yrtimid.osm.osmpoi.CancelFlag;
import il.yrtimid.osm.osmpoi.CollectionPipe;
import il.yrtimid.osm.osmpoi.Point;
import il.yrtimid.osm.osmpoi.SearchPipe;
import il.yrtimid.osm.osmpoi.Util;
import il.yrtimid.osm.osmpoi.domain.CommonEntityData;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import il.yrtimid.osm.osmpoi.domain.Node;
import il.yrtimid.osm.osmpoi.domain.Relation;
import il.yrtimid.osm.osmpoi.domain.RelationMember;
import il.yrtimid.osm.osmpoi.domain.Tag;
import il.yrtimid.osm.osmpoi.domain.Way;
import il.yrtimid.osm.osmpoi.logging.Log;
import il.yrtimid.osm.osmpoi.searchparameters.SearchAround;
import il.yrtimid.osm.osmpoi.searchparameters.SearchById;
import il.yrtimid.osm.osmpoi.searchparameters.SearchByKeyValue;
import il.yrtimid.osm.osmpoi.searchparameters.SearchByParentId;
import il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* @author yrtimid
*
*/
public class DbSearcher extends DbCreator {
private static final int SEARCH_SIZE = 20;
/**
* @param context
*/
public DbSearcher(Context context, File dbLocation) {
super(context, dbLocation);
}
/**
* Returns count grid cells around p point
*
* @param p
* point to get cells around
* @param count
* how much cells to return
* */
private List<Integer> getGrid(Point p, int count) {
SQLiteDatabase db = getReadableDatabase();
Cursor cur = null;
try {
cur = db.rawQuery("select id from grid order by (abs((minLat+maxLat)/2-?)+abs((minLon+maxLon)/2-?)) limit ?", new String[] { p.getLatitude().toString(), p.getLongitude().toString(), Integer.toString(count) });
List<Integer> ids = new ArrayList<Integer>();
if (cur.moveToFirst()) {
do {
ids.add(cur.getInt(0));
} while (cur.moveToNext());
}
return ids;
} catch (Exception e) {
Log.wtf("getGrid", e);
return null;
} finally {
if (cur != null)
cur.close();
}
}
/**
* Distance in meters up to most distant cell corner
*
* @param from
* @param cellId
* @return
*/
private Integer getDistanceToCell(Point from, int cellId) {
SQLiteDatabase db = getReadableDatabase();
Cursor cur = null;
Integer distance = 0;
try {
cur = db.rawQuery("select * from grid where id=?", new String[] { Integer.toString(cellId) });
if (cur.moveToFirst()) {
double minLat, minLon, maxLat, maxLon;
minLat = cur.getDouble(cur.getColumnIndex("minLat"));
minLon = cur.getDouble(cur.getColumnIndex("minLon"));
maxLat = cur.getDouble(cur.getColumnIndex("maxLat"));
maxLon = cur.getDouble(cur.getColumnIndex("maxLon"));
int d1 = from.getDistance(minLat, minLon);
int d2 = from.getDistance(minLat, maxLon);
int d3 = from.getDistance(maxLat, minLon);
int d4 = from.getDistance(maxLat, maxLon);
distance = Math.max(d1, Math.max(d2, Math.max(d3, d4)));
}
Log.d("Distance from "+from.toString()+" to cell "+cellId+" is "+distance);
return distance;
} catch (Exception e) {
Log.wtf("getDistanceToCell", e);
return null;
} finally {
if (cur != null)
cur.close();
}
}
public boolean findAroundPlace(SearchAround search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
return find(FindType.AROUND_PLACE, search.getCenter(), null, search.getMaxResults(), newItemNotifier, cancel);
}
public boolean findAroundPlaceByTag(SearchByKeyValue search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
return find(FindType.BY_TAG, search.getCenter(), search.getMatcher(), search.getMaxResults(), newItemNotifier, cancel);
}
public boolean findById(SearchById search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
return getById(search.getEntityType(), search.getId(), newItemNotifier, cancel);
}
public boolean findByParentId(SearchByParentId search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
return getByParentId(search, newItemNotifier, cancel);
}
private boolean getById(EntityType entityType, Long id, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
if (cancel.isCancelled())
return true;
Entity result = null;
Cursor cur = null;
try {
String sql = "SELECT * FROM " + entityTypeToTableName.get(entityType) + " WHERE id=?";
SQLiteDatabase db = getReadableDatabase();
cur = db.rawQuery(sql, new String[] { id.toString() });
if (cur.moveToFirst()) {
result = constructEntity(cur, entityType);
fillTags(result);
fillSubItems(result, cancel);
}
} catch (Exception e) {
Log.wtf("getById", e);
return false;
} finally {
if (cur != null)
cur.close();
}
if (result != null)
newItemNotifier.pushItem(result);
return true;
}
private enum FindType {
AROUND_PLACE, BY_TAG
}
/**
* Used for cases where result count isn't known
*/
private boolean find(FindType findType, Point point, TagMatcher tagMatcher, int maxResults, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
int nodesOffset = 0;
int waysOffset = 0;
int relationsOffset = 0;
int gridSize = 2;
boolean lastRun = false;
List<Integer> lastGrid = new ArrayList<Integer>();
try {
Cursor cur = null;
do {
List<Integer> grid = getGrid(point, gridSize * gridSize);
Log.d("Grid size: " + grid.size());
int radius = getDistanceToCell(point, grid.get(grid.size() - 1));
newItemNotifier.pushRadius(radius);
if (gridSize > 2) { // not first run, the whole grid may have
// only one cell
if (gridSize * gridSize > grid.size()) {
if (grid.size() > ((gridSize - 1) * (gridSize - 1)))// new grid bigger than previous
lastRun = true;
else
return true;
}
}
grid.removeAll(lastGrid);
lastGrid.addAll(grid);
Integer[] gridIds = grid.toArray(new Integer[grid.size()]);
int nodesCount = 0;
int waysCount = 0;
int relationsCount = 0;
switch (findType) {
case AROUND_PLACE:
cur = getNodesAroundPlace(point, gridIds, maxResults > SEARCH_SIZE ? SEARCH_SIZE : maxResults, nodesOffset);
nodesCount = readEntities(cur, EntityType.Node, maxResults, newItemNotifier, cancel);
cur.close();
cur = getWaysAroundPlace(point, gridIds, maxResults > SEARCH_SIZE ? SEARCH_SIZE : maxResults, waysOffset);
waysCount = readEntities(cur, EntityType.Way, maxResults, newItemNotifier, cancel);
cur.close();
cur = getRelationsAroundPlace(point, gridIds, maxResults > SEARCH_SIZE ? SEARCH_SIZE : maxResults, relationsOffset);
relationsCount = readEntities(cur, EntityType.Relation, maxResults, newItemNotifier, cancel);
cur.close();
break;
case BY_TAG:
cur = getNodesAroundPlaceByTag(point, gridIds, tagMatcher, maxResults > SEARCH_SIZE ? SEARCH_SIZE : maxResults, nodesOffset);
nodesCount = readEntities(cur, EntityType.Node, maxResults, newItemNotifier, cancel);
cur.close();
cur = getWaysAroundPlaceByTag(point, gridIds, tagMatcher, maxResults > SEARCH_SIZE ? SEARCH_SIZE : maxResults, waysOffset);
waysCount = readEntities(cur, EntityType.Way, maxResults, newItemNotifier, cancel);
cur.close();
cur = getRelationsAroundPlaceByTag(point, gridIds, tagMatcher, maxResults > SEARCH_SIZE ? SEARCH_SIZE : maxResults, relationsOffset);
relationsCount = readEntities(cur, EntityType.Relation, maxResults, newItemNotifier, cancel);
cur.close();
break;
}
Log.d((nodesCount + waysCount) + " results");
nodesOffset += nodesCount;
waysOffset += waysCount;
relationsOffset += relationsCount;
maxResults -= nodesCount;
maxResults -= waysCount;
maxResults -= relationsCount;
if ((nodesCount + waysCount + relationsCount) == 0 && maxResults > 0) {// query returned no results - it's time to wider search
gridSize++;
}
} while (maxResults > 0 && cancel.isNotCancelled() && !lastRun);
return true;
} catch (Exception e) {
Log.wtf("findAroundPlace", e);
return false;
} finally {
}
}
/**
* @param maxResults
* negative number or zero - no limit
*/
private int readEntities(Cursor cur, EntityType entityType, int maxResults, SearchPipe<Entity> notifier, CancelFlag cancel) {
int count = 0;
try {
if (cur.moveToFirst()) {
do {
Entity entity = constructEntity(cur, entityType);
fillTags(entity);
fillSubItems(entity, cancel);
notifier.pushItem(entity);
maxResults--;
count++;
if (maxResults == 0)
break;
} while (cur.moveToNext() && cancel.isNotCancelled());
}
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
private int readMembers(Cursor cur, EntityType entityType, SearchPipe<RelationMember> pipe, CancelFlag cancel) {
int count = 0;
Entity entity;
try {
if (cur.moveToFirst()) {
do {
entity = constructEntity(cur, entityType);
fillTags(entity);
fillSubItems(entity, cancel);
String role = cur.getString(cur.getColumnIndex("role"));
if (entity != null){
RelationMember rm = new RelationMember(entity, role);
pipe.pushItem(rm);
count++;
}
} while (cur.moveToNext() && cancel.isNotCancelled());
}
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
private Cursor getNodesAroundPlace(Point point, Integer[] gridIds, Integer limit, Integer offset) {
SQLiteDatabase db;
try {
db = getReadableDatabase();
String inClause = "grid_id in (" + Util.join(",", (Object[]) gridIds) + ")";
String query = "select id, timestamp, lat, lon" + " from nodes" + " where " + inClause + " order by (abs(lat-?)+abs(lon-?))" + " limit ? offset ?";
String[] args = new String[] { point.getLatitude().toString(), point.getLongitude().toString(), limit.toString(), offset.toString() };
Log.d(query);
Log.d(Util.join(", ", (Object[]) args));
Cursor cur = db.rawQuery(query, args);
return cur;
} catch (Exception e) {
Log.wtf("getNodesAroundPlace", e);
return null;
}
}
private Cursor getWaysAroundPlace(Point point, Integer[] gridIds, Integer limit, Integer offset) {
SQLiteDatabase db;
try {
db = getReadableDatabase();
String inClause = "grid_id in (" + Util.join(",", (Object[]) gridIds) + ")";
String query = "select ways.id as id, nodes.id as node_id, ways.timestamp, lat, lon"
+ " from ways"
+ " inner join way_nodes on ways.id=way_nodes.way_id"
+ " inner join nodes on way_nodes.node_id=nodes.id"
+ " where " + inClause
+ " order by (abs(lat-?)+abs(lon-?))"
+ " limit ? offset ?";
String[] args = new String[] { point.getLatitude().toString(), point.getLongitude().toString(), limit.toString(), offset.toString() };
Log.d(query);
Log.d(Util.join(", ", (Object[]) args));
Cursor cur = db.rawQuery(query, args);
return cur;
} catch (Exception e) {
Log.wtf("getWaysAroundPlace", e);
return null;
}
}
// TODO: implement
private Cursor getRelationsAroundPlace(Point point, Integer[] gridIds, Integer limit, Integer offset) {
SQLiteDatabase db;
try {
db = getReadableDatabase();
String inClause = "grid_id in (" + Util.join(",", (Object[]) gridIds) + ")";
String query ="select relations.id as id, relations.timestamp"
+ " from relations"
+ " inner join members on relations.id = members.relation_id"
+ " inner join nodes on members.ref = nodes.id and members.type = 'Node'"
+ " where " + inClause
+ " order by (abs(lat-?) + abs(lon-?))"
+ " union all"
+ " select relations.id as id, relations.timestamp"
+ " from relations"
+ " inner join members on relations.id = members.relation_id"
+ " inner join ways on members.ref = ways.id and members.type = 'Way'"
+ " inner join way_nodes on ways.id = way_nodes.way_id"
+ " inner join nodes on way_nodes.node_id = nodes.id"
+ " where " + inClause
+ " order by (abs(lat-?) + abs(lon-?))";
String outerQuery = "select * from ("+query+")v"
+ " limit ? offset ?";
String[] args = new String[] { point.getLatitude().toString(), point.getLongitude().toString(),
point.getLatitude().toString(), point.getLongitude().toString(),
limit.toString(), offset.toString() };
Log.d(outerQuery);
Log.d(Util.join(", ", (Object[]) args));
Cursor cur = db.rawQuery(outerQuery, args);
return cur;
} catch (Exception e) {
Log.wtf("getRelationsAroundPlace", e);
return null;
}
}
private Cursor getNodesAroundPlaceByTag(Point point, Integer[] gridIds, TagMatcher matcher, Integer limit, Integer offset) {
SQLiteDatabase db;
try {
String inClause = "grid_id in (" + Util.join(",", (Object[]) gridIds) + ")";
TagMatcherFormatter.WhereClause where = TagMatcherFormatter.format(matcher, "EXISTS (SELECT 1 FROM node_tags WHERE (%s) AND node_tags.node_id=nodes.id)");
String query = "select distinct nodes.id, timestamp, lat, lon from nodes"
+ " where " + inClause + " AND ( " + where.where + " )"
+ " order by (abs(lat-?) + abs(lon-?))"
+ " limit ? offset ?";
String[] args = new String[] { point.getLatitude().toString(), point.getLongitude().toString(), limit.toString(), offset.toString() };
Log.d(query);
Log.d(Util.join(", ", (Object[]) args));
db = getReadableDatabase();
Cursor cur = db.rawQuery(query, args);
return cur;
} catch (Exception e) {
Log.wtf("getNodesAroundPlaceByTag", e);
return null;
}
}
private Cursor getWaysAroundPlaceByTag(Point point, Integer[] gridIds, TagMatcher matcher, Integer limit, Integer offset) {
SQLiteDatabase db;
try {
db = getReadableDatabase();
String inClause = "grid_id in (" + Util.join(",", (Object[]) gridIds) + ")";
TagMatcherFormatter.WhereClause where = TagMatcherFormatter.format(matcher, "EXISTS (SELECT 1 FROM way_tags WHERE (%s) AND way_tags.way_id=ways.id)");
String query = "select distinct ways.id as id, nodes.id as node_id, ways.timestamp, nodes.lat, nodes.lon from ways"
+ " inner join way_nodes on ways.id = way_nodes.way_id"
+ " inner join nodes on way_nodes.node_id = nodes.id"
+ " where " + inClause + " AND (" + where.where + ")"
+ " group by ways.id"
+ " order by (abs(lat-?) + abs(lon-?))"
+ " limit ? offset ?";
String[] args = new String[] { point.getLatitude().toString(), point.getLongitude().toString(), limit.toString(), offset.toString() };
Log.d(query);
Log.d(Util.join(", ", (Object[]) args));
Cursor cur = db.rawQuery(query, args);
return cur;
} catch (Exception e) {
Log.wtf("getWaysAroundPlaceByTag", e);
return null;
}
}
/**
* Ignores point, just searches for any relation accordingly to matcher
*
* @param point
* @param gridIds
* @param matcher
* @param limit
* @param offset
* @return
*/
private Cursor getRelationsAroundPlaceByTag(Point point, Integer[] gridIds, TagMatcher matcher, Integer limit, Integer offset) {
SQLiteDatabase db;
try {
db = getReadableDatabase();
TagMatcherFormatter.WhereClause where = TagMatcherFormatter.format(matcher, "EXISTS (SELECT 1 FROM relation_tags WHERE (%s) AND relation_tags.relation_id=relations.id)");
String inClause = "grid_id in (" + Util.join(",", (Object[]) gridIds) + ")";
String query ="select relations.id as id, relations.timestamp, nodes.lat, nodes.lon"
+ " from relations"
+ " inner join members on relations.id = members.relation_id"
+ " inner join nodes on members.ref = nodes.id and members.type = 'Node'"
+ " where " + inClause + " AND ("+where.where+")"
+ " union all"
+ " select relations.id as id, relations.timestamp, nodes.lat, nodes.lon"
+ " from relations"
+ " inner join members on relations.id = members.relation_id"
+ " inner join ways on members.ref = ways.id and members.type = 'Way'"
+ " inner join way_nodes on ways.id = way_nodes.way_id"
+ " inner join nodes on way_nodes.node_id = nodes.id"
+ " where " + inClause + " AND ("+where.where+")";
String outerQuery = "select id, timestamp from ("+query+")v"
+ " order by (abs(lat-?) + abs(lon-?))"
+ " limit ? offset ?";
String[] args = new String[] { point.getLatitude().toString(), point.getLongitude().toString(),
limit.toString(), offset.toString() };
Log.d(outerQuery);
Log.d(Util.join(", ", (Object[]) args));
Cursor cur = db.rawQuery(outerQuery, args);
return cur;
} catch (Exception e) {
Log.wtf("getRelationsAroundPlaceByTag", e);
return null;
}
}
private boolean getByParentId(SearchByParentId search, final SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
if (cancel.isCancelled())
return true;
switch (search.getEntityType()) {
case Node:
return true;
case Way:
return getNodesByWayId(search, newItemNotifier, cancel);
case Relation:
SearchPipe<RelationMember> pipe = new SearchPipe<RelationMember>() {
@Override
public void pushItem(RelationMember item) {
newItemNotifier.pushItem(item.getMember());
}
@Override
public void pushRadius(int radius) {
newItemNotifier.pushRadius(radius);
}
};
return getMembersByRelationId(search, pipe, cancel);
default:
break;
}
return false;
}
/**
*
* @param search
* if search has result count limiting - the center point will be used to find N nearest objects
*/
private boolean getNodesByWayId(SearchByParentId search, SearchPipe<Entity> notifier, CancelFlag cancel) {
Cursor cur = null;
Long wayId = search.getId();
try {
SQLiteDatabase db = getReadableDatabase();
String sql = "SELECT n.* FROM " + Queries.NODES_TABLE + " n INNER JOIN " + Queries.WAY_NODES_TABLE + " w ON n.id=w.node_id WHERE w.way_id=?";
String[] args;
if (search.getMaxResults() > 0) {
sql += " order by (abs(lat-?)+abs(lon-?)) limit ?";
args = new String[] { wayId.toString(), search.getCenter().getLatitude().toString(), search.getCenter().getLongitude().toString(), search.getMaxResults().toString() };
} else {
args = new String[] { wayId.toString() };
}
cur = db.rawQuery(sql, args);
readEntities(cur, EntityType.Node, search.getMaxResults(), notifier, cancel);
} catch (Exception e) {
Log.wtf("getNodesByWayId", e);
return false;
} finally {
if (cur != null)
cur.close();
}
return true;
}
/*private boolean getNodesAndWaysByRelationId(SearchByParentId search, SearchPipe<Entity> notifier, CancelFlag cancel) {
Cursor cur = null;
Long relationId = search.getId();
try {
SQLiteDatabase db = getReadableDatabase();
Integer maxResults = search.getMaxResults();
String sql = "SELECT n.* FROM " + NODES_TABLE + " n INNER JOIN " + MEMBERS_TABLE + " m ON m.Type='" + EntityType.Node + "' AND n.id=m.ref WHERE m.relation_id=?";
String[] args;
if (maxResults > 0) {
sql += " order by (abs(lat-?)+abs(lon-?)) limit ?";
args = new String[] { relationId.toString(), search.getCenter().getLatitude().toString(), search.getCenter().getLongitude().toString(), maxResults.toString() };
} else {
args = new String[] { relationId.toString() };
}
Log.d(sql);
cur = db.rawQuery(sql, args);
maxResults -= readEntities(cur, EntityType.Node, maxResults, notifier, cancel);
cur.close();
if (maxResults > 0) {
sql = "SELECT w.* FROM " + WAYS_TABLE + " w INNER JOIN " + MEMBERS_TABLE + " m ON m.Type='" + EntityType.Way + "' AND w.id=m.ref WHERE m.relation_id=?";
Log.d(sql);
cur = db.rawQuery(sql, new String[] { relationId.toString() });
maxResults -= readEntities(cur, EntityType.Way, maxResults, notifier, cancel);
cur.close();
}
if (maxResults > 0) {
sql = "SELECT r.* FROM " + RELATIONS_TABLE + " r INNER JOIN " + MEMBERS_TABLE + " m ON m.Type='" + EntityType.Relation + "' AND r.id=m.ref WHERE m.relation_id=?";
Log.d(sql);
cur = db.rawQuery(sql, new String[] { relationId.toString() });
maxResults -= readEntities(cur, EntityType.Relation, maxResults, notifier, cancel);
cur.close();
}
} catch (Exception e) {
Log.wtf("getNodesAndWaysByRelationId", e);
return false;
} finally {
if (cur != null)
cur.close();
}
return true;
}*/
private boolean getMembersByRelationId(SearchByParentId search, SearchPipe<RelationMember> pipe, CancelFlag cancel) {
Cursor cur = null;
Long relationId = search.getId();
try {
SQLiteDatabase db = getReadableDatabase();
Integer maxResults = search.getMaxResults();
String sql = "SELECT n.*, role FROM " + Queries.NODES_TABLE + " n INNER JOIN " + Queries.MEMBERS_TABLE + " m ON m.Type='" + EntityType.Node + "' AND n.id=m.ref WHERE m.relation_id=?";
sql += " order by (abs(lat-?)+abs(lon-?))";
String[] args;
if (maxResults > 0) {
sql += " limit ?";
args = new String[] { relationId.toString(), search.getCenter().getLatitude().toString(), search.getCenter().getLongitude().toString(), maxResults.toString() };
} else {
args = new String[] { relationId.toString(), search.getCenter().getLatitude().toString(), search.getCenter().getLongitude().toString() };
}
Log.d(sql);
cur = db.rawQuery(sql, args);
maxResults -= readMembers(cur, EntityType.Node, pipe, cancel);
cur.close();
if (maxResults > 0) {
sql = "SELECT w.*, role FROM " + Queries.WAYS_TABLE + " w INNER JOIN " + Queries.MEMBERS_TABLE + " m ON m.Type='" + EntityType.Way + "' AND w.id=m.ref WHERE m.relation_id=?";
Log.d(sql);
cur = db.rawQuery(sql, new String[] { relationId.toString() });
maxResults -= readMembers(cur, EntityType.Way, pipe, cancel);
cur.close();
}
if (maxResults > 0) {
sql = "SELECT r.*, role FROM " + Queries.RELATIONS_TABLE + " r INNER JOIN " + Queries.MEMBERS_TABLE + " m ON m.Type='" + EntityType.Relation + "' AND r.id=m.ref WHERE m.relation_id=?";
Log.d(sql);
cur = db.rawQuery(sql, new String[] { relationId.toString() });
maxResults -= readMembers(cur, EntityType.Relation, pipe, cancel);
cur.close();
}
} catch (Exception e) {
Log.wtf("getNodesAndWaysByRelationId", e);
return false;
} finally {
if (cur != null)
cur.close();
}
return true;
}
private void fillTags(Entity entity) {
Collection<Tag> tags = entity.getTags();
SQLiteDatabase db = null;
Cursor cur = null;
try {
db = getReadableDatabase();
String sql = null;
switch(entity.getType()){
case Node:
sql = "select k,v from " + Queries.NODES_TAGS_TABLE + " where node_id = ?";
break;
case Way:
sql = "select k,v from " + Queries.WAY_TAGS_TABLE + " where way_id = ?";
break;
case Relation:
sql = "select k,v from " + Queries.RELATION_TAGS_TABLE + " where relation_id = ?";
break;
default:
break;
}
cur = db.rawQuery(sql, new String[] { Long.toString(entity.getId()) });
if (cur.moveToFirst()) {
do {
Tag t = constructTag(cur);
tags.add(t);
} while (cur.moveToNext());
}
} catch (Exception e) {
Log.wtf("fillTags for "+entity.getType().name()+", with id "+entity.getId(), e);
} finally {
if (cur != null)
cur.close();
}
}
private CommonEntityData constructEntity(Cursor cur) {
long id = cur.getLong(cur.getColumnIndex("id"));
long timestamp = cur.getLong(cur.getColumnIndex("timestamp"));
CommonEntityData entityData = new CommonEntityData(id, timestamp);
return entityData;
}
private Entity constructEntity(Cursor cur, EntityType entityType){
switch (entityType) {
case Node:
return constructNode(cur);
case Way:
return constructWay(cur);
case Relation:
return constructRelation(cur);
}
return null;
}
private Node constructNode(Cursor cur) {
CommonEntityData entityData = constructEntity(cur);
Double lat = cur.getDouble(cur.getColumnIndex("lat"));
Double lon = cur.getDouble(cur.getColumnIndex("lon"));
return new Node(entityData, lat, lon);
}
private Tag constructTag(Cursor cur) {
String k = cur.getString(cur.getColumnIndex("k"));
String v = cur.getString(cur.getColumnIndex("v"));
return new Tag(k, v);
}
private Way constructWay(Cursor cur) {
CommonEntityData entityData = constructEntity(cur);
Way w = new Way(entityData);
return w;
}
private Relation constructRelation(Cursor cur) {
CommonEntityData entityData = constructEntity(cur);
Relation rel = new Relation(entityData);
return rel;
}
private void fillSubItems(Entity entity, CancelFlag cancel){
SearchByParentId search = new SearchByParentId(entity.getType(), entity.getId());
switch(entity.getType()){
case Node:
break;
case Way:
{
CollectionPipe<Entity> pipe = new CollectionPipe<Entity>();
getNodesByWayId(search, pipe, cancel);
List<Node> list = ((Way)entity).getNodes();
for(Entity e: pipe.getItems()){
list.add((Node)e);
}
}
break;
case Relation:
{
CollectionPipe<RelationMember> pipe = new CollectionPipe<RelationMember>();
getMembersByRelationId(search, pipe, cancel);
((Relation)entity).getMembers().addAll(pipe.getItems());
}
break;
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
import il.yrtimid.osm.osmpoi.Util;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.logging.Log;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/**
* @author yrtimid
*
*/
public class CachedDbOpenHelper extends DbFiller implements IDbCachedFiller {
private static int MAX_QUEUE_SIZE = 200;
private Boolean flushing = false;
private Collection<Node> addNodeIfBelongToWayQueue = new ArrayList<Node>();
private Collection<Node> addNodeIfBelongToRelationQueue = new ArrayList<Node>();
private Collection<Way> addWayIfBelongToRelationQueue = new ArrayList<Way>();
/**
* @param context
*/
public CachedDbOpenHelper(Context context, File dbLocation) {
super(context, dbLocation);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#beginAdd()
*/
@Override
public void beginAdd(){
SQLiteDatabase db = getWritableDatabase();
db.beginTransaction();
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#endAdd()
*/
@Override
public void endAdd(){
try{
flushing = true;
addNodeIfBelongsToWay(null);
addNodeIfBelongsToRelation(null);
addWayIfBelongsToRelation(null);
flushing = false;
SQLiteDatabase db = getWritableDatabase();
db.setTransactionSuccessful();
db.endTransaction();
}catch(Exception ex){
Log.wtf("endAdd failed", ex);
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#addNodeIfBelongsToWay(il.yrtimid.osm.osmpoi.domain.Node)
*/
@Override
public void addNodeIfBelongsToWay(Node node) throws SQLException{
if (node != null){
addNodeIfBelongToWayQueue.add(node);
}
if (flushing || addNodeIfBelongToWayQueue.size()>=MAX_QUEUE_SIZE){
ArrayList<Long> ids = new ArrayList<Long>(addNodeIfBelongToWayQueue.size());
for(Node n:addNodeIfBelongToWayQueue){
ids.add(n.getId());
}
HashSet<Long> neededIds = new HashSet<Long>();
String inClause = Util.join(",", ids.toArray());
SQLiteDatabase db = getWritableDatabase();
Cursor cur = null;
try{
Log.d("Checking nodes in ways: "+inClause);
cur = db.rawQuery("SELECT node_id FROM "+Queries.WAY_NODES_TABLE+" WHERE node_id in ("+inClause+")", null);
if (cur.moveToFirst()){
do{
neededIds.add(cur.getLong(0));
}while(cur.moveToNext());
}
}catch(Exception e){
Log.wtf("addNodeIfBelongsToWay ids in "+inClause, e);
}finally{
if (cur!=null) cur.close();
}
for(Node n:addNodeIfBelongToWayQueue){
if (neededIds.contains(n.getId())){
super.addNode(n);
}
}
addNodeIfBelongToWayQueue.clear();
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#addNodeIfBelongsToRelation(il.yrtimid.osm.osmpoi.domain.Node)
*/
@Override
public void addNodeIfBelongsToRelation(Node node) throws SQLException{
if (node != null){
addNodeIfBelongToRelationQueue.add(node);
}
if (flushing || addNodeIfBelongToRelationQueue.size()>=MAX_QUEUE_SIZE){
ArrayList<Long> ids = new ArrayList<Long>(addNodeIfBelongToRelationQueue.size());
for(Node n:addNodeIfBelongToRelationQueue){
ids.add(n.getId());
}
HashSet<Long> neededIds = new HashSet<Long>();
String inClause = Util.join(",", ids.toArray());
SQLiteDatabase db = getWritableDatabase();
Cursor cur = null;
try{
Log.d("Checking nodes in relations: "+inClause);
cur = db.rawQuery("SELECT ref FROM "+Queries.MEMBERS_TABLE+" WHERE type='NODE' AND ref in ("+inClause+")", null);
if (cur.moveToFirst()){
do{
neededIds.add(cur.getLong(0));
}while(cur.moveToNext());
}
}catch(Exception e){
Log.wtf("addNodeIfBelongsToRelation ids in "+inClause, e);
}finally{
if (cur!=null) cur.close();
}
for(Node n:addNodeIfBelongToRelationQueue){
if (neededIds.contains(n.getId())){
super.addNode(n);
}
}
addNodeIfBelongToRelationQueue.clear();
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#addWayIfBelongsToRelation(il.yrtimid.osm.osmpoi.domain.Way)
*/
@Override
public void addWayIfBelongsToRelation(Way way) throws SQLException{
if (way != null){
addWayIfBelongToRelationQueue.add(way);
}
if (flushing || addWayIfBelongToRelationQueue.size()>=MAX_QUEUE_SIZE){
ArrayList<Long> ids = new ArrayList<Long>(addWayIfBelongToRelationQueue.size());
for(Way w:addWayIfBelongToRelationQueue){
ids.add(w.getId());
}
HashSet<Long> neededIds = new HashSet<Long>();
String inClause = Util.join(",", ids.toArray());
SQLiteDatabase db = getWritableDatabase();
Cursor cur = null;
try{
Log.d("Checking ways in relations: "+inClause);
cur = db.rawQuery("SELECT ref FROM "+Queries.MEMBERS_TABLE+" WHERE type='WAY' AND ref in ("+inClause+")", null);
if (cur.moveToFirst()){
do{
neededIds.add(cur.getLong(0));
}while(cur.moveToNext());
}
}catch(Exception e){
Log.wtf("addWayIfBelongsToRelation ids in "+inClause, e);
}finally{
if (cur!=null) cur.close();
}
for(Way w:addWayIfBelongToRelationQueue){
if (neededIds.contains(w.getId())){
super.addWay(w);
}
}
addWayIfBelongToRelationQueue.clear();
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import il.yrtimid.osm.osmpoi.categories.Category;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import il.yrtimid.osm.osmpoi.logging.Log;
import il.yrtimid.osm.osmpoi.searchparameters.SearchById;
/**
* @author yrtimid
*
*/
public class DbStarred extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected Context context;
/**
* @param context
* @param name
* @param factory
* @param version
*/
public DbStarred(Context context, File dbLocation) {
super(context, dbLocation.getPath(), null, DATABASE_VERSION);
this.context = context;
}
/*
* (non-Javadoc)
*
* @see
* android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
* .SQLiteDatabase)
*/
@Override
public void onCreate(SQLiteDatabase db) {
createAllTables(db);
}
/*
* (non-Javadoc)
*
* @see
* android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
* .SQLiteDatabase, int, int)
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
protected void createAllTables(SQLiteDatabase db){
db.execSQL(Queries.SQL_CREATE_STARRED_TABLE);
}
protected void dropAllTables(SQLiteDatabase db){
db.beginTransaction();
try{
db.execSQL("DROP TABLE IF EXISTS "+Queries.STARRED_TABLE);
db.setTransactionSuccessful();
}catch(Exception e){
Log.wtf("dropAllTables", e);
}finally{
db.endTransaction();
}
db.execSQL("VACUUM");
}
public void addStarred(Entity entity, String title){
SQLiteDatabase db = null;
try{
db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("type", entity.getType().name());
values.put("id", entity.getId());
values.put("title", title);
db.insertWithOnConflict(Queries.STARRED_TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}catch (Exception e) {
Log.wtf("addStarred",e);
}finally{
if (db != null) db.close();
}
}
public void removeStarred(Entity entity){
SQLiteDatabase db = null;
try{
db = getWritableDatabase();
db.delete(Queries.STARRED_TABLE, "type=? AND id=?", new String[] {entity.getType().name(), Long.toString(entity.getId())});
}catch(Exception e){
Log.wtf("removeStarred",e);
}finally{
if (db != null) db.close();
}
}
public Boolean isStarred(Entity entity){
SQLiteDatabase db = null;
Cursor cur = null;
try{
db = getReadableDatabase();
cur = db.rawQuery("SELECT 1 FROM "+Queries.STARRED_TABLE+" WHERE type=? AND id=?", new String[] {entity.getType().name(), Long.toString(entity.getId())});
boolean hasResults = (cur.moveToFirst());
return hasResults;
}catch(Exception e){
Log.wtf("isStarred",e);
return false;
}finally{
if (cur != null) cur.close();
if (db != null) db.close();
}
}
public Collection<Category> getAllStarred(){
SQLiteDatabase db = null;
Cursor cur = null;
Collection<Category> results = new ArrayList<Category>();
try{
db = getReadableDatabase();
cur = db.rawQuery("SELECT * FROM "+Queries.STARRED_TABLE, null);
if (cur.moveToFirst()){
do{
String title = cur.getString(cur.getColumnIndex("title"));
String type = cur.getString(cur.getColumnIndex("type"));
Long id = cur.getLong(cur.getColumnIndex("id"));
Category cat = new Category(Category.Type.SEARCH);
cat.setLocalizable(false);
cat.setName(title);
EntityType entityType = Enum.valueOf(EntityType.class, type);
cat.setSearchParameter(new SearchById(entityType, id));
results.add(cat);
}while(cur.moveToNext());
}
}catch(Exception e){
Log.wtf("getAllStarred",e);
}finally{
if (cur != null) cur.close();
if (db != null) db.close();
}
return results;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
/**
* @author yrtimid
*
*/
public interface SearchPipe<T> extends ItemPipe<T> {
public void pushRadius(int radius);
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.formatters;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import il.yrtimid.osm.osmpoi.domain.Entity;
/**
* @author yrtimid
*
*/
public class TagSelector {
private String pattern;
private static Pattern tagNamePattern = Pattern.compile("\\{([^\\}]+)\\}");
private Collection<String> tagsInPattern = new ArrayList<String>();
public TagSelector(String pattern) {
this.pattern = pattern;
Matcher tagMatcher = tagNamePattern.matcher(this.pattern);
while(tagMatcher.find()){
String name = tagMatcher.group(1);
tagsInPattern.add(name);
}
}
public String select(Entity entity, CharSequence localPostfix){
if (tagsInPattern.size()>0){
String result = pattern;
Map<String,String> tags = entity.getTags().buildMap();
for(String tagName:tagsInPattern){
if (tags.containsKey(tagName+":"+localPostfix)) //trying local tag
result = result.replace("{"+tagName+"}", tags.get(tagName+":"+localPostfix));
if (tags.containsKey(tagName)) //trying normal tag
result = result.replace("{"+tagName+"}", tags.get(tagName));
if (tags.containsKey(tagName+":en")) //fall back to english version
result = result.replace("{"+tagName+"}", tags.get(tagName+":en"));
else //nothing found, remove place holder
result = result.replace("{"+tagName+"}", "");
}
return result;
}else {
return pattern;
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.formatters;
import il.yrtimid.osm.osmpoi.logging.Log;
import il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.content.Context;
/**
* @author yrtimid
*
*/
public class EntityFormattersLoader {
public static List<EntityFormatter> load(Context context){
List<EntityFormatter> formatters = new ArrayList<EntityFormatter>();
InputStream xmlStream = null;
try {
xmlStream = context.getAssets().open("entity_formatters.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlStream);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getDocumentElement().getElementsByTagName("formatter");
for (int i = 0; i < nodes.getLength(); i++) {
Element ele = (Element)nodes.item(i);
String match = ele.getAttribute("match");
String selectPattern = ele.getAttribute("select_pattern");
TagMatcher matcher = TagMatcher.parse(match);
TagSelector selector = new TagSelector(selectPattern);
formatters.add(new EntityFormatter(matcher, selector));
}
}catch(SAXException e){
Log.wtf("can't parse entity_formatters.xml", e);
}catch (ParserConfigurationException e){
Log.wtf("can't create parser", e);
} catch (IOException e) {
Log.wtf("can't open entity_formatters.xml", e);
}finally{
try {
if (xmlStream != null)
xmlStream.close();
} catch (IOException e) {
Log.wtf("Closing entity_formatters.xml stream", e);
}
}
return formatters;
}
}
| Java |
package il.yrtimid.osm.osmpoi.formatters;
import java.util.List;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher;
/**
* @author yrtimid
*
*/
public class EntityFormatter {
TagMatcher matcher;
TagSelector selector;
public EntityFormatter(TagMatcher matcher, TagSelector selector) {
this.matcher = matcher;
this.selector = selector;
}
public static String format(List<EntityFormatter> formatters, Entity entity, CharSequence localPostfix){
for(EntityFormatter formatter : formatters){
if (formatter.matcher.isMatch(entity))
return formatter.selector.select(entity, localPostfix);
}
return "ID: "+Long.toString(entity.getId());
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.searchparameters.*;
/**
* @author yrtimid
*
*/
public interface ISearchSource {
//public abstract boolean isSupportsCancel();
public void search(BaseSearchParameter search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel);
// public void getByDistance(SearchAround search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel);
// public void getByDistanceAndKeyValue(SearchByKeyValue search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel);
// public void getById(SearchById search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel);
// public void getByParentId(SearchByParentId search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel);
public abstract void close();
public abstract String getName();
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import android.os.Parcel;
import android.os.Parcelable;
/**
* A data class representing a single member within a relation entity.
*
* @author Brett Henderson
*/
public class ParcelableRelationMember implements Parcelable {
protected RelationMember member;
public ParcelableRelationMember(RelationMember member){
this.member = member;
}
/**
* @param source
*/
public ParcelableRelationMember(Parcel source) {
member = new RelationMember();
member.setMemberRole(source.readString());
EntityType memberType = Enum.valueOf(EntityType.class, source.readString());
//TODO: check creating from parcel
ParcelableEntity pEntity = source.readParcelable(Entity.class.getClassLoader());
this.member.setMember(pEntity.getEntity());
}
/**
* @return the member
*/
public RelationMember getMember() {
return member;
}
public static final Parcelable.Creator<ParcelableRelationMember> CREATOR = new Parcelable.Creator<ParcelableRelationMember>() {
@Override
public ParcelableRelationMember createFromParcel(Parcel source) {
return new ParcelableRelationMember(source);
}
@Override
public ParcelableRelationMember[] newArray(int size) {
return new ParcelableRelationMember[size];
}
};
/* (non-Javadoc)
* @see android.os.Parcelable#describeContents()
*/
@Override
public int describeContents() {
return 0;
}
/* (non-Javadoc)
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(member.getMemberRole());
dest.writeString(member.getMemberType().name());
switch(member.getMemberType()){
case Node:
dest.writeParcelable(new ParcelableNode((Node)member.getMember()), flags);
break;
case Way:
dest.writeParcelable(new ParcelableWay((Way)member.getMember()), flags);
break;
case Relation:
dest.writeParcelable(new ParcelableRelation((Relation)member.getMember()), flags);
break;
default:
break;
}
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import android.os.Parcel;
import android.os.Parcelable;
/**
* A data class representing a single OSM tag.
*
* @author Brett Henderson
*/
public class ParcelableTag implements Parcelable {
private Tag tag;
public ParcelableTag(Tag tag){
this.tag = tag;
}
/**
* @param source
*/
public ParcelableTag(Parcel source) {
String key = source.readString();
String value = source.readString();
this.tag = new Tag(key, value);
}
public Tag getTag(){
return tag;
}
public static final Parcelable.Creator<ParcelableTag> CREATOR = new Parcelable.Creator<ParcelableTag>() {
@Override
public ParcelableTag createFromParcel(Parcel source) {
return new ParcelableTag(source);
}
@Override
public ParcelableTag[] newArray(int size) {
return new ParcelableTag[size];
}
};
/*
* (non-Javadoc)
*
* @see android.os.Parcelable#describeContents()
*/
@Override
public int describeContents() {
return 0;
}
/*
* (non-Javadoc)
*
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(tag.getKey());
dest.writeString(tag.getValue());
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import android.os.Parcel;
import android.os.Parcelable;
public class ParcelableNode extends ParcelableEntity implements Parcelable {
protected Node node;
public ParcelableNode(Node node) {
super(node);
this.node = node;
}
/**
* @param source
*/
public ParcelableNode(Parcel source) {
this(new Node());
super.readFromParcel(this.node, source);
node.setLatitude(source.readDouble());
node.setLongitude(source.readDouble());
}
/**
* @return the node
*/
public Node getNode() {
return node;
}
public static final Parcelable.Creator<ParcelableNode> CREATOR = new Parcelable.Creator<ParcelableNode>() {
@Override
public ParcelableNode createFromParcel(Parcel source) {
return new ParcelableNode(source);
}
@Override
public ParcelableNode[] newArray(int size) {
return new ParcelableNode[size];
}
};
/*
* (non-Javadoc)
*
* @see android.os.Parcelable#describeContents()
*/
@Override
public int describeContents() {
return 0;
}
/*
* (non-Javadoc)
*
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeDouble(node.getLatitude());
dest.writeDouble(node.getLongitude());
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.ArrayList;
import java.util.List;
import android.os.Parcel;
import android.os.Parcelable;
/**
* A data class representing a single OSM way.
*
* @author Brett Henderson
*/
public class ParcelableWay extends ParcelableEntity implements Parcelable {
protected Way way;
/**
*
*/
public ParcelableWay(Way way) {
super(way);
this.way = way;
}
/**
* @param source
*/
public ParcelableWay(Parcel source) {
this(new Way());
super.readFromParcel(way, source);
List<ParcelableNode> pWayNodes = new ArrayList<ParcelableNode>();
source.readTypedList(pWayNodes, ParcelableNode.CREATOR);
List<Node> wayNodes = way.getNodes();
for(ParcelableNode pn : pWayNodes){
wayNodes.add(pn.getNode());
}
}
public static final Parcelable.Creator<ParcelableWay> CREATOR = new Parcelable.Creator<ParcelableWay>() {
@Override
public ParcelableWay createFromParcel(Parcel source) {
return new ParcelableWay(source);
}
@Override
public ParcelableWay[] newArray(int size) {
return new ParcelableWay[size];
}
};
/*
* (non-Javadoc)
*
* @see android.os.Parcelable#describeContents()
*/
@Override
public int describeContents() {
return 0;
}
/*
* (non-Javadoc)
*
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
List<ParcelableNode> pWayNodes = new ArrayList<ParcelableNode>();
List<Node> wayNodes = way.getNodes();
for(Node n : wayNodes){
pWayNodes.add(new ParcelableNode(n));
}
dest.writeTypedList(pWayNodes);
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import android.os.Parcel;
import android.os.Parcelable;
/**
* A data class representing a single OSM entity. All top level data types
* inherit from this class.
*
* @author Brett Henderson
*/
public abstract class ParcelableEntity implements Parcelable {
protected Entity entity;
protected ParcelableEntity() {}
public ParcelableEntity(Entity entity){
this.entity = entity;
}
public void readFromParcel(Entity entity, Parcel source){
this.entity = entity;
ParcelableCommonEntityData parcelableCommonEntityData = source.readParcelable(ParcelableCommonEntityData.class.getClassLoader());
this.entity.entityData = parcelableCommonEntityData.getCommonEntityData();
}
/**
* @return the entity
*/
public Entity getEntity() {
return entity;
}
/* (non-Javadoc)
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
*/
@Override
public void writeToParcel(Parcel dest, int flags){
ParcelableCommonEntityData p = new ParcelableCommonEntityData(entity.entityData);
dest.writeParcelable(p, flags);
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.ArrayList;
import java.util.List;
import android.os.Parcel;
import android.os.Parcelable;
/**
* A data class representing a single OSM relation.
*
* @author Brett Henderson
*/
public class ParcelableRelation extends ParcelableEntity implements Parcelable {
protected Relation rel;
public ParcelableRelation(Relation rel){
super(rel);
this.rel = rel;
}
/**
* @param source
*/
public ParcelableRelation(Parcel source) {
this(new Relation());
super.readFromParcel(rel, source);
List<ParcelableRelationMember> pMembers = new ArrayList<ParcelableRelationMember>();
source.readTypedList(pMembers, ParcelableRelationMember.CREATOR);
for(ParcelableRelationMember pMember : pMembers){
this.rel.getMembers().add(pMember.getMember());
}
}
public static final Parcelable.Creator<ParcelableRelation> CREATOR = new Parcelable.Creator<ParcelableRelation>() {
@Override
public ParcelableRelation createFromParcel(Parcel source) {
return new ParcelableRelation(source);
}
@Override
public ParcelableRelation[] newArray(int size) {
return new ParcelableRelation[size];
}
};
/* (non-Javadoc)
* @see android.os.Parcelable#describeContents()
*/
@Override
public int describeContents() {
return 0;
}
/* (non-Javadoc)
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
List<ParcelableRelationMember> pMembers = new ArrayList<ParcelableRelationMember>();
for(RelationMember member : rel.getMembers()){
pMembers.add(new ParcelableRelationMember(member));
}
dest.writeTypedList(pMembers);
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.ArrayList;
import java.util.List;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Contains data common to all entity types. This is separated from the entity
* class to allow it to be instantiated before all the data required for a full
* entity is available.
*/
public class ParcelableCommonEntityData implements Parcelable {
protected CommonEntityData data;
public ParcelableCommonEntityData(Parcel source) {
data = new CommonEntityData();
data.id = source.readLong();
data.timestamp = source.readLong();
data.tags = new TagCollection();
List<ParcelableTag> pTags = new ArrayList<ParcelableTag>();
source.readTypedList((List<ParcelableTag>) pTags, ParcelableTag.CREATOR);
for(ParcelableTag pTag : pTags){
data.tags.add(pTag.getTag());
}
}
public ParcelableCommonEntityData(CommonEntityData data){
this.data = data;
}
/**
* @return the data
*/
public CommonEntityData getCommonEntityData() {
return data;
}
public static final Parcelable.Creator<ParcelableCommonEntityData> CREATOR = new Parcelable.Creator<ParcelableCommonEntityData>() {
@Override
public ParcelableCommonEntityData createFromParcel(Parcel source) {
return new ParcelableCommonEntityData(source);
}
@Override
public ParcelableCommonEntityData[] newArray(int size) {
return new ParcelableCommonEntityData[size];
}
};
/*
* (non-Javadoc)
*
* @see android.os.Parcelable#describeContents()
*/
@Override
public int describeContents() {
return 0;
}
/*
* (non-Javadoc)
*
* @see android.os.Parcelable#writeToParcel(android.os.Parcel, int)
*/
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(data.id);
dest.writeLong(data.timestamp);
List<ParcelableTag> pTags = new ArrayList<ParcelableTag>();
for(Tag tag : data.tags){
pTags.add(new ParcelableTag(tag));
}
dest.writeTypedList(pTags);
}
}
| Java |
package il.yrtimid.osm.osmpoi;
import java.io.IOException;
import java.util.List;
import android.content.Context;
import il.yrtimid.osm.osmpoi.dal.OsmOverpassAPI;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.searchparameters.BaseSearchParameter;
import il.yrtimid.osm.osmpoi.searchparameters.SearchAround;
import il.yrtimid.osm.osmpoi.searchparameters.SearchById;
import il.yrtimid.osm.osmpoi.searchparameters.SearchByKeyValue;
import il.yrtimid.osm.osmpoi.searchparameters.SearchByParentId;
import il.yrtimid.osm.osmpoi.tagmatchers.KeyValueMatcher;
public class OverpassAPISearchSource implements ISearchSource {
public static ISearchSource create(Context context) {
return new OverpassAPISearchSource();
}
protected OverpassAPISearchSource() {
}
@Override
public void search(BaseSearchParameter search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
if (search instanceof SearchByKeyValue) {
getByDistanceAndKeyValue((SearchByKeyValue) search, newItemNotifier, cancel);
} else if (search instanceof SearchAround) {
//getByDistance((SearchAround) search, newItemNotifier, cancel);
} else if (search instanceof SearchByParentId) {
//getByParentId((SearchByParentId) search, newItemNotifier, cancel);
} else if (search instanceof SearchById) {
//getById((SearchById) search, newItemNotifier, cancel);
}
}
public void getByDistanceAndKeyValue(SearchByKeyValue search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
Point c = search.getCenter();
Double radius = 0.0d;
int results = 0;
while (results < search.getMaxResults()){
if (cancel.isCancelled()) break;
radius += 0.01d;
int radiusInMeters = c.getDistance(c.latitude+radius, c.longitude+radius);
newItemNotifier.pushRadius(radiusInMeters);
List<Entity> result;
try {
result = OsmOverpassAPI.Search(c.latitude, c.longitude, radius, search.getMatcher());
} catch (IOException e1) {
e1.printStackTrace();
break;
}
for(Entity e : result){
newItemNotifier.pushItem(e);
}
results+=result.size();
}
}
// public void getByDistance(SearchAround search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
// // TODO Auto-generated method stub
//
// }
//
// public void getById(SearchById search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
// // TODO Auto-generated method stub
//
// }
//
// public void getByParentId(SearchByParentId search, SearchPipe<Entity> newItemNotifier, CancelFlag cancel) {
// // TODO Auto-generated method stub
//
// }
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public String getName() {
return "OverpassAPI search";
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
import il.yrtimid.osm.osmpoi.domain.Entity;
/**
* @author yrtimid
*
*/
public class ResultItem {
public Entity entity;
public Integer radius;
public ResultItem(Entity entity, Integer radius) {
this.entity = entity;
this.radius = radius;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
/**
* @author yrtimid
*
*/
public enum SearchSourceType {
NONE,
DB,
ONLINE
}
| Java |
package il.yrtimid.osm.osmpoi;
public class CircleArea {
Point point;
int radius;
public CircleArea(CircleArea area) {
point = new Point(area.point);
this.radius = area.radius;
}
public CircleArea(double latitude, double longitude, int radius) {
point = new Point(latitude, longitude);
this.radius = radius;
}
public Double getLatitude() {
return point.getLatitude();
}
public Double getLongitude() {
return point.getLongitude();
}
public Point getCenter(){
return point;
}
public void setLocation(double latitude, double longitude){
this.point.setLatitude(latitude);
this.point.setLongitude(longitude);
}
public int getRadius() {
return radius;
}
public void setRadius(int radius){
this.radius = radius;
}
public Boolean isInArea(double latitude, double longitude) {
return point.getDistance(latitude, longitude) <= radius;
}
/*public Boolean isInArea(Node node){
return isInArea(node.getLatitude(), node.getLongitude());
}*/
public int getDistance(double latitude, double longitude) {
return point.getDistance(latitude, longitude);
}
/*public int getDistance(Node node) {
return getDistance(node.getLatitude(), node.getLongitude());
}*/
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.services;
import il.yrtimid.osm.osmpoi.ImportSettings;
import il.yrtimid.osm.osmpoi.ItemPipe;
import il.yrtimid.osm.osmpoi.OsmPoiApplication;
import il.yrtimid.osm.osmpoi.R;
import il.yrtimid.osm.osmpoi.dal.IDbCachedFiller;
import il.yrtimid.osm.osmpoi.dbcreator.common.DbCreator;
import il.yrtimid.osm.osmpoi.dbcreator.common.INotificationManager;
import il.yrtimid.osm.osmpoi.dbcreator.common.Notification2;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.logging.Log;
import il.yrtimid.osm.osmpoi.pbf.OsmImporter;
import il.yrtimid.osm.osmpoi.pbf.ProgressNotifier;
import il.yrtimid.osm.osmpoi.ui.SearchActivity;
import il.yrtimid.osm.osmpoi.ui.Preferences;
import il.yrtimid.osm.osmpoi.ui.Util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.webkit.URLUtil;
/**
* @author yrtimid
*
*/
public class FileProcessingService extends Service {
public enum Operation {
IMPORT_TO_DB,
CLEAR_DB,
BUILD_GRID
}
public static final String EXTRA_FILE_PATH = "file_path";
public static final String EXTRA_OPERATION = "operation";
public static final int IMPORT_TO_DB = 1;
public static final int IMPORT_TO_DB_NODES = 11;
public static final int IMPORT_TO_DB_WAYS = 12;
public static final int IMPORT_TO_DB_RELS = 13;
public static final int CLEAR_DB = 20;
public static final int ABORTED = 30;
public static final int BUILD_GRID = 40;
public static final int DOWNLOAD_FILE = 50;
private boolean hasRunningJobs = false;
IDbCachedFiller poiDbHelper;
IDbCachedFiller addressDbHelper;
NotificationManager notificationManager;
PendingIntent contentIntent;
Context context;
INotificationManager notificationManager2;
/*
* (non-Javadoc)
*
* @see android.app.Service#onBind(android.content.Intent)
*/
@Override
public IBinder onBind(Intent arg0) {
return null;
}
/*
* (non-Javadoc)
*
* @see android.app.Service#onCreate()
*/
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
poiDbHelper = OsmPoiApplication.databases.getPoiDb();
addressDbHelper = OsmPoiApplication.databases.getAddressDb();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, SearchActivity.class);
contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notificationManager2 = new AndroidNotificationManager(context, contentIntent);
}
/*
* (non-Javadoc)
*
* @see android.app.Service#onDestroy()
*/
@Override
public void onDestroy() {
super.onDestroy();
//poiDbHelper.close();
//addressDbHelper.close();
if (hasRunningJobs) {
final Notification notif = new Notification(R.drawable.ic_launcher, "OsmPoi Service", System.currentTimeMillis());
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.setLatestEventInfo(context, "OsmPoi Service", "Backgroud job was canceled!", contentIntent);
notificationManager.notify(ABORTED, notif);
}
}
/*
* (non-Javadoc)
*
* @see android.app.Service#onStartCommand(android.content.Intent, int, int)
*/
@Override
public int onStartCommand(final Intent intent, int flags, final int startId) {
super.onStartCommand(intent, flags, startId);
Runnable task = null;
switch (Enum.valueOf(Operation.class, intent.getStringExtra(EXTRA_OPERATION))) {
case IMPORT_TO_DB:
task = new Runnable() {
public void run() {
hasRunningJobs = true;
importToDB(intent.getStringExtra(EXTRA_FILE_PATH));
hasRunningJobs = false;
stopSelf(startId);
}
};
break;
case CLEAR_DB:
task = new Runnable() {
public void run() {
hasRunningJobs = true;
clearDb();
hasRunningJobs = false;
stopSelf(startId);
}
};
break;
case BUILD_GRID:
task = new Runnable(){
public void run(){
hasRunningJobs = true;
rebuildGrid();
hasRunningJobs = false;
stopSelf(startId);
}
};
break;
}
if (task != null){
Thread t = new Thread(task, "Service");
t.setPriority(Thread.MIN_PRIORITY);
t.start();
}else {
stopSelf();
}
return START_REDELIVER_INTENT;
}
private void clearDb() {
Notification notif = new Notification(R.drawable.ic_launcher, "Clearing DB", System.currentTimeMillis());
notif.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
try {
notif.setLatestEventInfo(context, "Clearing DB", "Clearing DB...", contentIntent);
notificationManager.notify(CLEAR_DB, notif);
startForeground(CLEAR_DB, notif);
poiDbHelper.clearAll();
addressDbHelper.clearAll();
stopForeground(true);
notif = new Notification(R.drawable.ic_launcher, "Clearing DB", System.currentTimeMillis());
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.setLatestEventInfo(context, "Clearing DB", "Clearing DB finished", contentIntent);
notificationManager.notify(CLEAR_DB, notif);
} catch (Exception ex) {
Log.wtf("Service clearDb", ex);
}
}
private void rebuildGrid(){
try {
long startTime = System.currentTimeMillis();
final Notification notif = new Notification(R.drawable.ic_launcher, "Rebuilding grid", System.currentTimeMillis());
notif.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
notif.setLatestEventInfo(context, "Rebuilding grid", "Clearing old grid...", contentIntent);
notificationManager.notify(BUILD_GRID, notif);
startForeground(BUILD_GRID, notif);
final ImportSettings settings = Preferences.getImportSettings(context);
notif.setLatestEventInfo(context, "Rebuilding grid", "Creating grid...", contentIntent);
notificationManager.notify(BUILD_GRID, notif);
poiDbHelper.initGrid();
notif.setLatestEventInfo(context, "Rebuilding grid", "Optimizing grid...", contentIntent);
notificationManager.notify(BUILD_GRID, notif);
poiDbHelper.optimizeGrid(settings.getGridCellSize());
stopForeground(true);
long endTime = System.currentTimeMillis();
int workTime = Math.round((endTime-startTime)/1000/60);
Notification finalNotif = new Notification(R.drawable.ic_launcher, "Rebuilding grid", System.currentTimeMillis());
finalNotif.flags |= Notification.FLAG_AUTO_CANCEL;
finalNotif.setLatestEventInfo(context, "Rebuilding grid", "Done successfully. ("+workTime+"min)", contentIntent);
notificationManager.notify(IMPORT_TO_DB, finalNotif);
} catch (Exception ex) {
Log.wtf("Exception while rebuilding grid", ex);
}
}
private void importToDB(String sourceFilePath) {
try {
Log.d("Importing file from: "+sourceFilePath);
if (sourceFilePath.startsWith("/")){
//local file, can use directly
}else {
sourceFilePath = downloadFile(sourceFilePath);
}
final ImportSettings settings = Preferences.getImportSettings(context);
DbCreator creator = new DbCreator(poiDbHelper, addressDbHelper, notificationManager2);
creator.importToDB(sourceFilePath, settings);
} catch (Exception ex) {
Log.wtf("Exception while importing PBF into DB", ex);
try{
Notification2 finalNotif = new Notification2("Importing file into DB", System.currentTimeMillis());
finalNotif.flags |= Notification.FLAG_AUTO_CANCEL;
finalNotif.setLatestEventInfo("PBF Import", "Import failed. "+ex.getMessage());
notificationManager2.notify(IMPORT_TO_DB, finalNotif);
stopForeground(true);
}
catch(Exception ex2){
Log.wtf("Exception while importing PBF into DB", ex2);
}
}
}
public Long importRelations(final InputStream input, final Notification notif, final ImportSettings settings) {
poiDbHelper.beginAdd();
addressDbHelper.beginAdd();
Long count = OsmImporter.processAll(input, new ItemPipe<Entity>() {
@Override
public void pushItem(Entity item) {
try{
if (item.getType() == EntityType.Relation){
settings.cleanTags(item);
if (settings.isPoi(item))
poiDbHelper.addEntity(item);
else if (settings.isAddress(item))
addressDbHelper.addEntity(item);
}
}catch(Exception e){
Log.wtf("pushItem failed: "+item.toString(), e);
}
}
}, new ProgressNotifier() {
@Override
public void onProgressChange(Progress progress) {
notif.setLatestEventInfo(context, "PBF Import", "Importing relations: " + progress.toString(), contentIntent);
notificationManager.notify(IMPORT_TO_DB, notif);
}
});
if (count == -1L){
notif.setLatestEventInfo(context, "PBF Import", "Relations import failed", contentIntent);
}
poiDbHelper.endAdd();
addressDbHelper.endAdd();
return count;
}
public Long importWays(final InputStream input, final Notification notif, final ImportSettings settings) {
poiDbHelper.beginAdd();
addressDbHelper.beginAdd();
Long count = OsmImporter.processAll(input, new ItemPipe<Entity>() {
@Override
public void pushItem(Entity item) {
try{
if (item.getType() == EntityType.Way){
settings.cleanTags(item);
if (settings.isPoi(item))
poiDbHelper.addEntity(item);
else if (settings.isAddress(item))
addressDbHelper.addEntity(item);
else if (settings.isImportRelations()){
Way w = (Way)item;
poiDbHelper.addWayIfBelongsToRelation(w);
addressDbHelper.addWayIfBelongsToRelation(w);
}
}
}catch(Exception e){
Log.wtf("pushItem failed: "+item.toString(), e);
}
}
}, new ProgressNotifier() {
@Override
public void onProgressChange(Progress progress) {
notif.setLatestEventInfo(context, "PBF Import", "Importing ways: " + progress.toString(), contentIntent);
notificationManager.notify(IMPORT_TO_DB, notif);
}
});
if (count == -1L){
notif.setLatestEventInfo(context, "PBF Import", "Nodes import failed", contentIntent);
}
poiDbHelper.endAdd();
addressDbHelper.endAdd();
return count;
}
public Long importNodes(final InputStream input, final Notification notif, final ImportSettings settings) {
poiDbHelper.beginAdd();
Long count = OsmImporter.processAll(input, new ItemPipe<Entity>() {
@Override
public void pushItem(Entity item) {
try{
if (item.getType() == EntityType.Node){
settings.cleanTags(item);
if (settings.isPoi(item))
poiDbHelper.addEntity(item);
else if (settings.isAddress(item))
addressDbHelper.addEntity(item);
else {
Node n = (Node)item;
if (settings.isImportWays()){
poiDbHelper.addNodeIfBelongsToWay(n);
addressDbHelper.addNodeIfBelongsToWay(n);
}
if (settings.isImportRelations()){
poiDbHelper.addNodeIfBelongsToRelation(n);
addressDbHelper.addNodeIfBelongsToRelation(n);
}
}
}else if (item.getType() == EntityType.Bound){
poiDbHelper.addEntity(item);
}
}catch(Exception e){
Log.wtf("pushItem failed: "+item.toString(), e);
}
}
}, new ProgressNotifier() {
@Override
public void onProgressChange(Progress progress) {
notif.setLatestEventInfo(context, "PBF Import", "Importing nodes: " + progress.toString(), contentIntent);
notificationManager.notify(IMPORT_TO_DB, notif);
}
});
if (count == -1L){
notif.setLatestEventInfo(context, "PBF Import", "Nodes import failed", contentIntent);
}
poiDbHelper.endAdd();
return count;
}
private String downloadFile(String path){
final Notification notif = new Notification(R.drawable.ic_launcher, "Downloading file", System.currentTimeMillis());
notif.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
notif.setLatestEventInfo(context, "PBF Import", "Downloading file...", contentIntent);
notificationManager.notify(DOWNLOAD_FILE, notif);
startForeground(DOWNLOAD_FILE, notif);
String localPath = path;
File homeFolder = Preferences.getHomeFolder(context);
byte[] buffer = new byte[1024];
int downloadedSize = 0;
int totalSize = 0;
File outputPath = null;
try{
URL u = new URL(path);
String outputFileName = URLUtil.guessFileName(path, null, null);
outputPath = new File(homeFolder,outputFileName);
OutputStream output = new BufferedOutputStream(new FileOutputStream(outputPath), buffer.length);
URLConnection conn = u.openConnection();
totalSize = conn.getContentLength();
InputStream input = new BufferedInputStream(conn.getInputStream(), buffer.length);
int bufferLength = 0;
int counter = 0;
while ( (bufferLength = input.read(buffer)) > 0 ) {
output.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
counter++;
if (counter == 100){
Log.d(String.format("Downloaded %d/%d", downloadedSize, totalSize));
notif.setLatestEventInfo(context, "PBF Import", formatDownloadProgress(downloadedSize, totalSize), contentIntent);
notificationManager.notify(DOWNLOAD_FILE, notif);
counter = 0;
}
}
output.close();
input.close();
localPath = outputPath.getPath();
stopForeground(true);
Notification finalNotif = new Notification(R.drawable.ic_launcher, "Downloading file", System.currentTimeMillis());
finalNotif.flags |= Notification.FLAG_AUTO_CANCEL;
finalNotif.setLatestEventInfo(context, "PBF Import", "Downloading finished.", contentIntent);
notificationManager.notify(DOWNLOAD_FILE, finalNotif);
}catch(Exception e){
Log.wtf("downloadFile", e);
if (outputPath.exists()){
outputPath.delete();
}
stopForeground(true);
Notification finalNotif = new Notification(R.drawable.ic_launcher, "Downloading file", System.currentTimeMillis());
finalNotif.flags |= Notification.FLAG_AUTO_CANCEL;
finalNotif.setLatestEventInfo(context, "PBF Import", "Downloading failed.", contentIntent);
notificationManager.notify(DOWNLOAD_FILE, finalNotif);
}
return localPath;
}
private String formatDownloadProgress(int downloadedSize, int totalSize) {
String ready = "";
String from = "";
ready = Util.formatSize(downloadedSize);
if (totalSize > 0){
from = "/"+Util.formatSize(totalSize);
}
return String.format("Downloading file %s%s", ready, from);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.services;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import il.yrtimid.osm.osmpoi.R;
import il.yrtimid.osm.osmpoi.dbcreator.common.INotificationManager;
import il.yrtimid.osm.osmpoi.dbcreator.common.Notification2;
/**
* @author yrtimid
*
*/
public class AndroidNotificationManager implements INotificationManager {
NotificationManager notificationManager;
Context context;
PendingIntent contentIntent;
public AndroidNotificationManager(Context context, PendingIntent contentIntent) {
this.context = context;
this.contentIntent = contentIntent;
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
public void notify(int id, Notification2 notification) {
Notification notif = new Notification(R.drawable.ic_launcher, notification.tickerText, notification.when);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.setLatestEventInfo(context, notification.title, notification.text, contentIntent);
notificationManager.notify(id, notif);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
/**
* @author yrtimid
*
*/
public class Point {
Double latitude;
Double longitude;
int radius;
public Point(Point point) {
this.latitude = point.latitude;
this.longitude = point.longitude;
}
public Point(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public Double getLatitude() {
return latitude;
}
public Double getLongitude() {
return longitude;
}
/**
* @param latitude the latitude to set
*/
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
/**
* @param longitude the longitude to set
*/
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("Lat:%f Lon:%f", latitude, longitude);
}
/**
* Calculates distance between current point and specified point in meters
* @param latitude
* @param longitude
* @return
*/
public int getDistance(double latitude, double longitude) {
return Util.getDistance(this.latitude, this.longitude, latitude, longitude);
}
/**
* Calculates distance between current point and specified point in meters
* @param anotherPoint
* @return
*/
public int getDistance(Point anotherPoint) {
return Util.getDistance(this.latitude, this.longitude, anotherPoint.latitude, anotherPoint.longitude);
}
}
| Java |
package il.yrtimid.osm.osmpoi.ui;
import il.yrtimid.osm.osmpoi.R;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.location.Location;
import android.widget.TextView;
public class Util {
/*public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (resolveInfo.size() > 0) {
return true;
}
return false;
}*/
public static void showAlert(Context context, String message) {
new AlertDialog.Builder(context).setMessage(message).show();
}
public static void showDebugAlert(Context context, String message) {
new AlertDialog.Builder(context).setTitle("Debug").setMessage(message).show();
}
public static void updateAccuracyText(TextView txtAccuracy, Location location) {
if (location != null && location.hasAccuracy()){
txtAccuracy.setText(String.format("%,dm", (int) location.getAccuracy()));
}else
txtAccuracy.setText(R.string.NA);
}
private static ProgressDialog progressDialog = null;
public static void showWaiting(Context context, String title, String message){
showWaiting(context, title, message, null);
}
public static void showWaiting(Context context, String title, String message, OnCancelListener cancelListener){
if (message == null) message = context.getString(R.string.loading);
progressDialog = ProgressDialog.show(context, title, message, true, true, cancelListener);
}
public static void dismissWaiting(){
if (progressDialog != null){
progressDialog.dismiss();
progressDialog = null;
}
}
private static char[] directionChars = new char[]{'↑','↗','→','↘','↓','↙','←','↖'};
public static char getDirectionChar(int degree){
if (degree>=360) degree = degree % 360;
if (degree<0) degree+=360;
degree+=45/2;
int section = (int)(degree/45);
if (section == 8) section = 0;
return directionChars[section];
}
public static int normalizeBearing(int bearing){
bearing = bearing % 360;
if (bearing < -180) bearing = bearing + 360;
if (bearing > 180) bearing = bearing - 360;
return bearing;
}
public static String formatDistance(int meters){
if (meters<1000)
return String.format("%,dm", meters);
else
return String.format("%,dkm", meters/1000);
}
public static String formatSize(int bytes){
if (bytes<1000)
return String.format("%dB", bytes);
else if (bytes<1000000)
return String.format("%.1fkB", bytes/1000.0);
else if (bytes<1000000000)
return String.format("%.1fMB", bytes/1000000.0);
else
return String.format("%.1fGB", bytes/1000000000.0);
}
public static String getLocalName(Context context, String key){
if (key == null || key.length()==0) return key;
if (false == Character.isLetter(key.charAt(0))) return key; //getIdentifier internally tries to convert name to integer, so if key=="10" we'll not get it resolved to real ID
int resId = context.getResources().getIdentifier(key, "string", context.getPackageName());
if (resId == 0)
return key;
else
return context.getResources().getString(resId);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.ui;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import il.yrtimid.osm.osmpoi.R;
import il.yrtimid.osm.osmpoi.logging.Log;
import il.yrtimid.osm.osmpoi.services.FileProcessingService;
import il.yrtimid.osm.osmpoi.ui.DownloadItem.ItemType;
import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.view.Window;
import android.webkit.URLUtil;
import android.widget.AbsListView;
import android.widget.ListView;
/**
* @author yrtimid
*
*/
public class DownloadActivity extends ListActivity implements ListView.OnScrollListener {
private DownloadListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
// setContentView(R.layout.select_download);
getListView().setOnScrollListener(this);
}
@Override
protected void onResume() {
super.onResume();
DownloadItem urls = loadList();
adapter = new DownloadListAdapter(this, R.layout.select_download_row, urls);
setListAdapter(adapter);
}
private DownloadItem loadList() {
DownloadItem root = new DownloadItem();
root.Name = "/";
root.Type = ItemType.FOLDER;
root.SubItems = new ArrayList<DownloadItem>();
List<String> urls = new ArrayList<String>();
try {
InputStream stream = this.getAssets().open("pbf_list");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.length() > 0 && URLUtil.isValidUrl(line))
urls.add(line);
}
} catch (IOException e) {
Log.wtf("loadList reading file", e);
}
if (urls.size() > 0) {
// find base url (same for all urls in list
String base = urls.get(0);
base = base.substring(0, base.lastIndexOf('/'));
for (String url : urls) {
while (false == base.regionMatches(0, url, 0, base.length())) {
base = base.substring(0, base.lastIndexOf('/'));
if (base.length() == 0)
break;
}
}
base += "/";
Map<String, DownloadItem> levelsMap = new HashMap<String, DownloadItem>();
for (String url : urls) {
String rel = url.substring(base.length());// relative path
String currentLevel = "";
DownloadItem currentFolder = null;
for (String level : rel.split("/")) {
if (level.endsWith(".pbf")) {
DownloadItem newFile = new DownloadItem();
newFile.Type = ItemType.FILE;
newFile.Name = level;
newFile.Url = url;
if (currentFolder == null) {// we at root
root.SubItems.add(newFile);
newFile.Parent = root;
} else {// we at sub-folder
currentFolder.SubItems.add(newFile);
newFile.Parent = currentFolder;
}
}
else {
currentLevel += level + "/";
if (levelsMap.containsKey(currentLevel)) {
currentFolder = levelsMap.get(currentLevel);
}
else {
DownloadItem newFolder = new DownloadItem();
newFolder.Type = ItemType.FOLDER;
newFolder.Name = level;
newFolder.Url = base + currentLevel;
newFolder.SubItems = new ArrayList<DownloadItem>();
if (currentFolder == null) {// we at root
root.SubItems.add(newFolder);
newFolder.Parent = root;
} else {// we at sub-folder
currentFolder.SubItems.add(newFolder);
newFolder.Parent = currentFolder;
}
currentFolder = newFolder;
levelsMap.put(currentLevel, currentFolder);
}
}
}
}
}
return root;
}
@Override
protected void onListItemClick(ListView parent, View view, int position, long id) {
DownloadItem item = adapter.getItem(position);
if (item.Type == ItemType.FOLDER) {
adapter.changeLevel(item);
parent.setSelection(0);
} else {
checkDownloadItemAvailability(item);
}
}
private void checkDownloadItemAvailability(final DownloadItem item) {
new AsyncTask<DownloadItem, Void, Boolean>() {
@Override
protected Boolean doInBackground(DownloadItem... params) {
try {
DownloadItem item = params[0];
URL u = new URL(item.Url);
HttpURLConnection conn;
conn = (HttpURLConnection) u.openConnection();
item.Size = conn.getContentLength();
item.LastModified = new Date(conn.getLastModified());
return conn.getResponseCode() == 200;
} catch (IOException e) {
Log.wtf("checkDownloadItem", e);
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
setProgressBarIndeterminateVisibility(false);
confirmDownloading(result, item);
}
}.execute(item);
setProgressBarIndeterminateVisibility(true);
}
private void confirmDownloading(Boolean itemAvailable, DownloadItem item) {
if (itemAvailable) {
final String url = item.Url;
final ConfirmDialog.Action runDownloadAndImportServiceAction =
new ConfirmDialog.Action() {
@Override
public void PositiveAction() {
runDownloadAndImportService(url);
}
};
final ConfirmDialog.Action confirmDownloadAction =
new ConfirmDialog.Action() {
@Override
public void PositiveAction() {
ConfirmDialog.Confirm(DownloadActivity.this, getString(R.string.import_confirm), runDownloadAndImportServiceAction);
}
};
String lastModified = DateFormat.getMediumDateFormat(this).format(item.LastModified);
String size = Util.formatSize(item.Size);
String message = getString(R.string.confirm_download_and_import, item.Name, size, lastModified);
ConfirmDialog.Confirm(this, message, confirmDownloadAction);
} else {
Util.showAlert(this, getString(R.string.file_unavailable, item.Name));
}
}
private void runDownloadAndImportService(String url) {
Intent serviceIntent = new Intent(this, FileProcessingService.class);
serviceIntent.putExtra(FileProcessingService.EXTRA_OPERATION, FileProcessingService.Operation.IMPORT_TO_DB.name());
serviceIntent.putExtra(FileProcessingService.EXTRA_FILE_PATH, url);
startService(serviceIntent);
}
/*
* (non-Javadoc)
*
* @see
* android.widget.AbsListView.OnScrollListener#onScrollStateChanged(android
* .widget.AbsListView, int)
*/
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see android.widget.AbsListView.OnScrollListener#onScroll(android.widget.
* AbsListView, int, int, int)
*/
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
}
| Java |
package il.yrtimid.osm.osmpoi.ui;
import il.yrtimid.osm.osmpoi.ImportSettings;
import il.yrtimid.osm.osmpoi.OsmPoiApplication;
import il.yrtimid.osm.osmpoi.R;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import il.yrtimid.osm.osmpoi.logging.Log;
import il.yrtimid.osm.osmpoi.services.FileProcessingService;
import java.io.File;
import java.util.List;
import com.kaloer.filepicker.FilePickerActivity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
//TODO: prevent executing more than one service task at a time
public class Preferences extends PreferenceActivity implements OnPreferenceClickListener, OnPreferenceChangeListener {
public static final String SEARCH_SOURCE = "search_source";
public static final String LAST_SEARCH = "last_search";
public static final String RESULT_LANGUAGE = "result_language";
public static final String IS_DB_ON_SDCARD = "is_db_on_sdcard";
private static final String PREFERENCE_IMPORT_PBF = "preference_import_pbf";
private static final String PREFERENCE_CLEAR_DB = "debug_clear_db";
private static final String PREFERENCE_BUILD_GRID = "debug_rebuild_grid";
private static final String PREFERENCE_DOWNLOAD = "preference_download";
private static final String PREFERENCE_DEBUG_RESET = "preference_debug_reset";
private static final String PREFERENCE_INCLUDE_EXCLUDE_RESET = "include_exclude_reset";
public static final String NODES_INCLUDE = "nodes_include";
public static final String NODES_EXCLUDE = "nodes_exclude";
public static final String WAYS_INCLUDE = "ways_include";
public static final String WAYS_EXCLUDE = "ways_exclude";
public static final String RELATIONS_INCLUDE = "relations_include";
public static final String RELATIONS_EXCLUDE = "relations_exclude";
private static final int INTERNAL_PICK_FILE_REQUEST_FOR_IMPORT = 1;
SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
findPreference(PREFERENCE_IMPORT_PBF).setOnPreferenceClickListener(this);
findPreference(PREFERENCE_CLEAR_DB).setOnPreferenceClickListener(this);
//findPreference(SEARCH_SOURCE).setOnPreferenceChangeListener(this);
findPreference(IS_DB_ON_SDCARD).setOnPreferenceChangeListener(this);
findPreference(PREFERENCE_BUILD_GRID).setOnPreferenceClickListener(this);
findPreference(PREFERENCE_DOWNLOAD).setOnPreferenceClickListener(this);
findPreference(PREFERENCE_DEBUG_RESET).setOnPreferenceClickListener(this);
findPreference(PREFERENCE_DOWNLOAD).setOnPreferenceClickListener(this);
findPreference(PREFERENCE_INCLUDE_EXCLUDE_RESET).setOnPreferenceClickListener(this);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
OsmPoiApplication.Config.reloadConfig(this);
}
/*
* (non-Javadoc)
*
* @see
* android.preference.Preference.OnPreferenceClickListener#onPreferenceClick
* (android.preference.Preference)
*/
@Override
public boolean onPreferenceClick(final Preference preference) {
String key = preference.getKey();
if (PREFERENCE_IMPORT_PBF.equals(key)) {
Intent intent = new Intent(this, FilePickerActivity.class);
intent.putExtra(FilePickerActivity.EXTRA_FILE_PATH, getHomeFolder(this).getPath());
startActivityForResult(intent, INTERNAL_PICK_FILE_REQUEST_FOR_IMPORT);
return true;
} else if (PREFERENCE_CLEAR_DB.equals(key)) {
ConfirmDialog.Confirm((Context) Preferences.this, getString(R.string.clean_db_confirm), new ConfirmDialog.Action() {
@Override
public void PositiveAction() {
runClearDbService();
}
});
return true;
} else if (PREFERENCE_BUILD_GRID.equals(key)){
runBuildGridService();
return true;
} else if (PREFERENCE_DOWNLOAD.equals(key)){
Intent intent = new Intent(this, DownloadActivity.class);
startActivity(intent);
} else if (PREFERENCE_DEBUG_RESET.equals(key)){
OsmPoiApplication.Config.reset(this);
OsmPoiApplication.Config.reloadConfig(this);
this.finish();
} else if (PREFERENCE_INCLUDE_EXCLUDE_RESET.equals(key)){
OsmPoiApplication.Config.resetIncludeExclude(this);
OsmPoiApplication.Config.reloadConfig(this);
this.finish();
}
return false;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == INTERNAL_PICK_FILE_REQUEST_FOR_IMPORT) {
if (resultCode == RESULT_OK) {
final File f = new File(data.getStringExtra(FilePickerActivity.EXTRA_FILE_PATH));
importPBF(f);
}
}
}
private void importPBF(final File f) {
ConfirmDialog.Confirm((Context) Preferences.this, getString(R.string.import_confirm), new ConfirmDialog.Action() {
@Override
public void PositiveAction() {
runPbfImportService(f);
}
});
}
private void runPbfImportService(final File f) {
Intent serviceIntent = new Intent(Preferences.this, FileProcessingService.class);
serviceIntent.putExtra(FileProcessingService.EXTRA_OPERATION, FileProcessingService.Operation.IMPORT_TO_DB.name());
serviceIntent.putExtra(FileProcessingService.EXTRA_FILE_PATH, f.getPath());
startService(serviceIntent);
}
private void runClearDbService() {
Intent serviceIntent = new Intent(Preferences.this, FileProcessingService.class);
serviceIntent.putExtra(FileProcessingService.EXTRA_OPERATION, FileProcessingService.Operation.CLEAR_DB.name());
startService(serviceIntent);
}
private void runBuildGridService(){
Intent serviceIntent = new Intent(Preferences.this, FileProcessingService.class);
serviceIntent.putExtra(FileProcessingService.EXTRA_OPERATION, FileProcessingService.Operation.BUILD_GRID.name());
startService(serviceIntent);
}
/*
* (non-Javadoc)
*
* @see
* android.preference.Preference.OnPreferenceChangeListener#onPreferenceChange
* (android.preference.Preference, java.lang.Object)
*/
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
/* if (SEARCH_SOURCE.equals(preference.getKey())) {
SearchSourceType type = (SearchSourceType) Enum.valueOf(SearchSourceType.class, (String) newValue);
Boolean success = OsmPoiApplication.Config.tryCreateSearchSource(this, type);
if (success) {
return true;
} else {
Toast.makeText(this, R.string.cant_create_search_source, Toast.LENGTH_LONG).show();
}
}else if (IS_DB_ON_SDCARD.equals(preference.getKey())){
OsmPoiApplication.Config.reloadConfig(this);
return true;
}
return false;
*/
return true;
}
/**
*
* @param context
* @return path of the home folder on external storage, or null if internal
* storage must be used.
*/
/*
* private String getHomeFolder() { SharedPreferences prefs =
* getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE); String homeFolder =
* prefs.getString(PREFERENCE_HOME_FOLDER, null); if (homeFolder == null) {
* // try external storage String state =
* Environment.getExternalStorageState(); if
* (Environment.MEDIA_MOUNTED.equals(state)) { File appDir =
* this.getExternalFilesDir(null); if (appDir != null) { try { homeFolder =
* appDir.getCanonicalPath(); } catch (IOException e) { Log.e(TAG,
* e.getMessage()); homeFolder = null; } }
*
* } else { Log.w(TAG, "Can't use external storage. StorageState:" + state);
* }
*
* if (homeFolder != null) { SharedPreferences.Editor prefsEditor =
* getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE).edit();
* prefsEditor.putString(PREFERENCE_HOME_FOLDER, homeFolder);
* prefsEditor.commit(); } } Log.i(TAG, "Home folder: " + (homeFolder ==
* null ? getFilesDir() : homeFolder)); return homeFolder; }
*/
/*
* public FileInputStream getInputFile(String name) throws
* FileNotFoundException { String homeFolder = getHomeFolder(); if
* (homeFolder == null) { return openFileInput(name); } else { return new
* FileInputStream(new File(homeFolder, name)); } }
*/
/* public static FileOutputStream getOutputFile(Context context, String name) throws FileNotFoundException {
String homeFolder = getHomeFolder(context);
if (homeFolder == null) {
return context.openFileOutput(name, MODE_PRIVATE);
} else {
return new FileOutputStream(new File(homeFolder, name));
}
}*/
public static File getHomeFolder(Context context) {
//File appDir = context.getExternalFilesDir(null); //api 8+
File extStorageDir = Environment.getExternalStorageDirectory();
File appDir = new File(extStorageDir, "/Android/data/"+context.getPackageName()+"/files/");
if (appDir.exists() == false){
try{
appDir.mkdirs();
}catch(Exception e){
Log.wtf("Creating home folder: "+appDir.getPath(), e);
}
}
return appDir;
}
public static void resetSearchSourceType(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.remove(Preferences.SEARCH_SOURCE);
editor.commit();
}
public static void setLastSearch(Context context, CharSequence value) {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString(LAST_SEARCH, value.toString());
editor.commit();
}
public static CharSequence getLastSearch(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getString(LAST_SEARCH, "");
}
public boolean isServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningServiceInfo> services = manager.getRunningServices(Integer.MAX_VALUE);
for (RunningServiceInfo info : services) {
if (info.service.getClassName().equals(FileProcessingService.class.getName())) {
return true;
}
}
return false;
}
public static ImportSettings getImportSettings(Context context){
ImportSettings settings = new ImportSettings();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
settings.setBuildGrid(prefs.getBoolean("debug_import_build_grid", true));
settings.setClearBeforeImport(prefs.getBoolean("debug_import_cleardb", true));
updateSettings(settings,EntityType.Node, prefs.getString(NODES_INCLUDE, ""), true);
updateSettings(settings,EntityType.Node, prefs.getString(NODES_EXCLUDE, ""), false);
updateSettings(settings,EntityType.Way, prefs.getString(WAYS_INCLUDE, ""), true);
updateSettings(settings,EntityType.Way, prefs.getString(WAYS_EXCLUDE, ""), false);
updateSettings(settings,EntityType.Relation, prefs.getString(RELATIONS_INCLUDE, ""), true);
updateSettings(settings,EntityType.Relation, prefs.getString(RELATIONS_EXCLUDE, ""), false);
settings.setImportAddresses(prefs.getBoolean("import_addresses", false));
settings.setGridCellSize(Integer.parseInt(prefs.getString("grid_size", "1000")));
return settings;
}
private static void updateSettings(ImportSettings settings, EntityType type, String value, boolean isInclude) {
String[] lines = value.split("\n");
for(String l : lines){
String[] t = l.split("=");
if (t.length == 2){
settings.setKeyValue(type, t[0], t[1], isInclude);
}
}
}
/*private void checkFileSize(String url){
try {
URL u = new URL(url);
URLConnection conn;
conn = u.openConnection();
int totalSize = conn.getContentLength();
if (totalSize>200*1024*1024) {
ConfirmDialog.Confirm((Context) Preferences.this, getString(R.string.large_file_confirm), new ConfirmDialog.Action() {
@Override
public void PositiveAction() {
}
});
}
} catch (IOException e) {
Log.wtf("checkFileSize", e);
}
}
*/
}
| Java |
package il.yrtimid.osm.osmpoi.ui;
import il.yrtimid.osm.osmpoi.domain.*;
import java.util.Comparator;
import android.location.Location;
public class DistanceComparator implements Comparator<Entity> {
private Location loc;
public DistanceComparator(Location loc) {
this.loc = loc;
}
@Override
public int compare(Entity lhs, Entity rhs) {
Node ln = il.yrtimid.osm.osmpoi.Util.getFirstNode(lhs);
Node rn = il.yrtimid.osm.osmpoi.Util.getFirstNode(rhs);
if (ln != null && rn != null){
Location ll = new Location(this.loc);
ll.setLatitude(ln.getLatitude());
ll.setLongitude(ln.getLongitude());
Location rl = new Location(this.loc);
rl.setLatitude(rn.getLatitude());
rl.setLongitude(rn.getLongitude());
return Float.compare(loc.distanceTo(ll), loc.distanceTo(rl));
}
else if (ln != null){
return 1;
}
else if (rn != null){
return -1;
}
else {
return 0;
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.ui;
import il.yrtimid.osm.osmpoi.R;
import il.yrtimid.osm.osmpoi.categories.Category;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* @author yrtimid
*
*/
public class CategoriesListAdapter extends BaseAdapter {
private Category category;
private Context context;
private LayoutInflater inflater;
/**
*
*/
public CategoriesListAdapter(Context context, Category category) {
this.category = category;
this.context = context;
inflater = LayoutInflater.from(context);
}
/* (non-Javadoc)
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
return category.getSubCategoriesCount();
}
/* (non-Javadoc)
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Object getItem(int position) {
return category.getSubCategories().get(position);
}
/* (non-Javadoc)
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId(int position) {
return position;
}
/* (non-Javadoc)
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
convertView = inflater.inflate(R.layout.category_item, parent, false);
}
ImageView iconView = (ImageView)convertView.findViewById(android.R.id.icon);
TextView textView = (TextView)convertView.findViewById(android.R.id.text1);
Category cat = category.getSubCategories().get(position);
String name = (cat.isLocalizable())?Util.getLocalName(context, cat.getName()):cat.getName();
textView.setText(name);
Drawable icon = getIcon(cat.getIcon());
if (icon != null){
iconView.setImageDrawable(icon);
}else {
iconView.setImageDrawable(null);
}
return convertView;
}
private Drawable getIcon(String key){
if (key == null || key.length()==0) return null;
if (false == Character.isLetter(key.charAt(0))) return null; //getIdentifier internally tries to convert name to integer, so if key=="10" we'll not get it resolved to real ID
int resId = context.getResources().getIdentifier(key, "drawable", context.getPackageName());
if (resId == 0){
resId = context.getResources().getIdentifier(key, "drawable", "android");
if (resId == 0)
return null;
}
return context.getResources().getDrawable(resId);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.ui;
import il.yrtimid.osm.osmpoi.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
/**
* @author yrtimid
*
*/
public class ConfirmDialog {
public interface Action{
public void PositiveAction();
}
public static void Confirm(Context context, String message, final Action action){
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
action.PositiveAction();
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
default:
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setNegativeButton(context.getText(R.string.cancel), listener)
.setPositiveButton(context.getText(R.string.Continue), listener)
.show();
}
}
| Java |
package il.yrtimid.osm.osmpoi.ui;
public interface Action {
public void onAction();
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.ui;
import java.util.Date;
import java.util.List;
/**
* @author yrtimid
*
*/
public class DownloadItem{
public enum ItemType {
FOLDER, FILE
}
public String Url;
public String Name;
public Integer Size;
public Date LastModified;
public ItemType Type;
public DownloadItem Parent;
public List<DownloadItem> SubItems;
}
| Java |
package il.yrtimid.osm.osmpoi.ui;
import il.yrtimid.osm.osmpoi.CancelFlag;
import il.yrtimid.osm.osmpoi.OsmPoiApplication;
import il.yrtimid.osm.osmpoi.R;
import il.yrtimid.osm.osmpoi.ResultItem;
import il.yrtimid.osm.osmpoi.SearchPipe;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.logging.Log;
import il.yrtimid.osm.osmpoi.searchparameters.BaseSearchParameter;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
public class SearchAsyncTask extends AsyncTask<BaseSearchParameter, ResultItem, Boolean> {
public class AsyncTaskCancelFlag extends CancelFlag{
AsyncTask<?,?,?> task;
/**
*
*/
public AsyncTaskCancelFlag(AsyncTask<?, ?, ?> task) {
this.task = task;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.CancelFlag#isCancelled()
*/
@Override
public boolean isCancelled() {
return task.isCancelled();
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.CancelFlag#isNotCancelled()
*/
@Override
public boolean isNotCancelled() {
return !task.isCancelled();
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.CancelFlag#cancel()
*/
@Override
public void cancel() {
task.cancel(true);
}
}
SearchPipe<Entity> newItemNotifier;
Action onFinish;
Action onCancel;
CancelFlag cancelFlag;
Context context;
public SearchAsyncTask(Context context, SearchPipe<Entity> newItemNotifier, Action onFinish, Action onCancel) {
this.context = context;
this.newItemNotifier = newItemNotifier;
this.onFinish = onFinish;
this.onCancel = onCancel;
}
@Override
protected Boolean doInBackground(BaseSearchParameter... task) {
this.cancelFlag = new AsyncTaskCancelFlag(this);
if (OsmPoiApplication.searchSource == null) return false;
try{
SearchPipe<Entity> notifier = new SearchPipe<Entity>() {
@Override
public void pushItem(Entity item) {
SearchAsyncTask.this.publishProgress(new ResultItem(item, null));
}
@Override
public void pushRadius(int radius) {
SearchAsyncTask.this.publishProgress(new ResultItem(null, radius));
}
};
if (this.isCancelled()) return false;
Log.d("Search task started");
OsmPoiApplication.searchSource.search(task[0], notifier, this.cancelFlag);
return true;
}catch(Exception e){
Log.wtf("doInBackground", e);
return false;
}
}
@Override
protected void onProgressUpdate(ResultItem... values) {
super.onProgressUpdate(values);
for (ResultItem ri: values){
if (ri.entity != null)
this.newItemNotifier.pushItem(ri.entity);
if (ri.radius != null)
this.newItemNotifier.pushRadius(ri.radius);
}
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result == false){
Toast.makeText(context, context.getString(R.string.error), Toast.LENGTH_SHORT).show();
}
if (onFinish != null)
onFinish.onAction();
Log.d("Search task finished");
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onCancelled()
*/
@Override
protected void onCancelled() {
super.onCancelled();
if (onCancel != null)
onCancel.onAction();
Log.d("Search task canceled");
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.ui;
import il.yrtimid.osm.osmpoi.OsmPoiApplication;
import il.yrtimid.osm.osmpoi.R;
import il.yrtimid.osm.osmpoi.dal.DbAnalyzer;
import android.app.TabActivity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
/**
* @author yrtimid
*
*/
public class AboutActivity extends TabActivity implements TabHost.TabContentFactory {
private interface ItemsCounter {
public Long getCount();
}
DbAnalyzer poiDb = null;
DbAnalyzer addrDb = null;
LayoutInflater inflater;
static final String APP = "app";
static final String HELP = "help";
static final String COPYRIGHT = "copyright";
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inflater = LayoutInflater.from(this);
setContentView(R.layout.about);
poiDb = OsmPoiApplication.databases.getPoiAnalizerDb();
addrDb = OsmPoiApplication.databases.getAddressAnalizerDb();
TabHost host = getTabHost();
TabSpec spec;
spec = host.newTabSpec(APP);
spec.setIndicator(getString(R.string.about));
spec.setContent(this);
host.addTab(spec);
spec = host.newTabSpec(HELP);
spec.setIndicator(getString(R.string.help));
spec.setContent(this);
host.addTab(spec);
spec = host.newTabSpec(COPYRIGHT);
spec.setIndicator(getString(R.string.copyrights));
spec.setContent(this);
host.addTab(spec);
}
/*
* (non-Javadoc)
*
* @see
* android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String
* )
*/
@Override
public View createTabContent(String tag) {
View v = null;
if (tag.equals(APP)) {
v = inflater.inflate(R.layout.about_app, null);
populateVersion(v);
populateDbStats(v);
} else if (tag.equals(HELP)) {
v = inflater.inflate(R.layout.about_help, null);
} else if (tag.equals(COPYRIGHT)) {
v = inflater.inflate(R.layout.about_copyright, null);
populateCopyrightTexts(v);
}
return v;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
/*
if (poiDb != null)
poiDb.close();
if (addrDb != null)
addrDb.close();
*/
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
}
public void populateCount(View v, int dbStatsElementId, String name, final ItemsCounter counter) {
View dbStatsElement = v.findViewById(dbStatsElementId);
TextView nameText = (TextView) dbStatsElement.findViewById(R.id.textName);
nameText.setText(name);
final TextView countText = (TextView) dbStatsElement.findViewById(R.id.textCount);
final View countProgress = dbStatsElement.findViewById(R.id.progressCount);
countText.setVisibility(View.GONE);
countProgress.setVisibility(View.VISIBLE);
AsyncTask<Void, Void, Long> taskCount = new AsyncTask<Void, Void, Long>() {
Long startTime;
Long finishTime;
@Override
protected Long doInBackground(Void... params) {
startTime = System.currentTimeMillis();
Long result = counter.getCount();
finishTime = System.currentTimeMillis();
return result;
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(Long result) {
super.onPostExecute(result);
countProgress.setVisibility(View.GONE);
countText.setVisibility(View.VISIBLE);
countText.setText(result.toString() + " (" + (finishTime - startTime) / 1000 + "sec)");
}
};
taskCount.execute();
}
private void populateVersion(View view){
TextView appNameText = (TextView)view.findViewById(R.id.text_about_app_name);
appNameText.setText(getString(R.string.app_name));
PackageInfo info = null;
try {
info = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if (info != null){
appNameText.setText(getString(R.string.app_name) +" "+ info.versionName);
}
}
private void populateCopyrightTexts(View view){
populateTextFromHtml(view, R.id.about_map_data, R.string.about_map_data);
populateTextFromHtml(view, R.id.about_osmosis, R.string.about_osmosis);
populateTextFromHtml(view, R.id.about_osm_binary, R.string.about_osm_binary);
populateTextFromHtml(view, R.id.about_file_picker, R.string.about_file_picker);
populateTextFromHtml(view, R.id.about_map_icons, R.string.about_map_icons);
populateTextFromHtml(view, R.id.about_map_icons2, R.string.about_map_icons2);
}
private void populateTextFromHtml(View containerView, int textViewId, int resourceId){
TextView text = (TextView)containerView.findViewById(textViewId);
text.setMovementMethod(LinkMovementMethod.getInstance());
text.setText(Html.fromHtml(getString(resourceId)));
}
private void populateDbStats(View v){
populateCount(v, R.id.poi_nodes, "Nodes", new ItemsCounter() {
@Override
public Long getCount() {
return poiDb.getNodesCount();
}
});
populateCount(v, R.id.poi_ways, "Ways", new ItemsCounter() {
@Override
public Long getCount() {
return poiDb.getWaysCount();
}
});
populateCount(v, R.id.poi_relations, "Relations", new ItemsCounter() {
@Override
public Long getCount() {
return poiDb.getRelationsCount();
}
});
populateCount(v, R.id.poi_cells, "Cells", new ItemsCounter() {
@Override
public Long getCount() {
return poiDb.getCellsCount();
}
});
populateCount(v, R.id.addr_nodes, "Nodes", new ItemsCounter() {
@Override
public Long getCount() {
return addrDb.getNodesCount();
}
});
populateCount(v, R.id.addr_ways, "Ways", new ItemsCounter() {
@Override
public Long getCount() {
return addrDb.getWaysCount();
}
});
populateCount(v, R.id.addr_relations, "Relations", new ItemsCounter() {
@Override
public Long getCount() {
return addrDb.getRelationsCount();
}
});
}
}
| Java |
package il.yrtimid.osm.osmpoi.ui;
import il.yrtimid.osm.osmpoi.LocationChangeManager.LocationChangeListener;
import il.yrtimid.osm.osmpoi.OrientationChangeManager.OrientationChangeListener;
import il.yrtimid.osm.osmpoi.OsmPoiApplication;
import il.yrtimid.osm.osmpoi.R;
import il.yrtimid.osm.osmpoi.dal.DbStarred;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.formatters.EntityFormatter;
import il.yrtimid.osm.osmpoi.searchparameters.SearchByParentId;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
public class ResultItemActivity extends Activity implements OnCheckedChangeListener, LocationChangeListener, OrientationChangeListener {
public static final String ENTITY = "ENTITY";
private DbStarred dbHelper;
private Entity entity;
private Location location;
private float azimuth = 0.0f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.result_item_full_view);
Bundle extras = getIntent().getExtras();
this.entity = ((ParcelableEntity) extras.getParcelable(ENTITY)).getEntity();
setIcon();
dbHelper = OsmPoiApplication.databases.getStarredDb();
((TextView)findViewById(R.id.itemViewID)).setText(getString(R.string.ID)+": "+entity.getId());
CheckBox star = ((CheckBox)findViewById(R.id.star));
star.setChecked(dbHelper.isStarred(entity));
star.setOnCheckedChangeListener(this);
Node node = il.yrtimid.osm.osmpoi.Util.getFirstNode(entity);
if (node != null){
TextView textLat = (TextView) findViewById(R.id.textLat);
TextView textLon = (TextView) findViewById(R.id.textLon);
textLat.setText(String.format("Lat: %f", node.getLatitude()));
textLon.setText(String.format("Lon: %f", node.getLongitude()));
}
LayoutInflater inflater = LayoutInflater.from(this);
ViewGroup tags = (ViewGroup) findViewById(R.id.tagsLayout);
for(Tag tag: entity.getTags().getSorted()){
View v = inflater.inflate(R.layout.tag_row, null);
((TextView)v.findViewById(R.id.textKey)).setText(tag.getKey());
((TextView)v.findViewById(R.id.textValue)).setText(tag.getValue());
tags.addView(v);
}
}
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
OsmPoiApplication.locationManager.setLocationChangeListener(this);
OsmPoiApplication.orientationManager.setOrientationChangeListener(this);
updateDistanceAndDirection();
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
OsmPoiApplication.locationManager.setLocationChangeListener(null);
OsmPoiApplication.orientationManager.setOrientationChangeListener(null);
}
private void setIcon() {
ImageView imageType = ((ImageView)findViewById(R.id.imageType));
switch (entity.getType()) {
case Node:
imageType.setImageResource(R.drawable.ic_node);
break;
case Way:
imageType.setImageResource(R.drawable.ic_way);
break;
case Relation:
imageType.setImageResource(R.drawable.ic_relation);
break;
default:
break;
}
}
private void updateDistanceAndDirection(){
TextView tv = (TextView)findViewById(R.id.textDistanceAndDirection);
Node node = il.yrtimid.osm.osmpoi.Util.getFirstNode(entity);
if (node != null && this.location != null){
Location nl = new Location(this.location);
nl.setLatitude(node.getLatitude());
nl.setLongitude(node.getLongitude());
int bearing = Util.normalizeBearing(((int) location.bearingTo(nl)-(int)azimuth));
String distance = Util.formatDistance((int) location.distanceTo(nl));
tv.setText(String.format("%s %c (%d˚)", distance, Util.getDirectionChar(bearing), bearing));
}
else {
tv.setText("");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.item_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mnu_open:
Node node = il.yrtimid.osm.osmpoi.Util.getFirstNode(entity);
if (node != null){
String uri = String.format("geo:%f,%f?z=23", node.getLatitude(), node.getLongitude());
Intent pref = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(pref);
}
return true;
case R.id.mnu_find_associated:
Intent intent = new Intent(this, ResultsActivity.class);
intent.putExtra(ResultsActivity.SEARCH_PARAMETER, new SearchByParentId(entity.getType(), entity.getId()));
startActivity(intent);
default:
return super.onOptionsItemSelected(item);
}
}
/* (non-Javadoc)
* @see android.widget.CompoundButton.OnCheckedChangeListener#onCheckedChanged(android.widget.CompoundButton, boolean)
*/
@Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
setProgressBarIndeterminateVisibility(true);
if (buttonView.isChecked()){
String title = EntityFormatter.format(OsmPoiApplication.formatters, entity, OsmPoiApplication.Config.getResultLanguage());
LayoutInflater inflater = LayoutInflater.from(this);
final EditText textEntryView = (EditText)inflater.inflate(R.layout.starred_title, null);
textEntryView.setText(title);
new AlertDialog.Builder(this)
.setTitle(R.string.title)
.setView(textEntryView)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dbHelper.addStarred(entity, textEntryView.getText().toString());
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
buttonView.setChecked(false);
}
})
.create()
.show();
}else {
dbHelper.removeStarred(entity);
}
setProgressBarIndeterminateVisibility(false);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.LocationChangeManager.LocationChangeListener#OnLocationChanged(android.location.Location)
*/
@Override
public void OnLocationChanged(Location loc) {
this.location = loc;
updateDistanceAndDirection();
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.OrientationChangeManager.OrientationChangeListener#OnOrientationChanged(float)
*/
@Override
public void OnOrientationChanged(float azimuth) {
this.azimuth = azimuth;
updateDistanceAndDirection();
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.ui;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
/**
* @author yrtimid
*
*/
public class DownloadListAdapter extends BaseAdapter {
LayoutInflater inflater;
List<DownloadItem> items;
DownloadItem parent;
/**
* @param context
* @param textViewResourceId
* @param objects
*/
public DownloadListAdapter(Context context, int textViewResourceId, DownloadItem rootItem) {
inflater = LayoutInflater.from(context);
this.items = rootItem.SubItems;
parent = rootItem;
}
/*
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getCount()
*/
@Override
public int getCount() {
if (parent == null)
return items.size();
else
return items.size() + 1;
}
/*
* (non-Javadoc)
*
* @see android.widget.ArrayAdapter#getItem(int)
*/
@Override
public DownloadItem getItem(int position) {
if (position == 0)
return parent;
else
return items.get(position - 1);
}
public void changeLevel(DownloadItem newLevel) {
if (newLevel.Parent != null)
parent = newLevel.Parent;
items = newLevel.SubItems;
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
DownloadItem item = getItem(position);
if (convertView == null) {
//convertView = inflater.inflate(android.R.layout.simple_list_item_2, parent, false);
convertView = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
}
//TwoLineListItem listItem = (TwoLineListItem) convertView;
TextView listItem = (TextView) convertView;
if (position == 0 && parent != null){
//listItem.getText1().setText("..");
listItem.setText("..");
} else{
//listItem.getText1().setText(item.Name);
listItem.setText(item.Name);
}
//listItem.getText2().setText("");
return convertView;
}
@Override
public long getItemId(int position) {
return 0;
}
}
| Java |
package il.yrtimid.osm.osmpoi.ui;
import java.security.InvalidParameterException;
import il.yrtimid.osm.osmpoi.LocationChangeManager.LocationChangeListener;
import il.yrtimid.osm.osmpoi.OrientationChangeManager.OrientationChangeListener;
import il.yrtimid.osm.osmpoi.OsmPoiApplication;
import il.yrtimid.osm.osmpoi.R;
import il.yrtimid.osm.osmpoi.SearchPipe;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.searchparameters.BaseSearchParameter;
import il.yrtimid.osm.osmpoi.searchparameters.SearchAround;
import il.yrtimid.osm.osmpoi.searchparameters.SearchByKeyValue;
import android.app.Activity;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
* Actual search running and results view activity
* @author yrtimid
*
*/
public class ResultsActivity extends Activity implements OnItemClickListener, LocationChangeListener, OrientationChangeListener, OnClickListener {
//public static final String SEARCH_TYPE = "SEARCH_TYPE";
public static final String SEARCH_PARAMETER = "SEARCH_PARAMETER";
private static final int START_RESULTS = 20;
private static final int RESULTS_INCREMENT = 20;
private ResultsAdapter adapter;
private ListView resultsList;
private Boolean followingGPS = true;
private SearchAsyncTask searchTask;
private Button btnMoreResults;
private Boolean waitingForLocation = false;
private final Object waitingForLocationLocker = new Object();
private BaseSearchParameter currentSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSearchParameter();
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.results_view);
adapter = new ResultsAdapter(this, OsmPoiApplication.getCurrentLocation(), OsmPoiApplication.formatters);
adapter.setLocale(OsmPoiApplication.Config.getResultLanguage());
resultsList = (ListView) findViewById(R.id.listResults);
View footer = getLayoutInflater().inflate(R.layout.results_view_footer, null);
//button may become cancel/more only when will be possible to know currant state searching/idle
btnMoreResults = ((Button) footer.findViewById(R.id.btnMoreResults));
btnMoreResults.setOnClickListener(this);
resultsList.addFooterView(footer);
resultsList.setAdapter(adapter);
resultsList.setOnItemClickListener(this);
Entity[] savedData = (Entity[]) getLastNonConfigurationInstance();
if (savedData != null)
adapter.addItems(savedData);
else{
search();
}
}
private void getSearchParameter() {
Bundle extras = getIntent().getExtras();
currentSearch = (BaseSearchParameter)extras.getParcelable(SEARCH_PARAMETER);
currentSearch.setMaxResults(START_RESULTS);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onRetainNonConfigurationInstance()
*/
@Override
public Object onRetainNonConfigurationInstance() {
return adapter.getAllItems();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
updateCountView();
if (followingGPS)
OsmPoiApplication.locationManager.setLocationChangeListener(this);
OsmPoiApplication.orientationManager.setOrientationChangeListener(this);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
cancelCurrentTask();
OsmPoiApplication.locationManager.setLocationChangeListener(null);
OsmPoiApplication.orientationManager.setOrientationChangeListener(null);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.results_menu, menu);
return true;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.mnu_follow).setVisible(!followingGPS);
menu.findItem(R.id.mnu_stop_follow).setVisible(followingGPS);
menu.findItem(R.id.mnu_cancel).setVisible(searchTask != null && searchTask.getStatus() == Status.RUNNING && !searchTask.isCancelled());
menu.findItem(R.id.mnu_refresh).setVisible(searchTask == null || searchTask.getStatus() == Status.FINISHED || searchTask.isCancelled());
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mnu_follow:
OsmPoiApplication.locationManager.setLocationChangeListener(this);
followingGPS = true;
return true;
case R.id.mnu_stop_follow:
OsmPoiApplication.locationManager.setLocationChangeListener(null);
followingGPS = false;
return true;
case R.id.mnu_cancel:
cancelCurrentTask();
return true;
case R.id.mnu_refresh:
adapter.clear();
search();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void updateCountView() {
TextView txt = (TextView) findViewById(R.id.txtCount);
int count = adapter.getCount();
int dist = adapter.getMaximumDistance();
txt.setText(getResources().getQuantityString(R.plurals.results_within, count, count, Util.formatDistance(dist)));
}
private void updateAccuracyView() {
Location curLocation = OsmPoiApplication.getCurrentLocation();
TextView txtAccuracy = (TextView) findViewById(R.id.textAccuracy);
Util.updateAccuracyText(txtAccuracy, curLocation);
}
private void search() {
if (waitingForLocation) return;
if (false == OsmPoiApplication.hasLocation()) {
waitingForLocation = true;
Util.showWaiting(this, null, getString(R.string.waiting_for_location), new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
ResultsActivity.this.waitingForLocation = false;
}
});
return;
}
if (currentSearch instanceof SearchByKeyValue) {
try {
((SearchByKeyValue)currentSearch).getMatcher();
} catch (InvalidParameterException e) {
Toast.makeText(this, getText(R.string.cant_parse) + " " + e.getMessage(), Toast.LENGTH_LONG).show();
return;
}
((SearchByKeyValue)currentSearch).setCenter(OsmPoiApplication.getCurrentLocationPoint());
}else if (currentSearch instanceof SearchAround){
((SearchAround)currentSearch).setCenter(OsmPoiApplication.getCurrentLocationPoint());
}
cancelCurrentTask();
updateCountView();
searchTask = new SearchAsyncTask(this, new SearchPipe<Entity>() {
@Override
public void pushItem(Entity item) {
adapter.addItem(item);
updateCountView();
}
@Override
public void pushRadius(int radius) {
adapter.setRadius(radius);
updateCountView();
}
}, new Action() {
@Override
public void onAction() {
setProgressBarIndeterminateVisibility(false);
Toast.makeText(ResultsActivity.this, getText(R.string.search_finished), Toast.LENGTH_SHORT).show();
searchTask = null;
btnMoreResults.setEnabled(true);
}
}, new Action() {
@Override
public void onAction() {
if (searchTask == null) {
setProgressBarIndeterminateVisibility(false);
Toast.makeText(ResultsActivity.this, getText(R.string.search_cancelled), Toast.LENGTH_SHORT).show();
}
btnMoreResults.setEnabled(true);
}
});
setProgressBarIndeterminateVisibility(true);
btnMoreResults.setEnabled(false);
searchTask.execute(currentSearch);
Toast.makeText(this, OsmPoiApplication.searchSource.getName(), Toast.LENGTH_SHORT).show();
return;
}
public void cancelCurrentTask() {
if (searchTask != null && searchTask.getStatus() != Status.FINISHED) {
SearchAsyncTask t = searchTask;
searchTask = null;
t.cancel(true);
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
cancelCurrentTask();
Entity entity = (Entity) resultsList.getItemAtPosition(position);
Intent intent = new Intent(this, ResultItemActivity.class);
if (entity instanceof Node)
intent.putExtra(ResultItemActivity.ENTITY, new ParcelableNode((Node) entity));
else if (entity instanceof Way)
intent.putExtra(ResultItemActivity.ENTITY, new ParcelableWay((Way) entity));
else if (entity instanceof Relation)
intent.putExtra(ResultItemActivity.ENTITY, new ParcelableRelation((Relation) entity));
startActivity(intent);
// ResultItemDialog dialog = new ResultItemDialog(this, entity);
// dialog.show();
}
/*
* (non-Javadoc)
*
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
if (v.getId() == R.id.btnMoreResults) {
int max = currentSearch.getMaxResults();
currentSearch.setMaxResults(max + RESULTS_INCREMENT);
search();
}
}
/*
* (non-Javadoc)
*
* @see il.yrtimid.osm.osmpoi.LocationChangeManager.LocationChangeListener#
* OnLocationChanged(android.location.Location)
*/
@Override
public void OnLocationChanged(Location loc) {
adapter.setLocation(loc);
updateAccuracyView();
updateCountView();
synchronized (waitingForLocationLocker) {
if (waitingForLocation && OsmPoiApplication.hasLocation()) {
waitingForLocation = false;
Util.dismissWaiting();
search();
}
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.OrientationChangeManager.OrientationChangeListener#OnOrientationChanged(float)
*/
@Override
public void OnOrientationChanged(float azimuth) {
adapter.setAzimuth(azimuth);
}
}
| Java |
package il.yrtimid.osm.osmpoi.ui;
import il.yrtimid.osm.osmpoi.R;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.formatters.EntityFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.content.Context;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TwoLineListItem;
public class ResultsAdapter extends BaseAdapter {
LayoutInflater inflater;
Location location;
float azimuth = 0.0f;
List<Entity> items;
Comparator<Entity> comparator;
List<EntityFormatter> formatters;
int radius;
public ResultsAdapter(Context context, Location location, List<EntityFormatter> formatters) {
this.items = new ArrayList<Entity>();
this.location = location;
inflater = LayoutInflater.from(context);
this.comparator = new DistanceComparator(this.location);
this.formatters = formatters;
}
public void clear() {
items.clear();
notifyDataSetChanged();
}
public void addItem(Entity entity) {
if (!items.contains(entity)) {
items.add(entity);
updateAndSort();
}
}
public void addItems(Entity[] entities) {
for (Entity e : entities) {
if (!items.contains(e)) {
items.add(e);
}
}
updateAndSort();
}
public Entity[] getAllItems(){
return items.toArray(new Entity[items.size()]);
}
public void setLocation(Location newLoc) {
this.location = newLoc;
this.comparator = new DistanceComparator(this.location);
updateAndSort();
}
public void setAzimuth(float azimuth){
this.azimuth = azimuth;
notifyDataSetChanged();
}
public void setRadius(int radius){
this.radius = radius;
}
public void updateAndSort() {
Collections.sort(items, this.comparator);
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Entity item = (Entity)getItem(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.results_view_row, parent, false);
}
TwoLineListItem listItem = (TwoLineListItem) convertView;
String name = getEntityText(item);
listItem.getText1().setText(name);
if (this.location != null){
Node node = il.yrtimid.osm.osmpoi.Util.getFirstNode(item);
if (node != null){
Location nl = new Location(this.location);
nl.setLatitude(node.getLatitude());
nl.setLongitude(node.getLongitude());
int bearing = Util.normalizeBearing ((int) location.bearingTo(nl)-(int)azimuth);
listItem.getText2().setText(String.format("%s %c (%d˚)", Util.formatDistance((int) location.distanceTo(nl)), Util.getDirectionChar(bearing), bearing));
}
}
return convertView;
}
private CharSequence localPostfix = null;
public void setLocale(CharSequence locale) {
if (locale != null)
localPostfix = locale;
else
locale = null;
}
public String getEntityText(Entity entity) {
return EntityFormatter.format(this.formatters, entity, localPostfix);
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return items.get(position).getId();
}
public int getMaximumDistance(){
return radius;
}
/* public int getMaximumDistance(){
Node n = null;
if (items.size()>0){
n = il.yrtimid.osm.osmpoi.Util.getFirstNode(items.get(items.size()-1));
}
if (n!=null){
Location nl = new Location(this.location);
nl.setLatitude(n.getLatitude());
nl.setLongitude(n.getLongitude());
return (int) location.distanceTo(nl);
}else {
return 0;
}
}*/
}
| Java |
package il.yrtimid.osm.osmpoi.ui;
import il.yrtimid.osm.osmpoi.LocationChangeManager.LocationChangeListener;
import il.yrtimid.osm.osmpoi.OsmPoiApplication;
import il.yrtimid.osm.osmpoi.R;
import il.yrtimid.osm.osmpoi.categories.CategoriesLoader;
import il.yrtimid.osm.osmpoi.categories.Category;
import il.yrtimid.osm.osmpoi.dal.DbStarred;
import il.yrtimid.osm.osmpoi.formatters.EntityFormattersLoader;
import il.yrtimid.osm.osmpoi.searchparameters.BaseSearchParameter;
import il.yrtimid.osm.osmpoi.searchparameters.SearchById;
import il.yrtimid.osm.osmpoi.searchparameters.SearchByKeyValue;
import java.util.Collection;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
/**
* Main view with category list and other search options (starred items, custom search)
* @author yrtimid
*
*/
public class SearchActivity extends Activity implements LocationChangeListener, OnItemClickListener {
private static final String EXTRA_CATEGORY = "CATEGORY";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
setupCategories();
setupFormatters();
}
private void setupCategories() {
if (OsmPoiApplication.mainCategory == null)
OsmPoiApplication.mainCategory = CategoriesLoader.load(this);
ListView list = (ListView)findViewById(R.id.listCategories);
Bundle extras = getIntent().getExtras();
Category cat;
if (extras!=null && extras.containsKey(EXTRA_CATEGORY)){
cat = (Category) extras.getParcelable(EXTRA_CATEGORY);
}else {
cat = OsmPoiApplication.mainCategory;
}
CategoriesListAdapter adapter = new CategoriesListAdapter(this, cat);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
private void setupFormatters(){
if (OsmPoiApplication.formatters == null)
OsmPoiApplication.formatters = EntityFormattersLoader.load(this);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
OsmPoiApplication.Config.reloadConfig(this);
checkSearchSource();
OsmPoiApplication.locationManager.setLocationChangeListener(this);
//CharSequence lastSearch = Preferences.getLastSearch(this);
//EditText txtSearch = (EditText) findViewById(R.id.txtSearch);
//txtSearch.setText(lastSearch);
}
@Override
protected void onPause() {
super.onPause();
OsmPoiApplication.locationManager.setLocationChangeListener(null);
//EditText txtSearch = (EditText) findViewById(R.id.txtSearch);
//Preferences.setLastSearch(this, txtSearch.getText());
OsmPoiApplication.locationManager.setLocationChangeListener(null);
// Another activity is taking focus (this activity is about to be
// "paused").
}
@Override
protected void onStop() {
super.onStop();
//if (OsmPoiApplication.searchSource != null)
//OsmPoiApplication.searchSource.close();
// The activity is no longer visible (it is now "stopped")
}
@Override
protected void onDestroy() {
super.onDestroy();
// The activity is about to be destroyed.
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mnu_settings:
Intent pref = new Intent(this, Preferences.class);
startActivity(pref);
return true;
case R.id.mnu_about:
startActivity(new Intent(this, AboutActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void checkSearchSource() {
View mainLayout = findViewById(R.id.layoutMain);
View warning = findViewById(R.id.layoutNoSearchSource_ref);
if (OsmPoiApplication.searchSource == null) {
mainLayout.setVisibility(View.GONE);
warning.setVisibility(View.VISIBLE);
} else {
mainLayout.setVisibility(View.VISIBLE);
warning.setVisibility(View.GONE);
}
}
private void search(BaseSearchParameter search) {
Intent intent = new Intent(this, ResultsActivity.class);
//intent.putExtra(ResultsActivity.SEARCH_TYPE, searchType);
if (search instanceof SearchByKeyValue){
intent.putExtra(ResultsActivity.SEARCH_PARAMETER, (SearchByKeyValue)search);
}else if (search instanceof SearchById){
intent.putExtra(ResultsActivity.SEARCH_PARAMETER, (SearchById)search);
}
startActivity(intent);
}
/* (non-Javadoc)
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Category cat = (Category)parent.getItemAtPosition(position);
switch (cat.getType()){
case NONE:
showCategory(cat);
break;
case STARRED:
DbStarred dbStarredHelper = OsmPoiApplication.databases.getStarredDb();
Collection<Category> starred = dbStarredHelper.getAllStarred();
cat.getSubCategories().clear();
cat.getSubCategories().addAll(starred);
showCategory(cat);
break;
case CUSTOM:
LayoutInflater inflater = LayoutInflater.from(this);
final EditText textEntryView = (EditText)inflater.inflate(R.layout.custom_search, null);
new AlertDialog.Builder(this)
.setTitle(R.string.custom_search)
.setView(textEntryView)
.setPositiveButton(R.string.search, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
search(new SearchByKeyValue(textEntryView.getText().toString()));
}
})
.create()
.show();
break;
case SEARCH:
search(cat.getSearchParameter());
break;
case INLINE_SEARCH:
if (cat.isSubCategoriesFetched()){
showCategory(cat);
}else {
AsyncTask<Category, Void, Category> asyncLoad = new AsyncTask<Category, Void, Category>(){
@Override
protected Category doInBackground(Category... params) {
CategoriesLoader.loadInlineCategories(SearchActivity.this, params[0]);
return params[0];
}
@Override
protected void onPostExecute(Category result) {
super.onPostExecute(result);
Util.dismissWaiting();
SearchActivity.this.showCategory(result);
}
};
Util.showWaiting(this, getString(R.string.category), null);
asyncLoad.execute(cat);
}
break;
}
}
private void showCategory(Category cat) {
Intent intent = new Intent(this, SearchActivity.class);
intent.putExtra(EXTRA_CATEGORY, cat);
startActivity(intent);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.LocationManager.LocationChangeListener#OnLocationChanged(android.location.Location)
*/
@Override
public void OnLocationChanged(Location loc) {
if (OsmPoiApplication.getCurrentLocation() != null) {
TextView txtAccuracy = (TextView) findViewById(R.id.textAccuracy);
Util.updateAccuracyText(txtAccuracy, OsmPoiApplication.getCurrentLocation());
}
}
} | Java |
package il.yrtimid.osm.osmpoi.parcelables;
import il.yrtimid.osm.osmpoi.Point;
import android.os.Parcel;
import android.os.Parcelable;
public class SearchParameters implements android.os.Parcelable{
private Point center;
private String expression;
private int maxResults;
public static final Parcelable.Creator<SearchParameters> CREATOR = new Parcelable.Creator<SearchParameters>() {
@Override
public SearchParameters createFromParcel(Parcel source) {
return new SearchParameters(source);
}
@Override
public SearchParameters[] newArray(int size) {
return new SearchParameters[size];
}
};
public SearchParameters(){
this.center = new Point(0,0);
this.maxResults = 0;
}
public SearchParameters(Parcel source){
expression = source.readString();
this.center = new Point(source.readDouble(), source.readDouble());
maxResults = source.readInt();
}
public void setCenter(Point center) {
this.center = center;
}
public Point getCenter() {
return center;
}
public int getMaxResults() {
return maxResults;
}
public void setMaxResults(int maxResults) {
this.maxResults = maxResults;
}
public void setExpression(String expression) {
this.expression = expression;
}
public String getExpression(){
return this.expression;
}
public boolean hasExpression(){
return this.expression != null && this.expression.length()>0;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(expression);
dest.writeDouble(center.getLatitude());
dest.writeDouble(center.getLongitude());
dest.writeInt(maxResults);
}
}
| Java |
/*
* Copyright 2011 Anders Kalør
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT 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.kaloer.filepicker;
import il.yrtimid.osm.osmpoi.R;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FilePickerActivity extends ListActivity {
/**
* The file path
*/
public final static String EXTRA_FILE_PATH = "file_path";
/**
* Sets whether hidden files should be visible in the list or not
*/
public final static String EXTRA_SHOW_HIDDEN_FILES = "show_hidden_files";
/**
* The allowed file extensions in an ArrayList of Strings
*/
public final static String EXTRA_ACCEPTED_FILE_EXTENSIONS = "accepted_file_extensions";
/**
* The initial directory which will be used if no directory has been sent with the intent
*/
private final static String DEFAULT_INITIAL_DIRECTORY = "/";
protected File mDirectory;
protected ArrayList<File> mFiles;
protected FilePickerListAdapter mAdapter;
protected boolean mShowHiddenFiles = false;
protected String[] acceptedFileExtensions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the view to be shown if the list is empty
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View emptyView = inflator.inflate(R.layout.file_picker_empty_view, null);
((ViewGroup)getListView().getParent()).addView(emptyView);
getListView().setEmptyView(emptyView);
// Set initial directory
mDirectory = new File(DEFAULT_INITIAL_DIRECTORY);
// Initialize the ArrayList
mFiles = new ArrayList<File>();
// Set the ListAdapter
mAdapter = new FilePickerListAdapter(this, mFiles);
setListAdapter(mAdapter);
// Initialize the extensions array to allow any file extensions
acceptedFileExtensions = new String[] {};
// Get intent extras
if(getIntent().hasExtra(EXTRA_FILE_PATH)) {
mDirectory = new File(getIntent().getStringExtra(EXTRA_FILE_PATH));
}
if(getIntent().hasExtra(EXTRA_SHOW_HIDDEN_FILES)) {
mShowHiddenFiles = getIntent().getBooleanExtra(EXTRA_SHOW_HIDDEN_FILES, false);
}
if(getIntent().hasExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS)) {
ArrayList<String> collection = getIntent().getStringArrayListExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS);
acceptedFileExtensions = (String[]) collection.toArray(new String[collection.size()]);
}
}
@Override
protected void onResume() {
refreshFilesList();
super.onResume();
}
/**
* Updates the list view to the current directory
*/
protected void refreshFilesList() {
// Clear the files ArrayList
mFiles.clear();
// Set the extension file filter
ExtensionFilenameFilter filter = new ExtensionFilenameFilter(acceptedFileExtensions);
// Get the files in the directory
File[] files = mDirectory.listFiles(filter);
if(files != null && files.length > 0) {
for(File f : files) {
if(f.isHidden() && !mShowHiddenFiles) {
// Don't add the file
continue;
}
// Add the file the ArrayAdapter
mFiles.add(f);
}
Collections.sort(mFiles, new FileComparator());
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onBackPressed() {
if(mDirectory.getParentFile() != null) {
// Go to parent directory
mDirectory = mDirectory.getParentFile();
refreshFilesList();
return;
}
super.onBackPressed();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File newFile = (File)l.getItemAtPosition(position);
if(newFile.isFile()) {
// Set result
Intent extra = new Intent();
extra.putExtra(EXTRA_FILE_PATH, newFile.getAbsolutePath());
setResult(RESULT_OK, extra);
// Finish the activity
finish();
} else {
mDirectory = newFile;
// Update the files list
refreshFilesList();
}
super.onListItemClick(l, v, position, id);
}
private class FilePickerListAdapter extends ArrayAdapter<File> {
private List<File> mObjects;
public FilePickerListAdapter(Context context, List<File> objects) {
super(context, R.layout.file_picker_list_item, android.R.id.text1, objects);
mObjects = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.file_picker_list_item, parent, false);
} else {
row = convertView;
}
File object = mObjects.get(position);
ImageView imageView = (ImageView)row.findViewById(R.id.file_picker_image);
TextView textView = (TextView)row.findViewById(R.id.file_picker_text);
// Set single line
textView.setSingleLine(true);
textView.setText(object.getName());
if(object.isFile()) {
// Show the file icon
imageView.setImageResource(R.drawable.file);
} else {
// Show the folder icon
imageView.setImageResource(R.drawable.folder);
}
return row;
}
}
private class FileComparator implements Comparator<File> {
@Override
public int compare(File f1, File f2) {
if(f1 == f2) {
return 0;
}
if(f1.isDirectory() && f2.isFile()) {
// Show directories above files
return -1;
}
if(f1.isFile() && f2.isDirectory()) {
// Show files below directories
return 1;
}
// Sort the directories alphabetically
return f1.getName().compareToIgnoreCase(f2.getName());
}
}
private class ExtensionFilenameFilter implements FilenameFilter {
private String[] mExtensions;
public ExtensionFilenameFilter(String[] extensions) {
super();
mExtensions = extensions;
}
@Override
public boolean accept(File dir, String filename) {
if(new File(dir, filename).isDirectory()) {
// Accept all directory names
return true;
}
if(mExtensions != null && mExtensions.length > 0) {
for(int i = 0; i < mExtensions.length; i++) {
if(filename.endsWith(mExtensions[i])) {
// The filename ends with the extension
return true;
}
}
// The filename did not match any of the extensions
return false;
}
// No extensions has been set. Accept all file extensions.
return true;
}
}
}
| 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.buzz;
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;
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.buzz;
import com.google.api.client.sample.buzz.model.BuzzActivity;
import com.google.api.client.sample.buzz.model.BuzzActivityFeed;
/**
* @author Yaniv Inbar
*/
public class View {
static void header(String name) {
System.out.println();
System.out.println("============== " + name + " ==============");
System.out.println();
}
static void display(BuzzActivityFeed feed) {
for (BuzzActivity activity : feed.items) {
System.out.println();
System.out.println("-----------------------------------------------");
display(activity);
}
}
static void display(BuzzActivity activity) {
System.out.println("Content: " + activity.object.content);
System.out.println("Updated: " + activity.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.buzz;
import com.google.api.client.auth.oauth.OAuthAuthorizeTemporaryTokenUrl;
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.GoogleOAuthGetAccessToken;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthGetTemporaryToken;
import com.google.api.client.sample.buzz.model.Util;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.net.URI;
/**
* Implements OAuth authentication.
*
* @author Yaniv Inbar
*/
public class Auth {
private static OAuthHmacSigner signer;
private static OAuthCredentialsResponse credentials;
static void authorize() 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 = Util.AUTH_TRANSPORT;
signer = new OAuthHmacSigner();
signer.clientSharedSecret = ClientCredentials.ENTER_OAUTH_CONSUMER_SECRET;
temporaryToken.signer = signer;
temporaryToken.consumerKey = ClientCredentials.ENTER_OAUTH_CONSUMER_KEY;
temporaryToken.scope = "https://www.googleapis.com/auth/buzz";
temporaryToken.displayName = BuzzSample.APP_DESCRIPTION;
temporaryToken.callback = callbackServer.getCallbackUrl();
OAuthCredentialsResponse tempCredentials = temporaryToken.execute();
signer.tokenSharedSecret = tempCredentials.tokenSecret;
// authorization URL
OAuthAuthorizeTemporaryTokenUrl authorizeUrl = new OAuthAuthorizeTemporaryTokenUrl(
"https://www.google.com/buzz/api/auth/OAuthAuthorizeToken");
authorizeUrl.set("scope", temporaryToken.scope);
authorizeUrl.set("domain", ClientCredentials.ENTER_OAUTH_CONSUMER_KEY);
authorizeUrl.set("xoauth_displayname", BuzzSample.APP_DESCRIPTION);
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();
}
}
// access token
GoogleOAuthGetAccessToken accessToken = new GoogleOAuthGetAccessToken();
accessToken.transport = Util.AUTH_TRANSPORT;
accessToken.temporaryToken = tempToken;
accessToken.signer = signer;
accessToken.consumerKey = ClientCredentials.ENTER_OAUTH_CONSUMER_KEY;
accessToken.verifier = verifier;
credentials = accessToken.execute();
signer.tokenSharedSecret = credentials.tokenSecret;
createOAuthParameters().signRequestsUsingAuthorizationHeader(Util.TRANSPORT);
}
static void revoke() {
if (credentials != null) {
try {
GoogleOAuthGetAccessToken.revokeAccessToken(Util.AUTH_TRANSPORT, createOAuthParameters());
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
private static OAuthParameters createOAuthParameters() {
OAuthParameters authorizer = new OAuthParameters();
authorizer.consumerKey = ClientCredentials.ENTER_OAUTH_CONSUMER_KEY;
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.buzz;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.sample.buzz.model.BuzzActivity;
import com.google.api.client.sample.buzz.model.BuzzActivityFeed;
import com.google.api.client.sample.buzz.model.BuzzObject;
import com.google.api.client.sample.buzz.model.Util;
import java.io.IOException;
/**
* @author Yaniv Inbar
*/
public class BuzzSample {
static final String APP_DESCRIPTION = "Buzz API Java Client Sample";
public static void main(String[] args) {
Util.enableLogging();
try {
try {
setUpTransport();
authorize();
showActivities();
BuzzActivity activity = insertActivity();
activity = updateActivity(activity);
deleteActivity(activity);
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 void setUpTransport() {
JsonCParser parser = new JsonCParser();
parser.jsonFactory = Util.JSON_FACTORY;
Util.TRANSPORT.addParser(parser);
}
private static void authorize() throws Exception {
Auth.authorize();
}
private static void showActivities() throws IOException {
View.header("Show Buzz Activities");
BuzzActivityFeed feed = BuzzActivityFeed.list();
View.display(feed);
}
private static BuzzActivity insertActivity() throws IOException {
View.header("Insert Buzz Activity");
BuzzActivity activity = new BuzzActivity();
activity.object = new BuzzObject();
activity.object.content = "Posting using " + BuzzSample.APP_DESCRIPTION;
BuzzActivity result = activity.post();
View.display(result);
return result;
}
private static BuzzActivity updateActivity(BuzzActivity activity) throws IOException {
View.header("Update Buzz Activity");
activity.object.content += " (http://goo.gl/rOyC)";
BuzzActivity result = activity.update();
View.display(result);
return result;
}
private static void deleteActivity(BuzzActivity activity) throws IOException {
View.header("Delete Buzz Activity");
activity.delete();
System.out.println("Deleted.");
}
}
| 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.buzz;
/**
* @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.buzz.model;
import com.google.api.client.googleapis.json.JsonCContent;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.Key;
import java.io.IOException;
/**
* Buzz activity, such as a Buzz post.
*
* <p>
* The JSON of a typical activity looks like this:
*
* <pre>
* <code>{
* "id": "tag:google.com,2010:buzz:z12puk22ajfyzsz",
* "updated": "2010-10-04T16:27:15.169Z",
* "object": {
* "content": "Hey, this is my first Buzz Post!",
* ...
* },
* ...
* }</code>
* </pre>
*
* @author Yaniv Inbar
*/
public class BuzzActivity extends GenericJson {
/** Activity identifier. */
@Key
public String id;
/** Buzz details containing the content of the activity. */
@Key
public BuzzObject object;
/** Last time the activity was updated. */
@Key
public DateTime updated;
/**
* Post this Buzz Activity.
*
* @return posted Buzz Activity response from the Buzz server
* @throws IOException any I/O exception
*/
public BuzzActivity post() throws IOException {
HttpRequest request = Util.TRANSPORT.buildPostRequest();
request.url = BuzzUrl.forMyActivityFeed();
request.content = toContent();
return request.execute().parseAs(BuzzActivity.class);
}
/**
* Update this Buzz Activity.
*
* @return updated Buzz Activity response from the Buzz server
* @throws IOException any I/O exception
*/
public BuzzActivity update() throws IOException {
HttpRequest request = Util.TRANSPORT.buildPutRequest();
request.url = BuzzUrl.forMyActivity(this.id);
request.content = toContent();
return request.execute().parseAs(BuzzActivity.class);
}
/**
* Post this Buzz Activity.
*
* @throws IOException any I/O exception
*/
public void delete() throws IOException {
HttpRequest request = Util.TRANSPORT.buildDeleteRequest();
request.url = BuzzUrl.forMyActivity(this.id);
request.execute().ignore();
}
/** Returns a new JSON-C content serializer for this Buzz activity. */
private JsonCContent toContent() {
JsonCContent result = new JsonCContent();
result.data = this;
result.jsonFactory = Util.JSON_FACTORY;
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.buzz.model;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleUtils;
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.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();
public static final HttpTransport AUTH_TRANSPORT = newTransport();
public static final JsonFactory JSON_FACTORY = new JacksonFactory();
static HttpTransport newTransport() {
HttpTransport result = new NetHttpTransport();
GoogleUtils.useMethodOverride(result);
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-BuzzSample/1.0");
result.defaultHeaders = headers;
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.buzz.model;
import com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.util.Key;
/**
* Buzz URL builder.
*
* @author Yaniv Inbar
*/
public class BuzzUrl extends GoogleUrl {
@Key("max-results")
public Integer maxResults = 5;
/** Constructs a new Buzz URL from the given encoded URL. */
public BuzzUrl(String encodedUrl) {
super(encodedUrl);
alt = "json";
if (Util.DEBUG) {
prettyprint = true;
}
}
public static BuzzUrl forMyActivityFeed() {
return new BuzzUrl("https://www.googleapis.com/buzz/v1/activities/@me/@self");
}
public static BuzzUrl forMyActivity(String activityId) {
BuzzUrl result = forMyActivityFeed();
result.pathParts.add(activityId);
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.buzz.model;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
/**
* Buzz Object.
*
* <p>
* The JSON of a typical Buzz object looks like this:
*
* <pre>
* <code>{
* "content": "Hey, this is my first Buzz Post!",
* ...
* }</code>
* </pre>
*
* @author Yaniv Inbar
*/
public class BuzzObject extends GenericJson {
/** HTML content. */
@Key
public String 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.buzz.model;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Buzz activity feed.
*
* <p>
* The JSON of a typical activity feed looks like this:
*
* <pre>
* <code>{
* "data": {
* "items": [
* {
* "id": "tag:google.com,2010:buzz:z12puk22ajfyzsz",
* "object": {
* "content": "Hey, this is my first Buzz Post!",
* ...
* },
* ...
* }
* ]
* ]
* }
* }</code>
* </pre>
*
* @author Yaniv Inbar
*/
public class BuzzActivityFeed {
/** List of activities. */
@Key
public List<BuzzActivity> items = new ArrayList<BuzzActivity>();
/**
* List the user's Buzz activities.
*
* @return Buzz activities feed response from the Buzz server
* @throws IOException any I/O exception
*/
public static BuzzActivityFeed list() throws IOException {
HttpRequest request = Util.TRANSPORT.buildGetRequest();
request.url = BuzzUrl.forMyActivityFeed();
return request.execute().parseAs(BuzzActivityFeed.class);
}
}
| Java |
package com.google.api.client.sample.buzz.v1.android;
import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
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.json.jackson.JacksonFactory;
import com.google.api.services.buzz.v1.Buzz;
import com.google.api.services.buzz.v1.model.ActivityFeed;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Sample for Buzz on Android. It shows how to authenticate, show activities, post a new activity,
* update it, and delete it.
* <p>
* To enable logging of HTTP requests/responses, change {@link #LOGGING_LEVEL} to
* {@link Level#CONFIG} or {@link Level#ALL} and run this command:
* </p>
*
* <pre>
adb shell setprop log.tag.HttpTransport DEBUG
* </pre>
*
* @author Yaniv Inbar
*/
public class BuzzSample extends Activity {
/** Logging level for HTTP requests/responses. */
// private static Level LOGGING_LEVEL = Level.OFF;
private static Level LOGGING_LEVEL = Level.ALL;
private static final String TAG = "BuzzSample";
// private static final String AUTH_TOKEN_TYPE = "Google Buzz";
private static final String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/buzz";
private static final String PREF = "MyPrefs";
private static final int DIALOG_ACCOUNTS = 0;
private static final int MENU_ACCOUNTS = 0;
public static final int REQUEST_AUTHENTICATE = 0;
private final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final Buzz buzz = new Buzz("Google-BuzzSample/1.0", transport, new JacksonFactory());
// TODO(yanivi): save auth token in preferences
public String authToken;
public GoogleAccountManager accountManager;
@Override
public void onCreate(Bundle savedInstanceState) {
System.out.println("onCreate");
super.onCreate(savedInstanceState);
accountManager = new GoogleAccountManager(this);
Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
gotAccount(false);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ACCOUNTS:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select a Google account");
final Account[] accounts = accountManager.getAccounts();
final int size = accounts.length;
String[] names = new String[size];
for (int i = 0; i < size; i++) {
names[i] = accounts[i].name;
}
builder.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
gotAccount(accounts[which]);
}
});
return builder.create();
}
return null;
}
void gotAccount(boolean tokenExpired) {
SharedPreferences settings = getSharedPreferences(PREF, 0);
String accountName = settings.getString("accountName", null);
Account account = accountManager.getAccountByName(accountName);
if (account != null) {
if (tokenExpired) {
accountManager.invalidateAuthToken(authToken);
authToken = null;
}
gotAccount(account);
return;
}
showDialog(DIALOG_ACCOUNTS);
}
void gotAccount(final Account account) {
SharedPreferences settings = getSharedPreferences(PREF, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("accountName", account.name);
editor.commit();
accountManager.manager.getAuthToken(
account, AUTH_TOKEN_TYPE, true, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle bundle = future.getResult();
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, REQUEST_AUTHENTICATE);
} else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
onAuthToken();
}
} catch (Exception e) {
handleException(e);
}
}
}, null);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_AUTHENTICATE:
if (resultCode == RESULT_OK) {
gotAccount(false);
} else {
showDialog(DIALOG_ACCOUNTS);
}
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_ACCOUNTS, 0, "Switch Account");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ACCOUNTS:
showDialog(DIALOG_ACCOUNTS);
return true;
}
return false;
}
void handleException(Exception e) {
e.printStackTrace();
if (e instanceof HttpResponseException) {
HttpResponse response = ((HttpResponseException) e).response;
int statusCode = response.statusCode;
try {
response.ignore();
} catch (IOException e1) {
e1.printStackTrace();
}
// TODO(yanivi): should only try this once to avoid infinite loop
if (statusCode == 401) {
gotAccount(true);
return;
}
}
Log.e(TAG, e.getMessage(), e);
}
void onAuthToken() {
new GoogleAccessProtectedResource(authToken) {
@Override
protected void onAccessToken(String accessToken) {
gotAccount(true);
}
};
buzz.setAccessToken(authToken);
setContentView(R.layout.main);
final ListView activitiesListView = (ListView) findViewById(R.id.activities);
// TODO(yanivi): refresh activities
// TODO(yanivi): set logging level
registerForContextMenu(activitiesListView);
new LoadActivities().execute();
}
private static final String FIELDS_ACTIVITY = "object/content,updated,id";
private static final String FIELDS_ACTIVITY_FEED = "items(" + FIELDS_ACTIVITY + ")";
class LoadActivities extends AsyncTask<Void, Void, ActivityFeed> {
private final ProgressDialog dialog = new ProgressDialog(BuzzSample.this);
@Override
protected void onPreExecute() {
dialog.setMessage(getString(R.string.loading_activities));
dialog.show();
// ListView activitiesListView = (ListView) findViewById(R.id.activities);
// activitiesListView.setAdapter(
// new ArrayAdapter<String>(BuzzSample.this, R.layout.textview, R.id.textView,
// new String[] {getString(R.string.loading_activities)}));
}
@Override
protected ActivityFeed doInBackground(Void... params) {
// TODO(yanivi): load all pages and publish progress ?!
try {
com.google.api.services.buzz.v1.Buzz.Activities.List request =
buzz.activities.list("@me", "@consumption");
request.put("fields", FIELDS_ACTIVITY_FEED);
return request.execute();
} catch (Exception e) {
handleException(e);
return null;
}
}
@Override
protected void onPostExecute(ActivityFeed feed) {
dialog.dismiss();
if (feed == null) {
return;
}
List<Spanned> activities = new ArrayList<Spanned>();
if (feed.items != null) {
for (com.google.api.services.buzz.v1.model.Activity a : feed.items) {
activities.add(Html.fromHtml(a.buzzObject.content));
}
}
// TODO(yanivi): show poster's name and image and time of posting
// TODO(yanivi): show a next link
Spanned[] activityContents;
if (activities.isEmpty()) {
activityContents = new Spanned[] {Html.fromHtml(getString(R.string.no_activities))};
} else {
activityContents = activities.toArray(new Spanned[0]);
}
ListView activitiesListView = (ListView) findViewById(R.id.activities);
activitiesListView.setAdapter(new ArrayAdapter<Spanned>(
BuzzSample.this, R.layout.textview, R.id.textView, activityContents));
}
}
}
| 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;
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.
* </p>
*
* @author Yaniv Inbar
*/
public class LoginCallbackServer {
private static final String CALLBACK_PATH = "/OAuthCallback";
private int port;
private Server server;
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.discovery;
import com.google.api.client.auth.oauth.OAuthAuthorizeTemporaryTokenUrl;
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.googleapis.json.DiscoveryDocument.ServiceMethod;
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 Discovery API Client 1.0.0";
private static OAuthHmacSigner signer;
private static OAuthCredentialsResponse credentials;
static void authorize(HttpTransport transport, String apiName, ServiceMethod method)
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/" + apiName;
temporaryToken.displayName = APP_NAME;
temporaryToken.callback = callbackServer.getCallbackUrl();
OAuthCredentialsResponse tempCredentials = temporaryToken.execute();
signer.tokenSharedSecret = tempCredentials.tokenSecret;
// authorization URL
OAuthAuthorizeTemporaryTokenUrl authorizeUrl;
if (apiName.equals("buzz")) {
authorizeUrl = new OAuthAuthorizeTemporaryTokenUrl(
"https://www.google.com/buzz/api/auth/OAuthAuthorizeToken");
authorizeUrl.set("scope", temporaryToken.scope);
authorizeUrl.set("domain", "anonymous");
authorizeUrl.set("xoauth_displayname", APP_NAME);
} else if (apiName.equals("latitude")) {
// TODO: test!
authorizeUrl = new OAuthAuthorizeTemporaryTokenUrl(
"https://www.google.com/latitude/apps/OAuthAuthorizeToken");
} else {
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(HttpTransport transport) {
if (credentials != null) {
try {
GoogleOAuthGetAccessToken.revokeAccessToken(transport, 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.discovery;
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 {
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.discovery;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.SortedSet;
/**
* @author Yaniv Inbar
*/
public class MethodDetails implements Comparable<MethodDetails> {
String name;
ArrayList<String> requiredParameters = Lists.newArrayList();
SortedSet<String> optionalParameters = Sets.newTreeSet();
boolean hasContent;
@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;
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.HttpRequest;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.http.apache.ApacheHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Yaniv Inbar
*/
public class DiscoverySample {
private static final String APP_NAME = "Google Discovery API Client 1.1.0";
private static final Pattern API_NAME_PATTERN = Pattern.compile("\\w+");
private static final Pattern API_VERSION_PATTERN = Pattern.compile("[\\w.]+");
private static final Pattern METHOD_PATTERN = Pattern.compile("(\\w+)\\.(\\w+)");
public static void main(String[] args) throws Exception {
Debug.enableLogging();
// parse command argument
if (args.length == 0) {
showMainHelp();
} else {
String command = args[0];
if (command.equals("help")) {
help(args);
} else if (command.equals("call")) {
call(args);
} else if (command.equals("discover")) {
discover(args);
} else {
error(null, "unknown command: " + command);
}
}
}
private static void help(String[] args) {
if (args.length == 1) {
showMainHelp();
} else {
String helpCommand = args[1];
if (helpCommand.equals("call")) {
System.out.println("Usage: google call apiName apiVersion methodName [parameters]");
System.out.println();
System.out.println("Examples:");
System.out.println(" google call discovery v0.2beta1 apis.get buzz v1");
System.out.println(" google call buzz v1 activities.list @me @self "
+ "--max-results 3 --alt json --prettyprint true");
System.out.println(" echo {\\\"data\\\":{\\\"object\\\":{\\\"content\\\":"
+ "\\\"Posting using Google command-line tool based on "
+ "Discovery \\(http://goo.gl/ojuXq\\)\\\"}}} > "
+ "buzzpost.json && google call buzz v1 activities.insert @me buzzpost.json");
} else if (helpCommand.equals("discover")) {
System.out.println("Usage: google discover apiName apiVersion");
System.out.println();
System.out.println("Examples:");
System.out.println(" google discover buzz v1");
System.out.println(" google discover moderator v1");
} else {
error(null, "unknown command: " + helpCommand);
}
}
}
private static void showMainHelp() {
System.out.println(APP_NAME);
System.out.println();
System.out.println("For more help on a specific command, type one of:");
System.out.println();
System.out.println(" google help call");
System.out.println(" google help discover");
}
private static void error(String command, String detail) {
System.err.println("ERROR: " + detail);
System.err.println("For help, type: google" + (command == null ? "" : " help " + command));
System.exit(1);
}
private static void call(String[] args) throws Exception {
// load discovery document
if (args.length == 1) {
error("call", "missing api name");
}
if (args.length == 2) {
error("call", "missing api version");
}
if (args.length == 3) {
error("call", "missing method name");
}
String apiName = args[1];
String apiVersion = args[2];
String fullMethodName = args[3];
Matcher m = METHOD_PATTERN.matcher(fullMethodName);
if (!m.matches()) {
error("call", "invalid method name: " + fullMethodName);
}
String resourceName = m.group(1);
String methodName = m.group(2);
GoogleApi api = loadGoogleAPI("call", apiName, apiVersion);
Map<String, ServiceResource> resources = api.serviceDefinition.resources;
ServiceMethod method = null;
if (resources != null) {
ServiceResource resource = resources.get(resourceName);
Map<String, ServiceMethod> methods = resource.methods;
if (methods != null) {
method = methods.get(methodName);
}
}
if (method == null) {
error("call", "method not found: " + fullMethodName);
}
HashMap<String, String> parameters = Maps.newHashMap();
HashMap<String, String> queryParameters = Maps.newHashMap();
File requestBodyFile = null;
String contentType = "application/json";
int i = 4;
// required parameters
for (String reqParam : getRequiredParameters(method).keySet()) {
if (i == args.length) {
error("call", "missing required parameter: " + reqParam);
} else {
parameters.put(reqParam, args[i++]);
}
}
// possibly required content
if (!method.httpMethod.equals("GET") && !method.httpMethod.equals("DELETE")) {
String fileName = args[i++];
requestBodyFile = new File(fileName);
if (!requestBodyFile.canRead()) {
error("call", "unable to read file: " + fileName);
}
}
while (i < args.length) {
String argName = args[i++];
if (!argName.startsWith("--")) {
error("call", "optional parameters must start with \"--\": " + argName);
}
String parameterName = argName.substring(2);
if (i == args.length) {
error("call", "missing parameter value for: " + argName);
}
String parameterValue = args[i++];
if (parameterName.equals("contentType")) {
contentType = parameterValue;
if (method.httpMethod.equals("GET") || method.httpMethod.equals("DELETE")) {
error("call", "HTTP content type cannot be specified for this method: " + argName);
}
} else if (method.parameters == null || !method.parameters.containsKey(parameterName)) {
queryParameters.put(parameterName, parameterValue);
} else {
String oldValue = parameters.put(parameterName, parameterValue);
if (oldValue != null) {
error("call", "duplicate parameter: " + argName);
}
}
}
HttpRequest request = api.buildRequest(resourceName + "." + methodName, parameters);
// TODO(yanivi): bug that if prettyprint is set, error on String -> Boolean conversion
request.url.putAll(queryParameters);
if (requestBodyFile != null) {
InputStreamContent fileContent = new InputStreamContent();
fileContent.type = contentType;
fileContent.setFileInput(requestBodyFile);
request.content = fileContent;
}
try {
if (apiName.equals("bigquery") || apiName.equals("prediction")
|| apiName.equals("latitude")) {
error("call", "API not supported: " + apiName);
}
if (!apiName.equals("discovery") && !apiName.equals("diacritize")) {
Auth.authorize(api.transport, apiName, method);
}
String response = request.execute().parseAsString();
System.out.println(response);
Auth.revoke(api.transport);
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
Auth.revoke(api.transport);
System.exit(1);
} catch (Throwable t) {
t.printStackTrace();
Auth.revoke(api.transport);
System.exit(1);
}
}
private static GoogleApi loadGoogleAPI(String command, String apiName, String apiVersion)
throws IOException {
if (!API_NAME_PATTERN.matcher(apiName).matches()) {
error(command, "invalid API name: " + apiName);
}
if (!API_VERSION_PATTERN.matcher(apiVersion).matches()) {
error(command, "invalid API version: " + apiVersion);
}
GoogleApi api = new GoogleApi();
api.name = apiName;
api.version = apiVersion;
api.jsonFactory = new JacksonFactory();
api.discoveryTransport = new ApacheHttpTransport();
api.transport = new ApacheHttpTransport();
try {
api.load();
} catch (HttpResponseException e) {
if (e.response.statusCode == 404) {
error(command, "API not found: " + apiName);
}
} catch (IllegalArgumentException e) {
error(command, "Version not found: " + apiVersion);
}
return api;
}
private static void discover(String[] args) throws IOException {
System.out.println(APP_NAME);
// load discovery doc
if (args.length == 1) {
error("discover", "missing api name");
}
if (args.length == 2) {
error("discover", "missing api version");
}
String apiName = args[1];
String apiVersion = args[2];
System.out.println();
System.out.println("API Name: " + apiName);
System.out.println("API Version: " + apiVersion);
System.out.println();
System.out.println("Methods:");
GoogleApi api = loadGoogleAPI("discover", apiName, apiVersion);
// compute method details
ArrayList<MethodDetails> result = Lists.newArrayList();
Map<String, ServiceResource> resources = api.serviceDefinition.resources;
if (resources != null) {
// iterate over resources
for (Map.Entry<String, ServiceResource> resourceEntry : resources.entrySet()) {
String resourceName = resourceEntry.getKey();
ServiceResource resource = resourceEntry.getValue();
// iterate over methods
Map<String, ServiceMethod> methods = resource.methods;
if (methods != null) {
for (Map.Entry<String, ServiceMethod> methodEntry : methods.entrySet()) {
ServiceMethod method = methodEntry.getValue();
MethodDetails details = new MethodDetails();
details.name = resourceName + "." + methodEntry.getKey();
details.hasContent =
!method.httpMethod.equals("GET") && !method.httpMethod.equals("DELETE");
// required parameters
for (String param : getRequiredParameters(method).keySet()) {
details.requiredParameters.add(param);
}
// optional parameters
Map<String, ServiceParameter> parameters = method.parameters;
if (parameters != null) {
for (Map.Entry<String, ServiceParameter> parameterEntry : parameters.entrySet()) {
String parameterName = parameterEntry.getKey();
ServiceParameter parameter = parameterEntry.getValue();
if (!parameter.required) {
details.optionalParameters.add(parameterName);
}
}
}
result.add(details);
}
}
}
}
Collections.sort(result);
// display method details
for (MethodDetails methodDetail : result) {
System.out.println();
System.out.print("google call " + apiName + " " + apiVersion + " " + methodDetail.name);
for (String param : methodDetail.requiredParameters) {
System.out.print(" <" + param + ">");
}
if (methodDetail.hasContent) {
System.out.print(" contentFile");
}
if (methodDetail.optionalParameters.isEmpty() && !methodDetail.hasContent) {
System.out.println();
} else {
System.out.println(" [optional parameters...]");
System.out.println(" --contentType <value> (default is \"application/json\")");
for (String param : methodDetail.optionalParameters) {
System.out.println(" --" + param + " <value>");
}
}
}
}
static LinkedHashMap<String, ServiceParameter> getRequiredParameters(ServiceMethod method) {
ArrayList<String> requiredParams = Lists.newArrayList();
int cur = 0;
String pathUrl = method.pathUrl;
int length = pathUrl.length();
while (cur < length) {
int next = pathUrl.indexOf('{', cur);
if (next == -1) {
break;
}
int close = pathUrl.indexOf('}', next + 2);
String paramName = pathUrl.substring(next + 1, close);
requiredParams.add(paramName);
cur = close + 1;
}
Map<String, ServiceParameter> parameters = method.parameters;
if (parameters != null) {
SortedSet<String> nonPathRequiredParameters = Sets.newTreeSet();
for (Map.Entry<String, ServiceParameter> parameterEntry : parameters.entrySet()) {
String parameterName = parameterEntry.getKey();
ServiceParameter parameter = parameterEntry.getValue();
if (parameter.required && !requiredParams.contains(parameterName)) {
nonPathRequiredParameters.add(parameterName);
}
}
requiredParams.addAll(nonPathRequiredParameters);
}
LinkedHashMap<String, ServiceParameter> result = Maps.newLinkedHashMap();
for (String paramName : requiredParams) {
result.put(paramName, method.parameters.get(paramName));
}
return result;
}
}
| Java |
// Copyright 2011 Google Inc. All Rights Reserved.
package com.google.api.client.sample.buzz.appengine.oauth2;
import com.google.api.client.extensions.appengine.auth.AbstractAppEngineCallbackServlet;
import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow;
import com.google.api.client.googleapis.extensions.auth.helpers.oauth2.draft10.GoogleOAuth2ThreeLeggedFlow;
import javax.jdo.PersistenceManagerFactory;
/**
* This is the callback that handles completion requests from the token server.
* It is currently set up for the proper values for OAuth2 Draft 10.
*
* @author moshenko@google.com (Jacob Moshenko)
*
*/
public class AppEngineFlowOAuth2Callback extends AbstractAppEngineCallbackServlet {
@Override
protected Class<? extends ThreeLeggedFlow> getConcreteFlowType() {
return GoogleOAuth2ThreeLeggedFlow.class;
}
@Override
protected String getCompletionCodeQueryParam() {
return "code";
}
@Override
protected String getDeniedRedirectUrl() {
return "/denied";
}
@Override
protected String getSuccessRedirectUrl() {
return "/";
}
@Override
protected PersistenceManagerFactory getPersistenceManagerFactory() {
return PMF.get();
}
}
| Java |
// Copyright 2011 Google Inc. All Rights Reserved.
package com.google.api.client.sample.buzz.appengine.oauth2;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;
/**
* Singleton to manage an instance of a {@link PersistenceManagerFactory}.
*
* One must use a singleton or other dependency injection to manage a single
* instance of a {@link PersistenceManagerFactory} because creation of the
* {@link PersistenceManagerFactory} is very expensive.
*
* @author moshenko@google.com (Jacob Moshenko)
*
*/
public final class PMF {
private static final PersistenceManagerFactory pmfInstance =
JDOHelper.getPersistenceManagerFactory("transactions-optional");
private PMF() {
}
public static PersistenceManagerFactory get() {
return pmfInstance;
}
}
| Java |
// Copyright 2011 Google Inc. All Rights Reserved.
package com.google.api.client.sample.buzz.appengine.oauth2;
import com.google.api.client.extensions.appengine.auth.AbstractAppEngineFlowServlet;
import com.google.api.client.extensions.auth.helpers.Credential;
import com.google.api.client.extensions.auth.helpers.ThreeLeggedFlow;
import com.google.api.client.extensions.servlet.auth.AbstractFlowUserServlet;
import com.google.api.client.googleapis.extensions.auth.helpers.oauth2.draft10.GoogleOAuth2ThreeLeggedFlow;
import com.google.api.services.buzz.v1.Buzz;
import com.google.api.services.buzz.v1.model.Activity;
import com.google.api.services.buzz.v1.model.ActivityFeed;
import java.io.IOException;
import java.io.PrintWriter;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This is the main entry point for the example. It uses the
* {@link AbstractFlowUserServlet} to require an authorized session for the
* current user prior to invoking the {@link
* #doGetWithCredentials(HttpServletRequest, HttpServletResponse, Credential)}
* method.
*
* @author moshenko@google.com (Jacob Moshenko)
*
*/
public class SampleApp extends AbstractAppEngineFlowServlet {
@Override
protected ThreeLeggedFlow newFlow(String userId) {
return new GoogleOAuth2ThreeLeggedFlow(userId,
OAuth2ClientCredentials.CLIENT_ID,
OAuth2ClientCredentials.CLIENT_SECRET,
OAuth2ClientCredentials.SCOPE,
"http://localhost:8888/oauth2callback");
}
@Override
protected void doGetWithCredentials(
HttpServletRequest req, HttpServletResponse resp, Credential credential) throws IOException {
// List activities using the generated client
Buzz buzz = new Buzz(getHttpTransport(), credential, getJsonFactory());
ActivityFeed activities = buzz.activities.list("me", "@self").execute();
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
writer.println("Activities:");
for (Activity oneAct : activities.items) {
writer.println(oneAct.title);
}
}
@Override
protected PersistenceManagerFactory getPersistenceManagerFactory() {
return PMF.get();
}
}
| Java |
// Copyright 2011 Google Inc. All Rights Reserved.
package com.google.api.client.sample.buzz.appengine.oauth2;
import com.google.appengine.api.users.User;
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;
/**
* @author moshenko@google.com (Jacob Moshenko)
*
*/
public class DeniedAuth extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
UserService userService = UserServiceFactory.getUserService();
User loggedIn = userService.getCurrentUser();
resp.getWriter().print("<h3>" + loggedIn.getNickname()
+ ", why don't you want to play with me?</h1>");
resp.setStatus(200);
resp.addHeader("Content-Type", "text/html");
}
}
| Java |
// Copyright 2011 Google Inc. All Rights Reserved.
package com.google.api.client.sample.buzz.appengine.oauth2;
/**
* OAuth 2 credentials found in the <a href="https://code.google.com/apis/console">Google apis
* console</a>.
*
* <p>
* Once at the Google apis console, click on "Add project...", or if you've already set up a
* project, click the arrow next to the project name and click on "Create..." under "Other
* projects". For "Buzz API", click on the status switch to flip it to "ON", and agree to the terms
* of service. Next, click on "API Access". Click on "Create an OAuth 2.0 Client ID...". Select a
* product name and click "Next". Make sure you select "Installed application" and click "Create
* client ID".
* </p>
*
* @author Yaniv Inbar
*/
class OAuth2ClientCredentials {
/** Value of the "Client ID" shown under "Client ID for installed applications". */
static final String CLIENT_ID = "28040055140.apps.googleusercontent.com";
/** Value of the "Client secret" shown under "Client ID for installed applications". */
static final String CLIENT_SECRET = "vc1yjuXxCeELm+T+o6y+nL0F";
/** OAuth 2 scope to use (may also append {@code ".readonly"} for the read-only scope). */
static final String SCOPE = "https://www.googleapis.com/auth/buzz";
} | 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.verification;
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.verification;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.javanet.NetHttpTransport;
import com.google.api.client.json.Json;
import com.google.api.client.json.JsonHttpParser;
import com.google.api.client.sample.verification.model.Debug;
import com.google.api.client.sample.verification.model.WebResource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
/**
* @author Kevin Marshall
*/
public class VerificationSample {
static final String APP_DESCRIPTION =
"Site Verification API Java Client Sample";
static final String META_VERIFICATION_METHOD = "meta";
static final String SITE_TYPE = "site";
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Debug.enableLogging();
HttpTransport.setLowLevelHttpTransport(NetHttpTransport.INSTANCE);
HttpTransport transport = setUpTransport();
try {
try {
System.out.println("Getting an OAuth access token. " +
"Please follow the prompts on the browser window.");
Auth.authorize(transport);
System.out.println(
"This is an sample Java-based client for the Google Site " +
"Verification API.\n" +
"Your data may be modified as a result of running " +
"this demonstration.\n" +
"We recommend that you run this sample with a test account\n" +
"to avoid any accidental losses of data. Use at your own risk." +
"\n\n");
System.out.println("Enter the URL of a site to be verified:");
String siteUrl = in.readLine();
// Example of a getToken call.
// https://code.google.com/apis/siteverification/v1/reference.html#method_siteVerification_webResource_getToken
String token = WebResource.getToken(transport, siteUrl, SITE_TYPE,
META_VERIFICATION_METHOD);
System.out.println("Place this META tag on your site:\n\t" + token +
"\nWhen you are finished, press ENTER to proceed with " +
"verification.");
in.readLine();
// Example of an Insert call.
// https://code.google.com/apis/siteverification/v1/reference.html#method_siteVerification_webResource_insert
WebResource verifiedSite = new WebResource();
verifiedSite.site.identifier = siteUrl;
verifiedSite.site.type = "site";
verifiedSite = verifiedSite.executeInsert(transport, "meta");
System.out.println("Verification successful.");
// Example of an Update call.
// https://code.google.com/apis/siteverification/v1/reference.html#method_siteVerification_webResource_update
System.out.println(
"Congratulations, you're now a verified owner of this site!\n" +
"Do you also want to delegate ownership to another individual? (y/n)");
String delegatedOwner = null;
if (in.readLine().startsWith("y")) {
System.out.println("Enter the email address of a new co-owner: ");
delegatedOwner = in.readLine();
verifiedSite.owners.add(delegatedOwner);
verifiedSite = verifiedSite.executeUpdate(transport);
System.out.println("Delegation successful.");
}
System.out.println("\n\nHere are all of the sites you own:");
showVerifiedSites(transport);
// Example of Delete call.
// https://code.google.com/apis/siteverification/v1/reference.html#method_siteVerification_webResource_delete
System.out.println(
"\n\nLet's clean up. Do you want to unverify the site that " +
"you have just verified? (y/n)\n" +
"Remember that you will need to remove your token prior to unverification.");
if (in.readLine().startsWith("y")) {
try {
if (delegatedOwner != null) {
// Another example of an Update call.
System.out.print(
"Undelegating co-owner prior to unverifying yourself... ");
verifiedSite.owners.remove(delegatedOwner);
verifiedSite = verifiedSite.executeUpdate(transport);
System.out.println("done.");
}
System.out.print("Unverifying your site... ");
verifiedSite.executeDelete(transport);
System.out.println("done.");
} catch (HttpResponseException hre) {
if (hre.response.statusCode == 400) {
System.err.println("Unverification failed, because " +
"you have not yet removed your verification tokens from the site.");
}
}
}
Auth.revoke();
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
throw e;
}
} catch (Throwable t) {
t.printStackTrace();
Auth.revoke();
System.exit(1);
}
System.out.println("All done. Quitting.");
}
private static HttpTransport setUpTransport() {
HttpTransport transport = GoogleTransport.create();
GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders;
headers.setApplicationName("Google-VerificationSample/1.0");
transport.addParser(new JsonHttpParser());
return transport;
}
private static void showVerifiedSites(HttpTransport transport)
throws IOException {
List<WebResource> resources = WebResource.executeList(transport);
if (!resources.isEmpty()) {
for (WebResource nextResource : resources) {
System.out.println("\t" + Json.toString(nextResource));
}
} else {
System.out.println("You do not have any verified sites yet!");
}
}
}
| 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.verification;
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 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 = ClientCredentials.ENTER_CLIENT_SHARED_SECRET;
temporaryToken.signer = signer;
temporaryToken.consumerKey = ClientCredentials.ENTER_DOMAIN;
temporaryToken.scope = "https://www.googleapis.com/auth/siteverification";
temporaryToken.displayName = VerificationSample.APP_DESCRIPTION;
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.verification;
/**
* @author Kevin Marshall
*/
public class ClientCredentials {
// Set the value of this to the key provided to you by the Google APIs Console.
// https://code.google.com/apis/console/
// The API uses a small unregistered request quota if set to null.
public static final String ENTER_API_KEY = null;
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.verification.model;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Kevin Marshall
*
*/
public class WebResource extends GenericJson {
@Key
public String id;
@Key
public List<String> owners = new ArrayList<String>();
@Key
public WebResourceSite site = new WebResourceSite();
public static List<WebResource> executeList(HttpTransport transport)
throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = VerificationUrl.forWebResource();
return request.execute().parseAs(WebResourceList.class).items;
}
public WebResource executeGet(HttpTransport transport)
throws IOException {
HttpRequest request = transport.buildGetRequest();
request.url = VerificationUrl.forWebResource(id);
return request.execute().parseAs(WebResource.class);
}
public WebResource executeInsert(HttpTransport transport,
String verificationMethod) throws IOException {
HttpRequest request = transport.buildPostRequest();
setContent(request, this);
request.url = VerificationUrl.forInsertedWebResource(verificationMethod);
return request.execute().parseAs(WebResource.class);
}
public void executeDelete(HttpTransport transport) throws IOException {
HttpRequest request = transport.buildDeleteRequest();
request.url = VerificationUrl.forWebResource(id);
request.execute().ignore();
}
public WebResource executeUpdate(HttpTransport transport)
throws IOException {
HttpRequest request = transport.buildPutRequest();
setContent(request, this);
request.url = VerificationUrl.forWebResource(id);
return request.execute().parseAs(WebResource.class);
}
public static String getToken(HttpTransport transport, String url,
String type, String verificationMethod) throws IOException {
TokenRequest tokRequest = new TokenRequest();
tokRequest.site.identifier = url;
tokRequest.site.type = type;
tokRequest.verificationMethod = verificationMethod;
HttpRequest request = transport.buildPostRequest();
request.url = VerificationUrl.forToken();
setContent(request, tokRequest);
return request.execute().parseAs(TokenResponse.class).token;
}
private static void setContent(HttpRequest request, Object obj) {
JsonHttpContent content = new JsonHttpContent();
content.data = obj;
request.content = content;
}
}
| Java |
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.api.client.sample.verification.model;
import com.google.api.client.util.Key;
/**
* @author Kevin Marshall
*
*/
public class TokenResponse {
@Key
public String method;
@Key
public String token;
}
| 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.verification.model;
import com.google.api.client.googleapis.GoogleUrl;
import com.google.api.client.sample.verification.ClientCredentials;
import com.google.api.client.util.Key;
/**
* Latitude URL builder.
*
* @author Kevin Marshall
*/
public final class VerificationUrl extends GoogleUrl {
@Key
public String key = ClientCredentials.ENTER_API_KEY;
@Key
public String verificationMethod;
@Key
public String granularity;
@Key("min-time")
public String minTime;
@Key("max-time")
public String maxTime;
@Key("max-results")
public String maxResults;
/** Constructs a new Site Verification URL from the given encoded URI. */
public VerificationUrl(String encodedUrl) {
super(encodedUrl);
if (Debug.ENABLED) {
prettyprint = true;
}
}
private static VerificationUrl root() {
return new VerificationUrl(
"https://www.googleapis.com/siteVerification/v1");
}
public static VerificationUrl forWebResource() {
VerificationUrl result = root();
result.pathParts.add("webResource");
return result;
}
public static VerificationUrl forInsertedWebResource(
String verificationMethod) {
VerificationUrl result = forWebResource();
result.verificationMethod = verificationMethod;
return result;
}
public static VerificationUrl forWebResource(String resourceId) {
VerificationUrl result = forWebResource();
result.setRawPath(result.getRawPath() + "/" + resourceId);
return result;
}
public static VerificationUrl forToken() {
VerificationUrl result = root();
result.pathParts.add("token");
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.verification.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.verification.model;
import com.google.api.client.util.Key;
/**
* @author Kevin Marshall
*/
public class WebResourceSite {
@Key
public String identifier;
@Key
public String type;
}
| Java |
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.api.client.sample.verification.model;
import com.google.api.client.util.Key;
/**
* @author Kevin Marshall
*
*/
public class TokenRequest {
@Key
public String verificationMethod;
@Key
public WebResourceSite site = new WebResourceSite();
}
| 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.verification.model;
import com.google.api.client.util.Key;
import java.util.ArrayList;
import java.util.List;
/**
* @author Kevin Marshall
*
*/
public class WebResourceList {
@Key
public List<WebResource> items = new ArrayList<WebResource>();
}
| 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.latitude;
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;
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.