code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
/** 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 |
package ddn.anjuto.services;
import ddn.dao.hibernate.pojo.UserProfile;
public interface IUserService {
public void registerUser(UserProfile up) throws Exception;
}
| Java |
package ddn.anjuto.services;
import javax.annotation.Resource;
import ddn.dao.UserProfileDAO;
import ddn.dao.hibernate.pojo.UserProfile;
public class UserServiceImpl implements IUserService {
private UserProfileDAO userProfileDAO;
public UserProfileDAO getUserProfileDAO() {
return userProfileDAO;
}
@Resource(name = "userProfileDAO")
public void setUserProfileDAO(UserProfileDAO userProfileDAO) {
this.userProfileDAO = userProfileDAO;
}
@Override
public void registerUser(UserProfile up) throws Exception {
userProfileDAO.save(up);
}
}
| Java |
package ddn.anjuto.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@WebServlet(value = "/anjuto", loadOnStartup = 1)
public class RegisterController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected final Log log = LogFactory.getLog(this.getClass().getName());
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String jsonRequest = req.getParameter("jsonRequest");
log.debug("Peticion: " + jsonRequest);
}
}
| Java |
package ddn.dao.hibernate;
import java.sql.Timestamp;
import java.util.List;
import org.hibernate.criterion.Restrictions;
import ddn.dao.UserProfileDAO;
import ddn.dao.hibernate.generic.AbstractHibernateDAO;
import ddn.dao.hibernate.pojo.UserProfile;
/**
* <p>Hibernate DAO layer for UserProfiles</p>
* <p>Generated at Mon May 07 17:59:06 CEST 2012</p>
*
* @author Salto-db Generator v1.0.16 / EJB3 + Spring/Hibernate DAO
* @see http://www.hibernate.org/328.html
*/
public class UserProfileHibernateDAO extends
AbstractHibernateDAO<UserProfile, Integer> implements
UserProfileDAO {
/**
* Find UserProfile by login
*/
public List<UserProfile> findByLogin(String login) {
return findByCriteria(Restrictions.eq("login", login));
}
/**
* Find UserProfile by passwd
*/
public List<UserProfile> findByPasswd(String passwd) {
return findByCriteria(Restrictions.eq("passwd", passwd));
}
/**
* Find UserProfile by name
*/
public List<UserProfile> findByName(String name) {
return findByCriteria(Restrictions.eq("name", name));
}
/**
* Find UserProfile by birthday
*/
public List<UserProfile> findByBirthday(Timestamp birthday) {
return findByCriteria(Restrictions.eq("birthday", birthday));
}
/**
* Find UserProfile by gender
*/
public List<UserProfile> findByGender(String gender) {
return findByCriteria(Restrictions.eq("gender", gender));
}
}
| Java |
package ddn.dao.hibernate.pojo;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* <p>
* Pojo mapping TABLE user_profile
* </p>
* <p>
* </p>
*
* <p>
* Generated at Mon May 07 17:59:06 CEST 2012
* </p>
*
* @author Salto-db Generator v1.0.16 / EJB3
*
*/
@Entity
@Table(name = "user_profile", catalog = "anjuto")
@SuppressWarnings("serial")
public class UserProfile implements Serializable {
public UserProfile(int id, String login, String passwd, String name,
Timestamp birthday, String gender) {
this.birthday = birthday;
this.id = id;
this.login = login;
this.name = name;
this.passwd = passwd;
this.gender = gender;
}
/**
* Attribute id.
*/
private Integer id;
/**
* Attribute login.
*/
private String login;
/**
* Attribute passwd.
*/
private String passwd;
/**
* Attribute name.
*/
private String name;
/**
* Attribute birthday.
*/
private Timestamp birthday;
/**
* Attribute gender.
*/
private String gender;
/**
* <p>
* </p>
*
* @return id
*/
@Basic
@Id
@Column(name = "id")
public Integer getId() {
return id;
}
/**
* @param id
* new value for id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* <p>
* </p>
*
* @return login
*/
@Basic
@Column(name = "login", length = 45)
public String getLogin() {
return login;
}
/**
* @param login
* new value for login
*/
public void setLogin(String login) {
this.login = login;
}
/**
* <p>
* </p>
*
* @return passwd
*/
@Basic
@Column(name = "passwd", length = 45)
public String getPasswd() {
return passwd;
}
/**
* @param passwd
* new value for passwd
*/
public void setPasswd(String passwd) {
this.passwd = passwd;
}
/**
* <p>
* </p>
*
* @return name
*/
@Basic
@Column(name = "name", length = 45)
public String getName() {
return name;
}
/**
* @param name
* new value for name
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* </p>
*
* @return birthday
*/
@Basic
@Column(name = "birthday")
public Timestamp getBirthday() {
return birthday;
}
/**
* @param birthday
* new value for birthday
*/
public void setBirthday(Timestamp birthday) {
this.birthday = birthday;
}
/**
* <p>
* </p>
*
* @return gender
*/
@Basic
@Column(name = "gender", length = 45)
public String getGender() {
return gender;
}
/**
* @param gender
* new value for gender
*/
public void setGender(String gender) {
this.gender = gender;
}
} | Java |
package ddn.dao.hibernate.generic;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* Generated at Mon May 10 12:58:06 CEST 2010
*
* @author Salto-db Generator v1.0.16 / EJB3 + Spring/Hibernate DAO + TestCases
* @see http://www.hibernate.org/328.html
*/
public interface GenericDAO<T, ID extends Serializable> {
T getById(ID id, boolean lock);
T getById(ID id);
T loadById(ID id);
List<T> findAll();
List<T> findByCriteria(Map criterias);
public List<T> findByExample(T exampleInstance, String[] excludeProperty);
void save(T entity);
void update(T entity);
void saveOrUpdate(T entity);
void delete(T entity);
void deleteById(ID id);
} | Java |
package ddn.dao.hibernate.generic;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;
/**
* Generated at Mon May 10 12:58:06 CEST 2010
*
* @author Salto-db Generator v1.0.16 / EJB3 + Spring/Hibernate DAO + TestCases
* @see http://www.hibernate.org/328.html
*/
public abstract class AbstractHibernateDAO<T, ID extends Serializable> extends HibernateDaoSupport implements GenericDAO<T, ID> {
protected final Log log = LogFactory.getLog(this.getClass().getName());
private Class<T> persistentClass;
public AbstractHibernateDAO() {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public Class<T> getPersistentClass() {
return persistentClass;
}
@SuppressWarnings("unchecked")
public T getById(ID id) {
return (T) getSession().get(getPersistentClass(), id);
}
@SuppressWarnings("unchecked")
public T getById(ID id, boolean lock) {
if (lock) {
return (T) getSession().get(getPersistentClass(), id,
LockMode.UPGRADE);
} else
return getById(id);
}
@SuppressWarnings("unchecked")
public T loadById(ID id) {
return (T) getSession().load(getPersistentClass(), id);
}
@Transactional
public void save(T entity) {
log.info("Enters save");
if (entity instanceof UpdatablePojo){
UpdatablePojo o = (UpdatablePojo)entity;
Timestamp t = new Timestamp(System.currentTimeMillis());
o.setCreationDate(t);
o.setUpdateDate(t);
}
this.getSession(true).save(entity);
}
@Transactional
public void update(T entity) {
//getSession().update(entity);
if (entity instanceof UpdatablePojo){
UpdatablePojo o = (UpdatablePojo)entity;
o.setUpdateDate(new Timestamp(System.currentTimeMillis()));
}
this.getHibernateTemplate().update(entity);
}
@Transactional
public void saveOrUpdate(T entity) {
if (entity instanceof UpdatablePojo){
UpdatablePojo o = (UpdatablePojo)entity;
Timestamp t = new Timestamp(System.currentTimeMillis());
if (o.getCreationDate()==null){
o.setCreationDate(t);
}
o.setUpdateDate(t);
}
getSession(true).saveOrUpdate(entity);
}
@Transactional
public void delete(T entity) {
//getSession().delete(entity);
this.getHibernateTemplate().delete(entity);
}
@Transactional
public void deleteById(ID id) {
//getSession().delete(loadById(id));
this.getHibernateTemplate().delete(loadById(id));
}
@SuppressWarnings("unchecked")
public List<T> findAll() {
return findByCriteria();
}
/**
* Use this inside subclasses as a convenience method.
*/
@SuppressWarnings("unchecked")
protected List<T> findByCriteria(Criterion... criterion) {
Criteria crit = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion) {
if(c != null){
crit.add(c);
}
}
return crit.list();
}
/**
*
* Filter and order
*/
@SuppressWarnings("unchecked")
protected List<T> findByCriteria(String order, String orderField,Criterion... criterion) {
Criteria crit = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion) {
if(c != null){
crit.add(c);
}
}
if(order.equals("asc")){
crit.addOrder(Order.asc(orderField));
}else{
if (order.equals("desc")){
crit.addOrder(Order.desc(orderField));
}
}
return crit.list();
}
/**
*
* Filter and limited
*/
@SuppressWarnings("unchecked")
protected List<T> findByCriteria(Integer count,String orderField,Criterion... criterion) {
Criteria crit = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion) {
if(c != null){
crit.add(c);
}
}
crit.setMaxResults(count);
if (!orderField.equals("")){
crit.addOrder(Order.desc(orderField));
}
return crit.list();
}
/**
* Find by criteria.
*/
@SuppressWarnings("unchecked")
public List<T> findByCriteria(Map criterias) {
Criteria criteria = getSession().createCriteria(getPersistentClass());
criteria.add(Restrictions.allEq(criterias));
return criteria.list();
}
/**
* This method will execute an HQL query and return the number of affected entities.
*/
protected int executeQuery(String query, String namedParams[], Object params[]) {
Query q = getSessionFactory().openSession().createQuery(query);
//Query q = getSession().createQuery(query);
if (namedParams != null) {
for (int i = 0; i < namedParams.length; i++) {
q.setParameter(namedParams[i], params[i]);
}
}
return q.executeUpdate();
}
protected int executeQuery(String query) {
return executeQuery(query, null, null);
}
/**
* This method will execute a Named HQL query and return the number of affected entities.
*/
protected int executeNamedQuery(String namedQuery, String namedParams[], Object params[]) {
Query q = getSession().getNamedQuery(namedQuery);
if (namedParams != null) {
for (int i = 0; i < namedParams.length; i++) {
q.setParameter(namedParams[i], params[i]);
}
}
return q.executeUpdate();
}
protected int executeNamedQuery(String namedQuery) {
return executeNamedQuery(namedQuery, null, null);
}
@SuppressWarnings("unchecked")
public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
Criteria crit = getSession().createCriteria(getPersistentClass());
Example example = Example.create(exampleInstance).excludeZeroes().enableLike().ignoreCase();
for (String exclude : excludeProperty) {
example.excludeProperty(exclude);
}
crit.add(example);
return crit.list();
}
public List<T> findByCriteriaDisjunction(Disjunction disjunction){
Criteria crit = getSession().createCriteria(getPersistentClass());
crit.add(disjunction);
return crit.list();
}
}
| Java |
package ddn.dao.hibernate.generic;
import java.sql.Timestamp;
public interface UpdatablePojo {
public void setUpdateDate(Timestamp updateDate);
public void setCreationDate(Timestamp creationDate) ;
public Timestamp getCreationDate();
}
| Java |
package ddn.dao;
import java.sql.Timestamp;
import java.util.List;
import ddn.dao.hibernate.generic.GenericDAO;
import ddn.dao.hibernate.pojo.UserProfile;
/**
* <p>Generic DAO layer for UserProfiles</p>
* <p>Generated at Mon May 07 17:59:06 CEST 2012</p>
*
* @author Salto-db Generator v1.0.16 / EJB3 + Spring/Hibernate DAO
* @see http://www.hibernate.org/328.html
*/
public interface UserProfileDAO extends GenericDAO<UserProfile,Integer> {
/*
* TODO : Add specific businesses daos here.
* These methods will be overwrited if you re-generate this interface.
* You might want to extend this interface and to change the dao factory to return
* an instance of the new implemenation in buildUserProfileDAO()
*/
/**
* Find UserProfile by login
*/
public List<UserProfile> findByLogin(String login);
/**
* Find UserProfile by passwd
*/
public List<UserProfile> findByPasswd(String passwd);
/**
* Find UserProfile by name
*/
public List<UserProfile> findByName(String name);
/**
* Find UserProfile by birthday
*/
public List<UserProfile> findByBirthday(Timestamp birthday);
/**
* Find UserProfile by gender
*/
public List<UserProfile> findByGender(String gender);
} | Java |
import javax.xml.ws.Provider;
import javax.xml.ws.Service;
import javax.xml.ws.ServiceMode;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.WebServiceProvider;
import javax.xml.ws.handler.MessageContext;
@SuppressWarnings("unchecked")
@WebServiceProvider
@ServiceMode(value = Service.Mode.PAYLOAD)
public class GenericController<T> implements Provider<T> {
protected WebServiceContext wsContext;
private String SUCCESS = "success";
@Override
public T invoke(T request) {
MessageContext mc = wsContext.getMessageContext();
String path = (String) mc.get(MessageContext.PATH_INFO);
String method = (String) mc.get(MessageContext.HTTP_REQUEST_METHOD);
if (method.equals("GET"))
return get(mc);
if (method.equals("POST"))
return post(request, mc);
if (method.equals("PUT"))
return put(request, mc);
if (method.equals("DELETE"))
return delete(request, mc);
else
return null;
}
// Other methods not shown here
public T get(MessageContext mc) {
return (T) SUCCESS;
}
public T post(T request, MessageContext mc) {
return (T) SUCCESS;
}
public T put(T request, MessageContext mc) {
return (T) SUCCESS;
}
public T delete(T request, MessageContext mc) {
return (T) SUCCESS;
}
}
| Java |
package com.alfresco.cloud.example;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.jpeg.JpegParser;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.HttpRequestFactory;
/**
* Shows how to add an aspect to a document. In this case, we're
* using cm:geographic to store the latitude and longitude that is
* set on some jpeg images in a folder.
*
* @author jpotts
*
*/
public class CmisAspectExample extends BaseJavaExample {
public static final String FOLDER_NAME = "images";
public static final String FILE_PATH = "/users/jpotts/Documents/sample/photos/Portland";
public static final String FILE_TYPE = "image/jpeg";
/**
* @param args
*/
public static void main(String[] args) {
CmisAspectExample ccde = new CmisAspectExample();
try {
ccde.run();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doExample(HttpRequestFactory requestFactory, Credential credential)
throws IOException {
// Get the accessToken
String accessToken = credential.getAccessToken();
// Get a CMIS session
Session cmisSession = getCmisSession(accessToken);
// Find the root folder of our target site
String rootFolderId = getRootFolderId(requestFactory, HOME_NETWORK, SITE);
// Create a new folder in the root folder
Folder subFolder = createFolder(cmisSession, rootFolderId, FOLDER_NAME);
File dir = new File(FILE_PATH);
if (!dir.exists() || !dir.isDirectory()) {
System.out.println("Bad path specified: " + dir.getPath());
return;
}
File[] fileList = dir.listFiles();
for (File file : fileList) {
// set up the properties map
Map<String, Object> props = getProperties(file);
// if we couldn't get the props for some reason, just
// move on to the next one
if (props.isEmpty()) {
continue;
}
// create the document in the repo
createDocument(getCmisSession(accessToken), subFolder, file, FILE_TYPE, props);
}
}
/**
* Use the CMIS API to get a handle to the root folder of the
* target site, then create a new folder, then create
* a new document in the new folder
* @param cmisSession
* @param parentFolderId
* @param folderName
* @return Folder
*/
public Folder createFolder(Session cmisSession, String parentFolderId, String folderName) {
Folder rootFolder = (Folder) cmisSession.getObject(parentFolderId);
Folder subFolder = null;
try {
// Making an assumption here that you probably wouldn't normally do
subFolder = (Folder) cmisSession.getObjectByPath(rootFolder.getPath() + "/" + folderName);
System.out.println("Folder already existed!");
} catch (CmisObjectNotFoundException onfe) {
Map<String, Object> props = new HashMap<String, Object>();
props.put("cmis:objectTypeId", "cmis:folder");
props.put("cmis:name", folderName);
subFolder = rootFolder.createFolder(props);
String subFolderId = subFolder.getId();
System.out.println("Created new folder: " + subFolderId);
}
return subFolder;
}
/**
* Use Apache Tika to read the latitude and longitude from the
* jpegs.
*
* @param file
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public Map<String, Object> getProperties(File file)
throws FileNotFoundException, IOException {
Map<String, Object> props = new HashMap<String, Object>();
//Tika tika = new Tika();
String fileName = file.getName();
System.out.println("File: " + fileName);
InputStream stream = new FileInputStream(file);
try {
Metadata metadata = new Metadata();
ContentHandler handler = new DefaultHandler();
Parser parser = new JpegParser();
ParseContext context = new ParseContext();
//String mimeType = tika.detect(stream); // broken for my jpegs
String mimeType = "image/jpeg";
metadata.set(Metadata.CONTENT_TYPE, mimeType);
parser.parse(stream, handler, metadata, context);
String lat = metadata.get("geo:lat");
String lon = metadata.get("geo:long");
stream.close();
// create a map of properties
props.put("cmis:objectTypeId", "cmis:document,P:cm:geographic");
props.put("cmis:name", fileName);
if (lat != null && lon != null) {
System.out.println("LAT:" + lat);
System.out.println("LON:" + lon);
props.put("cm:latitude", lat);
props.put("cm:longitude", lon);
}
} catch (TikaException te) {
System.out.println("Caught tika exception, skipping");
} catch (SAXException se) {
System.out.println("Caught SAXException, skipping");
} finally {
if (stream != null) {
stream.close();
}
}
return props;
}
}
| Java |
package com.alfresco.cloud.example.model;
import com.google.api.client.util.Key;
/**
* @author jpotts
*/
public class Network {
@Key
public String id;
@Key
public boolean homeNetwork;
//@Key
//DateTime createdAt;
@Key
public boolean paidNetwork;
@Key
public boolean isEnabled;
@Key
public String subscriptionLevel;
}
| Java |
package com.alfresco.cloud.example.model;
/**
* @author jpotts
*/
public class Entry {
}
| Java |
package com.alfresco.cloud.example.model;
import com.google.api.client.util.Key;
/**
* @author jpotts
*/
public class SiteList {
@Key
public List<SiteEntry> list;
}
| Java |
package com.alfresco.cloud.example.model;
import com.google.api.client.util.Key;
/**
* @author jpotts
*/
public class SiteEntry extends Entry {
@Key
public Site entry;
}
| Java |
package com.alfresco.cloud.example.model;
import java.util.ArrayList;
import com.google.api.client.util.Key;
/**
* @author jpotts
*/
public class List<T extends Entry> {
@Key
public ArrayList<T> entries;
@Key
public Pagination pagination;
}
| Java |
package com.alfresco.cloud.example.model;
import com.google.api.client.util.Key;
/**
* @author jpotts
*/
public class Container {
@Key
public String id;
@Key
public String folderId;
}
| Java |
package com.alfresco.cloud.example.model;
import com.google.api.client.util.Key;
/**
* @author jpotts
*/
public class NetworkList {
@Key
public List<NetworkEntry> list;
}
| Java |
package com.alfresco.cloud.example.model;
import com.google.api.client.util.Key;
/**
* @author jpotts
*/
public class Pagination {
@Key
public int count;
@Key
public boolean hasMoreItems;
@Key
public int totalItems;
@Key
public int skipCount;
@Key
public int maxItems;
}
| Java |
package com.alfresco.cloud.example.model;
import com.google.api.client.util.Key;
/**
* @author jpotts
*/
public class NetworkEntry extends Entry {
@Key
public Network entry;
}
| Java |
package com.alfresco.cloud.example.model;
import com.google.api.client.util.Key;
/**
* @author jpotts
*/
public class ContainerList {
@Key
public List<ContainerEntry> list;
}
| Java |
package com.alfresco.cloud.example.model;
import com.google.api.client.util.Key;
/**
* @author jpotts
*/
public class Site {
@Key
public String id;
@Key
public String title;
@Key
public String visibility;
@Key
public String description;
}
| Java |
package com.alfresco.cloud.example.model;
import com.google.api.client.util.Key;
/**
* @author jpotts
*/
public class ContainerEntry extends Entry {
@Key
public Container entry;
}
| Java |
package com.alfresco.cloud.example;
import java.io.IOException;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.commons.data.RepositoryInfo;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.HttpRequestFactory;
/**
* Simple example that shows how to connect to the Alfresco Cloud
* and retrieve repository information.
*
* @author jpotts
*
*/
public class CmisRepositoryInfoExample extends BaseJavaExample {
public static void main(String[] args) {
CmisRepositoryInfoExample crie = new CmisRepositoryInfoExample();
try {
crie.run();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doExample(HttpRequestFactory requestFactory, Credential credential)
throws IOException {
// Get the accessToken
String accessToken = credential.getAccessToken();
// Get a CMIS session
Session cmisSession = getCmisSession(accessToken);
// Get the repository info
RepositoryInfo repositoryInfo = cmisSession.getRepositoryInfo();
System.out.println(" Name: " + repositoryInfo.getName());
System.out.println(" Vendor: " + repositoryInfo.getVendorName());
System.out.println(" Version: " + repositoryInfo.getProductVersion());
}
}
| Java |
package com.alfresco.cloud.example;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.Repository;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.api.SessionFactory;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.data.ContentStream;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.chemistry.opencmis.commons.exceptions.CmisContentAlreadyExistsException;
import org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException;
import com.alfresco.cloud.example.model.ContainerEntry;
import com.alfresco.cloud.example.model.ContainerList;
import com.alfresco.cloud.example.oauth.LocalServerReceiver;
import com.alfresco.cloud.example.oauth.OAuth2ClientCredentials;
import com.alfresco.cloud.example.oauth.VerificationCodeReceiver;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpParser;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
/**
* Base example class from which all other examples inherit.
*
* @author jpotts
*
*/
public abstract class BaseJavaExample {
public static final String HOME_NETWORK = "alfresco.com";
public static final String SITE = "alfresco-api-demo";
public static final String SCOPE = "public_api";
public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static final JsonFactory JSON_FACTORY = new JacksonFactory();
public static final String ALFRESCO_API_URL = "https://api.alfresco.com/";
public static final String TOKEN_SERVER_URL = ALFRESCO_API_URL + "auth/oauth/versions/2/token";
public static final String AUTHORIZATION_SERVER_URL = ALFRESCO_API_URL + "auth/oauth/versions/2/authorize";
public static final String SITES_URL = "/public/alfresco/versions/1/sites";
public static final String NODES_URL = "/public/alfresco/versions/1/nodes/";
public static final String ATOMPUB_URL = ALFRESCO_API_URL + "cmis/versions/1.0/atom";
public void launchInBrowser(
String browser, String redirectUrl, String clientId, String scope) throws IOException {
String authorizationUrl = new AuthorizationCodeRequestUrl(
AUTHORIZATION_SERVER_URL, clientId).setRedirectUri(redirectUrl)
.setScopes(Arrays.asList(scope)).build();
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Action.BROWSE)) {
desktop.browse(URI.create(authorizationUrl));
return;
}
}
if (browser != null) {
Runtime.getRuntime().exec(new String[] {browser, authorizationUrl});
} else {
System.out.println("Open the following address in your favorite browser:");
System.out.println(" " + authorizationUrl);
}
}
public void run() throws Exception {
// authorization
VerificationCodeReceiver receiver = new LocalServerReceiver();
try {
String redirectUri = receiver.getRedirectUri();
launchInBrowser("google-chrome", redirectUri, OAuth2ClientCredentials.CLIENT_ID, SCOPE);
final Credential credential = authorize(receiver, redirectUri);
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
credential.initialize(request);
request.addParser(new JsonHttpParser(JSON_FACTORY));
}
});
System.out.println("Access token:" + credential.getAccessToken());
doExample(requestFactory, credential);
} catch (Exception e) {
e.printStackTrace();
} finally {
receiver.stop();
}
}
public void doExample(HttpRequestFactory requestFactory, Credential credential)
throws IOException {
}
public Credential authorize(VerificationCodeReceiver receiver, String redirectUri)
throws IOException {
String code = receiver.waitForCode();
AuthorizationCodeFlow codeFlow = new AuthorizationCodeFlow.Builder(
BearerToken.authorizationHeaderAccessMethod(),
HTTP_TRANSPORT,
JSON_FACTORY,
new GenericUrl(TOKEN_SERVER_URL),
new ClientParametersAuthentication(
OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET),
OAuth2ClientCredentials.CLIENT_ID,
AUTHORIZATION_SERVER_URL).setScopes(SCOPE).build();
TokenResponse response = codeFlow.newTokenRequest(code)
.setRedirectUri(redirectUri).setScopes(SCOPE).execute();
return codeFlow.createAndStoreCredential(response, null);
}
/**
* Gets a CMIS Session by connecting to the Alfresco Cloud.
*
* @param accessToken
* @return Session
*/
public Session getCmisSession(String accessToken) {
// default factory implementation
SessionFactory factory = SessionFactoryImpl.newInstance();
Map<String, String> parameter = new HashMap<String, String>();
// connection settings
parameter.put(SessionParameter.ATOMPUB_URL, ATOMPUB_URL);
parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
parameter.put(SessionParameter.AUTH_HTTP_BASIC, "false");
parameter.put(SessionParameter.HEADER + ".0", "Authorization: Bearer " + accessToken);
parameter.put(SessionParameter.OBJECT_FACTORY_CLASS, "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
List<Repository> repositories = factory.getRepositories(parameter);
return repositories.get(0).createSession();
}
/**
* Use the CMIS API to create a document in a folder
*
* @param cmisSession
* @param parentFolder
* @param file
* @param fileType
* @param props
* @return
* @throws FileNotFoundException
*
* @author jpotts
*
*/
public Document createDocument(Session cmisSession,
Folder parentFolder,
File file,
String fileType,
Map<String, Object> props)
throws FileNotFoundException {
String fileName = file.getName();
// create a map of properties if one wasn't passed in
if (props == null) {
props = new HashMap<String, Object>();
}
// Add the object type ID if it wasn't already
if (props.get("cmis:objectTypeId") == null) {
props.put("cmis:objectTypeId", "cmis:document");
}
// Add the name if it wasn't already
if (props.get("cmis:name") == null) {
props.put("cmis:name", fileName);
}
ContentStream contentStream = cmisSession.getObjectFactory().
createContentStream(
fileName,
file.length(),
fileType,
new FileInputStream(file)
);
Document document = null;
try {
document = parentFolder.createDocument(props, contentStream, null);
System.out.println("Created new document: " + document.getId());
} catch (CmisContentAlreadyExistsException ccaee) {
document = (Document) cmisSession.getObjectByPath(parentFolder.getPath() + "/" + fileName);
System.out.println("Document already exists: " + fileName);
}
return document;
}
/**
* Use the CMIS API to get a handle to the root folder of the
* target site, then create a new folder, then create
* a new document in the new folder
*
* @param cmisSession
* @param parentFolderId
* @param folderName
* @return Folder
*
* @author jpotts
*
*/
public Folder createFolder(Session cmisSession, String parentFolderId, String folderName) {
Folder rootFolder = (Folder) cmisSession.getObject(parentFolderId);
Folder subFolder = null;
try {
// Making an assumption here that you probably wouldn't normally do
subFolder = (Folder) cmisSession.getObjectByPath(rootFolder.getPath() + "/" + folderName);
System.out.println("Folder already existed!");
} catch (CmisObjectNotFoundException onfe) {
Map<String, Object> props = new HashMap<String, Object>();
props.put("cmis:objectTypeId", "cmis:folder");
props.put("cmis:name", folderName);
subFolder = rootFolder.createFolder(props);
String subFolderId = subFolder.getId();
System.out.println("Created new folder: " + subFolderId);
}
return subFolder;
}
/**
* Use the REST API to find the documentLibrary folder for
* the target site
* @return String
*
* @author jpotts
*
*/
public String getRootFolderId(HttpRequestFactory requestFactory, String homeNetwork, String site) throws IOException {
GenericUrl containersUrl = new GenericUrl(ALFRESCO_API_URL +
homeNetwork +
"/public/alfresco/versions/1/sites/" +
site +
"/containers");
HttpRequest request = requestFactory.buildGetRequest(containersUrl);
ContainerList containerList = request.execute().parseAs(ContainerList.class);
String rootFolderId = null;
for (ContainerEntry containerEntry : containerList.list.entries) {
if (containerEntry.entry.folderId.equals("documentLibrary")) {
rootFolderId = containerEntry.entry.id;
break;
}
}
return rootFolderId;
}
} | Java |
package com.alfresco.cloud.example;
import java.io.IOException;
import com.alfresco.cloud.example.model.NetworkList;
import com.alfresco.cloud.example.model.SiteEntry;
import com.alfresco.cloud.example.model.SiteList;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
/**
* Simple example that shows how to hit the Alfresco Cloud with
* the REST API to find the user's home network and to list up to
* 10 sites visible to the user.
*
* @author jpotts
*/
public class GetSitesExample extends BaseJavaExample {
public static void main(String[] args) {
GetSitesExample gse = new GetSitesExample();
try {
gse.run();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doExample(HttpRequestFactory requestFactory, Credential credential)
throws IOException {
// Find the user's home network
GenericUrl url = new GenericUrl(ALFRESCO_API_URL);
HttpRequest request = requestFactory.buildGetRequest(url);
NetworkList networkList = request.execute().parseAs(NetworkList.class);
System.out.println("Found " + networkList.list.pagination.totalItems + " networks.");
String homeNetwork = networkList.list.entries.get(0).entry.id; // Assuming first network for right now
System.out.println("Your home network appears to be: " + homeNetwork);
// List some of the sites the user can see
GenericUrl sitesUrl = new GenericUrl(ALFRESCO_API_URL +
homeNetwork +
SITES_URL + "?maxItems=10");
request = requestFactory.buildGetRequest(sitesUrl);
SiteList siteList = request.execute().parseAs(SiteList.class);
System.out.println("Up to 10 sites you can see are:");
for (SiteEntry siteEntry : siteList.list.entries) {
System.out.println(siteEntry.entry.id);
}
System.out.println("Done!");
}
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.alfresco.cloud.example.oauth;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Runs a Jetty server on a free port, waiting for OAuth to redirect to it with the verification
* code.
* <p>
* Mostly copied from oacurl by phopkins@google.com.
* </p>
*
* @author Yaniv Inbar
*/
public final class LocalServerReceiver implements VerificationCodeReceiver {
private static final String CALLBACK_PATH = "/Callback";
private static final String LOCALHOST = "127.0.0.1";
private static final int PORT = 8080;
/** Server or {@code null} before {@link #getRedirectUri()}. */
private Server server;
/** Verification code or {@code null} before received. */
volatile String code;
@Override
public String getRedirectUri() throws Exception {
server = new Server(PORT);
for (Connector c : server.getConnectors()) {
c.setHost(LOCALHOST);
}
server.addHandler(new CallbackHandler());
server.start();
return "http://" + LOCALHOST + ":" + PORT + CALLBACK_PATH;
}
@Override
public synchronized String waitForCode() {
try {
this.wait();
} catch (InterruptedException exception) {
// should not happen
}
return code;
}
@Override
public void stop() throws Exception {
if (server != null) {
server.stop();
server = null;
}
}
/**
* Jetty handler that takes the verifier token passed over from the OAuth provider and stashes it
* where {@link #waitForCode} will find it.
*/
class CallbackHandler extends AbstractHandler {
@Override
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 error = request.getParameter("error");
if (error != null) {
System.out.println("Authorization failed. Error=" + error);
System.out.println("Quitting.");
System.exit(1);
}
code = request.getParameter("code");
synchronized (LocalServerReceiver.this) {
LocalServerReceiver.this.notify();
}
}
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 2.0 Authentication Token Recieved</title></head>");
doc.println("<body>");
doc.println("Received verification code. 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 |
package com.alfresco.cloud.example.oauth;
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Verification code receiver.
*
* @author Yaniv Inbar
*/
public interface VerificationCodeReceiver {
/** Returns the redirect URI. */
String getRedirectUri() throws Exception;
/** Waits for a verification code. */
String waitForCode();
/** Releases any resources and stops any processes started. */
void stop() throws Exception;
}
| Java |
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.alfresco.cloud.example.oauth;
public class OAuth2ClientCredentials {
/** Value of the "API Key". */
public static final String CLIENT_ID = "";
/** Value of the "API Secret". */
public static final String CLIENT_SECRET = "";
}
| Java |
package com.alfresco.cloud.example;
import java.io.File;
import java.io.IOException;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.Session;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
/**
* Shows how to use CMIS to create a document in the Alfresco Cloud.
* Also uses the REST API to like a folder and comment on a document.
*
* @author jpotts
*
*/
public class CmisCreateDocumentExample extends BaseJavaExample {
public static final String FOLDER_NAME = "test folder";
//public static final File FILE = new File("/users/jpotts/Documents/sample/sample-a.doc");
//public static final String FILE_TYPE = "application/msword";
public static final File FILE = new File("/users/jpotts/Documents/sample/sample-a.pdf");
public static final String FILE_TYPE = "application/pdf";
/**
* @param args
*/
public static void main(String[] args) {
CmisCreateDocumentExample ccde = new CmisCreateDocumentExample();
try {
ccde.run();
} catch (Exception e) {
e.printStackTrace();
}
}
public void doExample(HttpRequestFactory requestFactory, Credential credential)
throws IOException {
// Get the accessToken
String accessToken = credential.getAccessToken();
// Get a CMIS session
Session cmisSession = getCmisSession(accessToken);
// Find the root folder of our target site
String rootFolderId = getRootFolderId(requestFactory, HOME_NETWORK, SITE);
// Create a new folder in the root folder
Folder subFolder = createFolder(cmisSession, rootFolderId, FOLDER_NAME);
// Like the folder
like(requestFactory, HOME_NETWORK, subFolder.getId());
// Create a test document in the subFolder
Document document = createDocument(cmisSession, subFolder, FILE, FILE_TYPE, null);
// Create a comment on the test document
// NOTE: When dealing with documents, the REST API wants a versionSeriesID!
comment(requestFactory, HOME_NETWORK, document.getVersionSeriesId(), "Here is a comment!");
}
/**
* Use the REST API to "like" an object
*
* @param requestFactory
* @param homeNetwork
* @param objectId
* @throws IOException
*/
public void like(HttpRequestFactory requestFactory, String homeNetwork, String objectId) throws IOException {
GenericUrl likeUrl = new GenericUrl(ALFRESCO_API_URL +
homeNetwork +
NODES_URL +
objectId +
"/ratings");
HttpContent body = new ByteArrayContent("application/json", "{\"id\": \"likes\", \"myRating\": true}".getBytes());
HttpRequest request = requestFactory.buildPostRequest(likeUrl, body);
request.execute();
System.out.println("You liked: " + objectId);
}
/**
* Use the REST API to comment on an object
*
* @param requestFactory
* @param homeNetwork
* @param objectId
* @param comment
* @throws IOException
*/
public void comment(HttpRequestFactory requestFactory, String homeNetwork, String objectId, String comment) throws IOException {
GenericUrl commentUrl = new GenericUrl(ALFRESCO_API_URL +
homeNetwork +
NODES_URL +
objectId +
"/comments");
HttpContent body = new ByteArrayContent("application/json",
("{\"content\": \"" + comment + "\"}").getBytes());
HttpRequest request = requestFactory.buildPostRequest(commentUrl, body);
request.execute();
System.out.println("You commented on: " + objectId);
}
}
| Java |
package com.google.code.geobeagle;
import java.util.Hashtable;
public class CacheTypeFactory {
private final Hashtable<Integer, CacheType> mCacheTypes =
new Hashtable<Integer, CacheType>(CacheType.values().length);
public CacheTypeFactory() {
for (CacheType cacheType : CacheType.values())
mCacheTypes.put(cacheType.toInt(), cacheType);
}
public CacheType fromInt(int i) {
if (!mCacheTypes.containsKey(i))
return CacheType.NULL;
return mCacheTypes.get(i);
}
public CacheType fromTag(String tag) {
String tagLower = tag.toLowerCase();
int longestMatch = 0;
CacheType result = CacheType.NULL;
for (CacheType cacheType : mCacheTypes.values()) {
String cacheTypeTag = cacheType.getTag();
if (tagLower.contains(cacheTypeTag) && cacheTypeTag.length() > longestMatch) {
result = cacheType;
// Necessary to continue the search to find mega-events and
// individual waypoint types.
longestMatch = cacheTypeTag.length();
}
}
return result;
}
public int container(String container) {
if (container.equals("Micro")) {
return 1;
} else if (container.equals("Small")) {
return 2;
} else if (container.equals("Regular")) {
return 3;
} else if (container.equals("Large")) {
return 4;
}
return 0;
}
public int stars(String stars) {
try {
return Math.round(Float.parseFloat(stars) * 2);
} catch (Exception ex) {
return 0;
}
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.code.geobeagle.IToaster;
import com.google.code.geobeagle.Toaster.OneTimeToaster;
import com.google.code.geobeagle.database.CachesProviderLazyArea;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import java.util.List;
public class DensityOverlay extends Overlay {
// Create delegate because it's not possible to test classes that extend
// Android classes.
public static DensityOverlayDelegate createDelegate(List<DensityMatrix.DensityPatch> patches,
GeoPoint nullGeoPoint, CachesProviderLazyArea lazyArea, IToaster densityOverlayToaster) {
final Rect patchRect = new Rect();
final Paint paint = new Paint();
paint.setARGB(128, 255, 0, 0);
final Point screenLow = new Point();
final Point screenHigh = new Point();
final DensityPatchManager densityPatchManager = new DensityPatchManager(patches,
lazyArea, densityOverlayToaster);
return new DensityOverlayDelegate(patchRect, paint, screenLow, screenHigh,
densityPatchManager);
}
private DensityOverlayDelegate mDelegate;
public DensityOverlay(DensityOverlayDelegate densityOverlayDelegate) {
mDelegate = densityOverlayDelegate;
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
mDelegate.draw(canvas, mapView, shadow);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import java.util.AbstractList;
public class CachePinsOverlay extends ItemizedOverlay<CacheItem> {
private final CacheItemFactory mCacheItemFactory;
private final Context mContext;
private final AbstractList<Geocache> mCacheList;
public CachePinsOverlay(CacheItemFactory cacheItemFactory, Context context,
Drawable defaultMarker, AbstractList<Geocache> list) {
super(boundCenterBottom(defaultMarker));
mContext = context;
mCacheItemFactory = cacheItemFactory;
mCacheList = list;
populate();
}
/* (non-Javadoc)
* @see com.google.android.maps.Overlay#draw(android.graphics.Canvas, com.google.android.maps.MapView, boolean, long)
*/
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
return super.draw(canvas, mapView, shadow, when);
}
@Override
protected boolean onTap(int i) {
Geocache geocache = getItem(i).getGeocache();
if (geocache == null)
return false;
final Intent intent = new Intent(mContext, GeoBeagle.class);
intent.setAction(GeocacheListController.SELECT_CACHE);
intent.putExtra("geocacheId", geocache.getId());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
return true;
}
@Override
protected CacheItem createItem(int i) {
return mCacheItemFactory.createCacheItem(mCacheList.get(i));
}
@Override
public int size() {
return mCacheList.size();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;
import com.google.code.geobeagle.Geocache;
class CacheItem extends OverlayItem {
private final Geocache mGeocache;
CacheItem(GeoPoint geoPoint, Geocache geocache) {
super(geoPoint, (String)geocache.getId(), "");
mGeocache = geocache;
}
Geocache getGeocache() {
return mGeocache;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.