code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
/*
** 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.bcaching.communication;
import android.util.Log;
public class BCachingList {
private final BCachingJSONObject cacheList;
BCachingList(BCachingJSONObject cacheList) {
this.cacheList = cacheList;
}
String getCacheIds() throws BCachingException {
BCachingJSONArray summary = cacheList.getJSONArray("data");
Log.d("GeoBeagle", summary.toString());
StringBuilder csvIds = new StringBuilder();
int count = summary.length();
for (int i = 0; i < count; i++) {
csvIds.append(',');
BCachingJSONObject cacheObject = summary.getJSONObject(i);
csvIds.append(String.valueOf(cacheObject.getInt("id")));
}
if (count > 0)
csvIds.deleteCharAt(0);
return csvIds.toString();
}
long getServerTime() throws BCachingException {
return cacheList.getLong("serverTime");
}
int getCachesRead() throws BCachingException {
int length = cacheList.getJSONArray("data").length();
Log.d("GeoBeagle", "getCachesRead: " + length);
return length;
}
int getTotalCount() throws BCachingException {
return cacheList.getInt("totalCount");
}
}
| 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.bcaching.communication;
import com.google.inject.Inject;
import android.content.SharedPreferences;
import java.util.Hashtable;
public class BCachingListImporterStateless {
static final String MAX_COUNT = "50";
private final BCachingListImportHelper bCachingListImportHelper;
private final Hashtable<String, String> params;
@Inject
BCachingListImporterStateless(BCachingListImportHelper bCachingListImportHelper,
SharedPreferences sharedPreferences) {
this.bCachingListImportHelper = bCachingListImportHelper;
params = new Hashtable<String, String>();
params.put("a", "list");
boolean syncFinds = sharedPreferences.getBoolean("bcaching-sync-finds", false);
params.put("found", syncFinds ? "2" : "0"); // 0-no, 1-yes, 2-both
commonParams(params);
}
// For testing.
BCachingListImporterStateless(Hashtable<String, String> params,
BCachingListImportHelper bCachingListImportHelper) {
this.bCachingListImportHelper = bCachingListImportHelper;
this.params = params;
}
private BCachingList importList(String maxCount, String startTime) throws BCachingException {
params.put("maxcount", maxCount);
params.put("since", startTime);
// params.put("since", "1298740607924");
return bCachingListImportHelper.importList(params);
}
public BCachingList getCacheList(String startPosition, String startTime)
throws BCachingException {
params.put("first", startPosition);
return importList(MAX_COUNT, startTime);
}
public int getTotalCount(String startTime) throws BCachingException {
params.remove("first");
BCachingList importList = importList("1", startTime);
return importList.getTotalCount();
}
public static void commonParams(Hashtable<String, String> params) {
params.put("lastuploaddays", "7");
params.put("app", "GeoBeagle");
params.put("timeAsLong", "1");
params.put("own", "2");
}
}
| 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.bcaching.communication;
import com.google.code.geobeagle.bcaching.BufferedReaderFactory;
import com.google.inject.Inject;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Hashtable;
public class BCachingListImportHelper {
private final BCachingListFactory bcachingListFactory;
private final BufferedReaderFactory bufferedReaderFactory;
@Inject
BCachingListImportHelper(BufferedReaderFactory readerFactory,
BCachingListFactory bcachingListFactory) {
this.bufferedReaderFactory = readerFactory;
this.bcachingListFactory = bcachingListFactory;
}
public BCachingList importList(Hashtable<String, String> params) throws BCachingException {
BufferedReader bufferedReader = bufferedReaderFactory.create(params);
StringBuilder result = new StringBuilder();
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
Log.d("GeoBeagle", "importList: " + line);
result.append(line);
result.append('\n');
}
return bcachingListFactory.create(result.toString());
} catch (IOException e) {
throw new BCachingException("IO Error: " + e.getLocalizedMessage());
}
}
}
| 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.bcaching.communication;
import org.json.JSONException;
import org.json.JSONObject;
public class BCachingJSONObject {
private final JSONObject jsonObject;
public BCachingJSONObject(JSONObject jsonObject) {
this.jsonObject = jsonObject;
}
public BCachingJSONArray getJSONArray(String key) throws BCachingException {
try {
return new BCachingJSONArray(jsonObject.getJSONArray(key));
} catch (JSONException e) {
throw new BCachingException(e.getLocalizedMessage());
}
}
public int getInt(String key) throws BCachingException {
try {
return jsonObject.getInt(key);
} catch (JSONException e) {
throw new BCachingException(e.getLocalizedMessage());
}
}
public long getLong(String key) throws BCachingException {
try {
return jsonObject.getLong(key);
} catch (JSONException e) {
throw new BCachingException(e.getLocalizedMessage());
}
}
}
| 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.bcaching.communication;
public class BCachingException extends Exception {
private static final long serialVersionUID = 5483107564028776147L;
public BCachingException(String string) {
super(string);
}
} | 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.bcaching.communication;
import org.json.JSONArray;
import org.json.JSONException;
public class BCachingJSONArray {
private final JSONArray jsonArray;
public BCachingJSONArray(JSONArray jsonArray) {
this.jsonArray = jsonArray;
}
public BCachingJSONObject getJSONObject(int index) throws BCachingException {
try {
return new BCachingJSONObject(jsonArray.getJSONObject(index));
} catch (JSONException e) {
throw new BCachingException(e.getLocalizedMessage());
}
}
public int length() {
return jsonArray.length();
}
}
| 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.bcaching.communication;
import com.google.inject.Inject;
public class BCachingListImporter {
private final BCachingListImporterStateless bcachingListImporterStateless;
private BCachingList bcachingList;
private String startTime;
private long serverTime;
@Inject
public BCachingListImporter(BCachingListImporterStateless bcachingListImporterStateless) {
this.bcachingListImporterStateless = bcachingListImporterStateless;
}
public void readCacheList(int startPosition) throws BCachingException {
bcachingList = bcachingListImporterStateless.getCacheList(String.valueOf(startPosition),
startTime);
serverTime = bcachingList.getServerTime();
}
public int getTotalCount() throws BCachingException {
return bcachingListImporterStateless.getTotalCount(startTime);
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
/**
* Must be called after readCacheList().
*/
public long getServerTime() {
return serverTime;
}
public String getCacheIds() throws BCachingException {
return bcachingList.getCacheIds();
}
public int getCachesRead() throws BCachingException {
return bcachingList.getCachesRead();
}
}
| 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.bcaching.progress;
import com.google.inject.Singleton;
import android.os.Message;
import android.util.Log;
@Singleton
public class ProgressManager {
private int currentProgress;
public void setCurrentProgress(int currentProgress) {
this.currentProgress = currentProgress;
}
public void update(ProgressHandler handler, ProgressMessage progressMessage, int arg) {
Message.obtain(handler, progressMessage.ordinal(), arg, 0).sendToTarget();
}
public void update(ProgressHandler handler,
ProgressMessage progressMessage,
int arg1,
String arg2) {
if (!handler.hasMessages(progressMessage.ordinal()))
Message.obtain(handler, progressMessage.ordinal(), arg1, 0, arg2).sendToTarget();
}
public int getCurrentProgress() {
return currentProgress;
}
public void incrementProgress() {
Log.d("GeoBeagle", "incrementing Progress: " + currentProgress);
currentProgress++;
}
}
| 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.bcaching.progress;
import com.google.code.geobeagle.activity.cachelist.ActivityVisible;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.bcaching.BCachingModule;
import com.google.code.geobeagle.bcaching.BCachingProgressDialog;
import com.google.inject.Inject;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class ProgressHandler extends Handler {
private final ProgressDialog progressDialog;
private final CacheListRefresh cacheListRefresher;
private final ActivityVisible activityVisible;
@Inject
public ProgressHandler(BCachingProgressDialog progressDialog,
CacheListRefresh cacheListRefresh, ActivityVisible activityVisible) {
this.progressDialog = progressDialog;
this.cacheListRefresher = cacheListRefresh;
this.activityVisible = activityVisible;
}
public void done() {
progressDialog.setMessage(BCachingModule.BCACHING_INITIAL_MESSAGE);
progressDialog.dismiss();
}
@Override
public void handleMessage(Message msg) {
ProgressMessage progressMessage = ProgressMessage.fromInt(msg.what);
progressMessage.act(this, msg);
}
public void setFile(String filename, int progress) {
progressDialog.setMessage("Loading: " + filename);
progressDialog.setProgress(progress);
}
public void setMax(int max) {
progressDialog.setMax(max);
}
public void setProgress(int progress) {
progressDialog.setProgress(progress);
}
public void show() {
progressDialog.show();
}
public void refresh() {
Log.d("GeoBeagle", "REFRESHING");
if (activityVisible.getVisible()) {
cacheListRefresher.forceRefresh();
}
else
Log.d("GeoBeagle", "NOT VISIBLE, punting");
}
}
| 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.bcaching.progress;
import android.os.Message;
public enum ProgressMessage {
DONE {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.done();
}
},
REFRESH {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.refresh();
}
},
SET_FILE {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.setFile((String)msg.obj, msg.arg1);
}
},
SET_MAX {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.setMax(msg.arg1);
}
},
SET_PROGRESS {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.setProgress(msg.arg1);
}
},
START {
@Override
void act(ProgressHandler progressHandler, Message msg) {
progressHandler.setProgress(0);
progressHandler.setMax(100);
progressHandler.show();
}
};
static ProgressMessage fromInt(Integer i) {
return ProgressMessage.class.getEnumConstants()[i];
}
abstract void act(ProgressHandler progressHandler, Message msg);
}
| 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.preferences;
import com.google.code.geobeagle.activity.preferences.Preferences;
import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment;
import com.google.inject.Inject;
public class PreferencesUpgrader {
private final DependencyUpgrader dependencyUpgrader;
@Inject
PreferencesUpgrader(DependencyUpgrader dependencyUpgrader) {
this.dependencyUpgrader = dependencyUpgrader;
}
public void upgrade(int oldVersion) {
if (oldVersion <= 14) {
dependencyUpgrader.upgrade(Preferences.BCACHING_ENABLED, Preferences.BCACHING_USERNAME);
dependencyUpgrader.upgrade(Preferences.SDCARD_ENABLED,
GeoBeagleEnvironment.IMPORT_FOLDER);
}
}
}
| 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.preferences;
import com.google.inject.Inject;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
class DependencyUpgrader {
private final SharedPreferences sharedPreferences;
@Inject
DependencyUpgrader(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
}
void upgrade(String checkBoxKey, String stringKey) {
String stringValue = sharedPreferences.getString(stringKey, "");
if (stringValue.length() > 0) {
Editor editor = sharedPreferences.edit();
editor.putBoolean(checkBoxKey, true);
editor.commit();
}
}
}
| 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.cachedetails;
import com.google.inject.Inject;
import com.google.inject.Provider;
import android.app.Activity;
import android.content.Context;
class ShowToastOnUiThread {
@Inject
public ShowToastOnUiThread(Provider<Context> contextProvider,
Provider<Activity> activityProvider) {
this.contextProvider = contextProvider;
this.activityProvider = activityProvider;
}
private final Provider<Context> contextProvider;
private final Provider<Activity> activityProvider;
public void showToast(int msg, int length) {
Runnable showToast = new ShowToastRunnable(contextProvider.get(), msg, length);
activityProvider.get().runOnUiThread(showToast);
}
}
| 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.cachedetails;
import com.google.code.geobeagle.xmlimport.EmotifierPatternProvider;
import com.google.inject.Inject;
import java.net.URLEncoder;
import java.util.regex.Matcher;
public class Emotifier {
public static final String ICON_PREFIX = "<img src='file:///android_asset/";
public static final String ICON_SUFFIX = ".gif' border=0 align=bottom>";
public static final String EMOTICON_PREFIX = ICON_PREFIX + "icon_smile_";
private final EmotifierPatternProvider patternProvider;
@Inject
public Emotifier(EmotifierPatternProvider patternProvider) {
this.patternProvider = patternProvider;
}
String emotify(String text) {
Matcher matcher = patternProvider.get().matcher(text);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String match = matcher.group(1);
String encoded = URLEncoder.encode(match).replace("%", "");
matcher.appendReplacement(sb, EMOTICON_PREFIX + encoded + ICON_SUFFIX);
}
matcher.appendTail(sb);
return sb.toString();
}
}
| 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.cachedetails;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriterWrapper implements com.google.code.geobeagle.cachedetails.Writer,
FilerWriterOpener {
private java.io.Writer mWriter;
@Override
public void close() throws IOException {
mWriter.close();
mWriter = null;
}
@Override
public void open(String path) throws IOException {
mWriter = new BufferedWriter(new FileWriter(path), 4000);
}
@Override
public void mkdirs(String path) {
new File(new File(path).getParent()).mkdirs();
}
@Override
public void write(String str) throws IOException {
if (mWriter == null) {
Log.e("GeoBeagle", "Attempting to write string but no waypoint received yet: " + str);
return;
}
try {
mWriter.write(str);
} catch (IOException e) {
throw new IOException("Error writing line '" + str + "'");
}
}
@Override
public boolean isOpen() {
return mWriter != null;
}
}
| 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.cachedetails;
import android.content.Context;
import android.widget.Toast;
class ShowToastRunnable implements Runnable {
private final Context context;
private final int msg;
private final int length;
public ShowToastRunnable(Context context, int msg, int length) {
this.context = context;
this.msg = msg;
this.length = length;
}
@Override
public void run() {
Toast.makeText(context, msg, length).show();
}
}
| 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.cachedetails;
import java.io.IOException;
public interface Writer {
public void close() throws IOException;
// public void open(String path, String wpt) throws IOException;
public void write(String str) throws IOException;
public boolean isOpen();
void mkdirs(String path);
}
| 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.cachedetails;
import com.google.inject.Singleton;
import java.io.IOException;
import java.io.StringWriter;
//TODO: remove singleton.
@Singleton
public class StringWriterWrapper implements com.google.code.geobeagle.cachedetails.Writer,
NullWriterOpener {
private final StringWriter stringWriter;
public StringWriterWrapper() {
this.stringWriter = new StringWriter();
}
@Override
public void close() throws IOException {
}
@Override
public boolean isOpen() {
return true;
}
@Override
public void open() throws IOException {
stringWriter.getBuffer().setLength(0);
}
public String getString() {
return stringWriter.toString();
}
@Override
public void write(String str) throws IOException {
// Log.d("GeoBeagle", ":: " + str);
stringWriter.write(str);
}
@Override
public void mkdirs(String path) {
}
}
| 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.cachedetails;
import com.google.inject.Inject;
import android.content.Context;
import android.text.format.DateUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
class RelativeDateFormatter {
private final Calendar gmtCalendar;
@Inject
RelativeDateFormatter() {
this.gmtCalendar = Calendar.getInstance();
}
String getRelativeTime(Context context, String utcTime) throws ParseException {
long now = System.currentTimeMillis();
gmtCalendar.setTime(parse(utcTime));
long timeInMillis = gmtCalendar.getTimeInMillis();
long duration = Math.abs(now - timeInMillis);
if (duration < DateUtils.WEEK_IN_MILLIS) {
return (String)DateUtils.getRelativeTimeSpanString(timeInMillis, now,
DateUtils.DAY_IN_MILLIS, 0);
}
return (String)DateUtils.getRelativeTimeSpanString(context, timeInMillis, false);
}
private Date parse(String input) throws java.text.ParseException {
final String formatString = "yyyy-MM-dd'T'HH:mm:ss Z";
SimpleDateFormat df = new SimpleDateFormat(formatString);
String s;
try {
s = input.substring(0, 19) + " +0000";
} catch (Exception e) {
throw new ParseException(null, 0);
}
return df.parse(s);
}
}
| Java |
package com.google.code.geobeagle.cachedetails;
import java.io.IOException;
public interface NullWriterOpener {
public void open() throws IOException;
}
| 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.cachedetails;
import com.google.inject.Inject;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class DetailsDatabaseReader {
private static final String TABLE_DETAILS = "Details";
private static final String COLUMN_DETAILS = "Details";
private final SdDatabaseOpener sdDatabaseOpener;
private final String[] columns = new String[] {
COLUMN_DETAILS
};
@Inject
DetailsDatabaseReader(SdDatabaseOpener sdDatabaseOpener) {
this.sdDatabaseOpener = sdDatabaseOpener;
}
public String read(CharSequence cacheId) {
SQLiteDatabase sdDatabase = sdDatabaseOpener.open();
String[] selectionArgs = {
(String)cacheId
};
Cursor cursor = sdDatabase.query(TABLE_DETAILS, columns, "CacheId=?", selectionArgs, null,
null, null);
Log.d("GeoBeagle", "count: " + cursor.getCount() + ", " + cursor.getColumnCount());
cursor.moveToFirst();
if (cursor.getCount() < 1)
return null;
String details = cursor.getString(0);
cursor.close();
Log.d("GeoBeagle", "DETAILS: " + details);
sdDatabase.close();
return details;
}
}
| 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.cachedetails;
import com.google.inject.Inject;
import java.io.IOException;
public class HtmlWriter {
private final StringWriterWrapper mWriter;
static final String HEADER = "<html>\n<head>\n"
+ "<script type=\"text/javascript\" src=\"file:///android_asset/rot13.js\"></script>\n"
+ "<style type='text/css'> div.hint_loading { display: none } a.hint_loading { color: gray } "
+ " a.hint_loading:after { content: 'ing hint, please wait...' }</style>\n"
+ "</head>\n<body onLoad=encryptAll()>";
@Inject
public HtmlWriter(StringWriterWrapper writerWrapper) {
mWriter = writerWrapper;
}
public void close() throws IOException {
mWriter.close();
}
public void open() throws IOException {
mWriter.open();
}
public void writeln(String text) throws IOException {
mWriter.write(text + "<br/>\n");
}
public void write(String text) throws IOException {
mWriter.write(text + "\n");
}
public void writeFooter() throws IOException {
mWriter.write(" </body>\n");
mWriter.write("</html>\n");
}
public void writeHeader() throws IOException {
mWriter.write(HEADER);
}
public void writeSeparator() throws IOException {
mWriter.write("<hr/>\n");
}
}
| Java |
package com.google.code.geobeagle.cachedetails;
import java.io.IOException;
public interface FilerWriterOpener {
public void open(String path) throws IOException;
}
| 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.cachedetails;
import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment;
import com.google.inject.Inject;
public class FilePathStrategy {
private final GeoBeagleEnvironment geoBeagleEnvironment;
@Inject
public
FilePathStrategy(GeoBeagleEnvironment geoBeagleEnvironment) {
this.geoBeagleEnvironment = geoBeagleEnvironment;
}
private static String replaceIllegalFileChars(String wpt) {
return wpt.replaceAll("[<\\\\/:\\*\\?\">| \\t]", "_");
}
public String getPath(CharSequence gpxName, String wpt, String extension) {
String string = geoBeagleEnvironment.getDetailsDirectory() + gpxName + "/"
+ String.valueOf(Math.abs(wpt.hashCode()) % 16) + "/"
+ replaceIllegalFileChars(wpt) + "." + extension;
return string;
}
}
| 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.cachedetails;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
@Singleton
public class DetailsDatabaseWriter {
private SQLiteDatabase sdDatabase;
private final SdDatabaseOpener sdDatabaseOpener;
private final ContentValues contentValues;
@Inject
DetailsDatabaseWriter(SdDatabaseOpener sdDatabaseOpener) {
this.sdDatabaseOpener = sdDatabaseOpener;
contentValues = new ContentValues();
}
public void write(String cacheId, String details) {
contentValues.put("Details", details);
contentValues.put("CacheId", cacheId);
sdDatabase.replace("Details", "Details", contentValues);
}
public void deleteAll() {
sdDatabaseOpener.delete();
}
public void start() {
sdDatabase = sdDatabaseOpener.open();
Log.d("GeoBeagle", "STARTING TRANSACTION");
sdDatabase.beginTransaction();
}
public void end() {
if (sdDatabase == null)
return;
Log.d("GeoBeagle", "DetailsDatabaseWriter::end()");
sdDatabase.setTransactionSuccessful();
sdDatabase.endTransaction();
sdDatabase.close();
sdDatabase = null;
}
}
| 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.cachedetails;
import com.google.code.geobeagle.activity.compass.Util;
import com.google.inject.Inject;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.text.ParseException;
public class CacheDetailsHtmlWriter {
public static String replaceIllegalFileChars(String wpt) {
return wpt.replaceAll("[<\\\\/:\\*\\?\">| \\t]", "_");
}
private final Context context;
private final Emotifier emotifier;
private final HtmlWriter htmlWriter;
private String latitude;
private int logNumber;
private String longitude;
private String time;
private String finder;
private String logType;
private String relativeTime;
private final RelativeDateFormatter relativeDateFormatter;
private String wpt;
@Inject
public CacheDetailsHtmlWriter(HtmlWriter htmlWriter,
Emotifier emotifier,
Context context,
RelativeDateFormatter relativeDateFormatter) {
this.htmlWriter = htmlWriter;
this.emotifier = emotifier;
this.context = context;
this.relativeDateFormatter = relativeDateFormatter;
}
public void close() throws IOException {
htmlWriter.writeFooter();
htmlWriter.close();
latitude = longitude = time = finder = logType = relativeTime = "";
logNumber = 0;
}
public void latitudeLongitude(String latitude, String longitude) {
this.latitude = (String)Util.formatDegreesAsDecimalDegreesString(Double.valueOf(latitude));
this.longitude = (String)Util
.formatDegreesAsDecimalDegreesString(Double.valueOf(longitude));
}
public void logType(String trimmedText) {
logType = Emotifier.ICON_PREFIX + "log_" + trimmedText.replace(' ', '_').replace('\'', '_')
+ Emotifier.ICON_SUFFIX;
}
public void placedBy(String text) throws IOException {
Log.d("GeoBeagle", "PLACED BY: " + time);
String on = "";
try {
on = relativeDateFormatter.getRelativeTime(context, time);
} catch (ParseException e) {
on = "PARSE ERROR";
}
writeField("Placed by", text);
writeField("Placed on", on);
}
public void wptTime(String time) {
this.time = time;
}
public void writeField(String fieldName, String field) throws IOException {
htmlWriter.writeln("<font color=grey>" + fieldName + ":</font> " + field);
}
public void writeHint(String text) throws IOException {
htmlWriter
.write("<a class='hint hint_loading' id=hint_link onclick=\"dht('hint_link');return false;\" href=#>"
+ "Encrypt</a>");
htmlWriter.write("<div class=hint_loading id=hint_link_text>" + text + "</div>");
}
public void writeLine(String text) throws IOException {
htmlWriter.writeln(text);
}
public void writeLogDate(String text) throws IOException {
htmlWriter.writeSeparator();
try {
relativeTime = relativeDateFormatter.getRelativeTime(context, text);
} catch (ParseException e) {
htmlWriter.writeln("error parsing date: " + e.getLocalizedMessage());
}
}
public void writeLogText(String text, boolean encoded) throws IOException {
String f;
htmlWriter.writeln("<b>" + logType + " " + relativeTime + " by " + finder + "</b>");
if (encoded)
f = "<a class=hint id=log_%1$s onclick=\"dht('log_%1$s');return false;\" "
+ "href=#>Encrypt</a><div class=hint_text id=log_%1$s_text>%2$s</div>";
else
f = "%2$s";
htmlWriter.writeln(String.format(f, logNumber++, emotifier.emotify(text)));
}
public void writeLongDescription(String trimmedText) throws IOException {
htmlWriter.write(trimmedText);
htmlWriter.writeSeparator();
}
public void writeName(String name) throws IOException {
htmlWriter.write("<center><h3>" + name + "</h3></center>\n");
}
public void writeShortDescription(String trimmedText) throws IOException {
htmlWriter.writeSeparator();
htmlWriter.writeln(trimmedText);
htmlWriter.writeln("");
}
public void writeWptName(String wpt) throws IOException {
htmlWriter.open();
htmlWriter.writeHeader();
writeField("Location", latitude + ", " + longitude);
latitude = longitude = null;
this.wpt = wpt;
}
public void writeLogFinder(String finder) {
this.finder = finder;
}
public void writeUrl(String text) throws IOException {
writeField("Name", "<a href=" + text + ">" + wpt + "</a>");
}
}
| 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.cachedetails;
import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment;
import com.google.inject.Inject;
import java.io.IOException;
public class FileDataVersionWriter {
private final WriterWrapper writerWrapper;
private final GeoBeagleEnvironment geoBeagleEnvironment;
@Inject
FileDataVersionWriter(WriterWrapper writerWrapper, GeoBeagleEnvironment geoBeagleEnvironment) {
this.writerWrapper = writerWrapper;
this.geoBeagleEnvironment = geoBeagleEnvironment;
}
public void writeVersion() throws IOException {
String versionPath = geoBeagleEnvironment.getVersionPath();
writerWrapper.mkdirs(versionPath);
writerWrapper.open(versionPath);
writerWrapper.write("1");
writerWrapper.close();
}
}
| 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.cachedetails;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
@Singleton
class SdDatabaseOpener {
static final int DATABASE_VERSION = 6;
private final GeoBeagleEnvironment geoBeagleEnvironment;
private final ShowToastOnUiThread showToastOnUiThread;
@Inject
SdDatabaseOpener(GeoBeagleEnvironment geoBeagleEnvironment,
ShowToastOnUiThread showToastOnUiThread) {
this.geoBeagleEnvironment = geoBeagleEnvironment;
this.showToastOnUiThread = showToastOnUiThread;
}
void delete() {
new File(geoBeagleEnvironment.getExternalStorageDir() + "/geobeagle.db").delete();
}
SQLiteDatabase open() {
SQLiteDatabase sqliteDatabase = SQLiteDatabase.openDatabase(
geoBeagleEnvironment.getExternalStorageDir() + "/geobeagle.db", null,
SQLiteDatabase.CREATE_IF_NECESSARY);
int oldVersion = sqliteDatabase.getVersion();
Log.d("GeoBeagle", "SDDatabase verson: " + oldVersion);
if (oldVersion < DATABASE_VERSION) {
if (oldVersion > 0)
showToastOnUiThread.showToast(R.string.upgrading_database, Toast.LENGTH_LONG);
if (oldVersion < 6) {
sqliteDatabase.execSQL("DROP TABLE IF EXISTS DETAILS");
}
sqliteDatabase
.execSQL("CREATE TABLE IF NOT EXISTS Details (CacheId TEXT PRIMARY KEY, Details TEXT)");
sqliteDatabase.setVersion(DATABASE_VERSION);
}
return sqliteDatabase;
}
}
| 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;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
public class Azimuth {
private double currentAzimuth;
private float[] gravity;
private float[] geomagnetic;
private float rotationMatrix[] = new float[9];
private float identityMatrix[] = new float[9];
private float orientations[] = new float[3];
public Azimuth() {
rotationMatrix = new float[9];
identityMatrix = new float[9];
orientations = new float[9];
}
public void sensorChanged(SensorEvent event) {
boolean sensorReady = false;
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
gravity = event.values.clone();
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
geomagnetic = event.values.clone();
sensorReady = true;
}
if (gravity == null || geomagnetic == null || !sensorReady) {
return;
}
if (!SensorManager.getRotationMatrix(rotationMatrix, identityMatrix, gravity, geomagnetic)) {
return;
}
SensorManager.getOrientation(rotationMatrix, orientations);
currentAzimuth = Math.toDegrees(orientations[0]);
}
public double getAzimuth() {
return currentAzimuth;
}
}
| 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;
public class GpsDisabledLocation implements IGpsLocation {
@Override
public float distanceTo(IGpsLocation dest) {
return Float.MAX_VALUE;
}
@Override
public float distanceToGpsEnabledLocation(GpsEnabledLocation gpsEnabledLocation) {
return Float.MAX_VALUE;
}
}
| 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;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class OnClickCancelListener implements OnClickListener {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}
| 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;
import android.content.Context;
import android.preference.DialogPreference;
import android.provider.SearchRecentSuggestions;
import android.util.AttributeSet;
/**
* The {@link ClearSuggestionHistoryPreference} is a preference to show a dialog
* with Yes and No buttons.
* <p>
* This preference will store a boolean into the SharedPreferences.
*/
public class ClearSuggestionHistoryPreference extends DialogPreference {
public ClearSuggestionHistoryPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (callChangeListener(positiveResult) && positiveResult) {
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this.getContext(),
SuggestionProvider.AUTHORITY, SuggestionProvider.MODE);
suggestions.clearHistory();
}
}
}
| 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;
import com.google.code.geobeagle.activity.cachelist.CacheListModule;
import com.google.code.geobeagle.activity.cachelist.model.ModelModule;
import com.google.code.geobeagle.activity.compass.CompassActivityModule;
import com.google.code.geobeagle.activity.map.click.MapModule;
import com.google.code.geobeagle.bcaching.BCachingModule;
import com.google.code.geobeagle.database.DatabaseModule;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetModule;
import com.google.code.geobeagle.location.LocationModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;
import roboguice.application.GuiceApplication;
import roboguice.config.AbstractAndroidModule;
import java.util.ArrayList;
import java.util.List;
public class GeoBeagleApplication extends GuiceApplication {
public static Timing timing = new Timing();
@Override
protected Injector createInjector() {
ArrayList<Module> modules = new ArrayList<Module>();
Module roboguiceModule = new FasterRoboGuiceModule(contextScope, throwingContextProvider,
contextProvider, resourceListener, viewListener, extrasListener, this);
modules.add(roboguiceModule);
addApplicationModules(modules);
for (Module m : modules) {
if (m instanceof AbstractAndroidModule) {
((AbstractAndroidModule)m).setStaticTypeListeners(staticTypeListeners);
}
}
return Guice.createInjector(Stage.DEVELOPMENT, modules);
}
@Override
protected void addApplicationModules(List<Module> modules) {
timing.start();
// Debug.startMethodTracing("dmtrace", 32 * 1024 * 1024);
modules.add(new CompassActivityModule()); // +1 second (11.0)
modules.add(new GeoBeaglePackageModule());
modules.add(new DatabaseModule());
modules.add(new CacheListModule());
modules.add(new LocationModule());
modules.add(new ModelModule());
modules.add(new GpsStatusWidgetModule());
modules.add(new BCachingModule());
modules.add(new MapModule());
}
}
| 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;
import com.google.code.geobeagle.activity.cachelist.CacheListActivity;
import com.google.inject.Inject;
import android.app.Activity;
import android.content.Intent;
public class CacheListActivityStarterPreHoneycomb implements CacheListActivityStarter {
private Activity activity;
@Inject
CacheListActivityStarterPreHoneycomb(Activity activity) {
this.activity = activity;
}
@Override
public void start() {
activity.startActivity(new Intent(activity, CacheListActivity.class));
}
}
| 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;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matcher;
@SuppressWarnings("unchecked")
class ClassToTypeLiteralMatcherAdapter extends AbstractMatcher<TypeLiteral> {
protected final Matcher<Class> classMatcher;
public ClassToTypeLiteralMatcherAdapter(Matcher<Class> classMatcher) {
this.classMatcher = classMatcher;
}
public boolean matches(TypeLiteral typeLiteral) {
return classMatcher.matches(typeLiteral.getRawType());
}
}
| 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;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.ContextMenu.ContextMenuInfo;
public class MenuActionStub implements MenuItem {
@Override
public char getAlphabeticShortcut() {
return 0;
}
@Override
public int getGroupId() {
return 0;
}
@Override
public Drawable getIcon() {
return null;
}
@Override
public Intent getIntent() {
return null;
}
@Override
public int getItemId() {
return 7;
}
@Override
public ContextMenuInfo getMenuInfo() {
return null;
}
@Override
public char getNumericShortcut() {
return 0;
}
@Override
public int getOrder() {
return 0;
}
@Override
public SubMenu getSubMenu() {
return null;
}
@Override
public CharSequence getTitle() {
return null;
}
@Override
public CharSequence getTitleCondensed() {
return null;
}
@Override
public boolean hasSubMenu() {
return false;
}
@Override
public boolean isCheckable() {
return false;
}
@Override
public boolean isChecked() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
@Override
public boolean isVisible() {
return false;
}
@Override
public MenuItem setAlphabeticShortcut(char alphaChar) {
return null;
}
@Override
public MenuItem setCheckable(boolean checkable) {
return null;
}
@Override
public MenuItem setChecked(boolean checked) {
return null;
}
@Override
public MenuItem setEnabled(boolean enabled) {
return null;
}
@Override
public MenuItem setIcon(Drawable icon) {
return null;
}
@Override
public MenuItem setIcon(int iconRes) {
return null;
}
@Override
public MenuItem setIntent(Intent intent) {
return null;
}
@Override
public MenuItem setNumericShortcut(char numericChar) {
return null;
}
@Override
public MenuItem setOnMenuItemClickListener(
OnMenuItemClickListener menuItemClickListener) {
return null;
}
@Override
public MenuItem setShortcut(char numericChar, char alphaChar) {
return null;
}
@Override
public MenuItem setTitle(CharSequence title) {
return null;
}
@Override
public MenuItem setTitle(int title) {
return null;
}
@Override
public MenuItem setTitleCondensed(CharSequence title) {
return null;
}
@Override
public MenuItem setVisible(boolean visible) {
return null;
}
} | 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.main;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.Smoke;
import android.view.KeyEvent;
public class GeoBeagleActivityTest extends
ActivityInstrumentationTestCase2<GeoBeagle> {
private GeoBeagle geoBeagle;
private Instrumentation instrumentation;
public GeoBeagleActivityTest() {
super("com.google.code.geobeagle", GeoBeagle.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
geoBeagle = getActivity();
instrumentation = getInstrumentation();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
getActivity().finish();
}
@Smoke
public void testCreate() {
assertNotNull(geoBeagle.locationControlBuffered);
assertNotNull(geoBeagle.activitySaver);
getInstrumentation().waitForIdleSync();
}
@Smoke
public void testMenuSettings() throws InterruptedException {
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_RIGHT);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);
Thread.sleep(2000);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
}
public void testMenuCacheList() throws InterruptedException {
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_UP);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);
Thread.sleep(2000);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
}
}
| 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.cachelist;
import com.google.code.geobeagle.R;
import org.easymock.EasyMock;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.view.KeyEvent;
import android.view.MenuItem;
public class CacheListActivityTest extends
ActivityInstrumentationTestCase2<CacheListActivity> {
private CacheListActivity cacheListActivity;
private Instrumentation instrumentation;
private MenuItem item;
public CacheListActivityTest() {
super("com.google.code.geobeagle", CacheListActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
instrumentation = getInstrumentation();
item = EasyMock.createMock(MenuItem.class);
cacheListActivity = getActivity();
}
public void testAddMyLocation() throws InterruptedException {
EasyMock.expect(item.getItemId()).andReturn(
R.string.menu_add_my_location);
EasyMock.replay(item);
cacheListActivity.onOptionsItemSelected(item);
EasyMock.verify(item);
instrumentation.waitForIdleSync();
Thread.sleep(2000);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
}
public void testSearchOnline() throws InterruptedException {
EasyMock.expect(item.getItemId())
.andReturn(R.string.menu_search_online);
EasyMock.replay(item);
cacheListActivity.onOptionsItemSelected(item);
EasyMock.verify(item);
instrumentation.waitForIdleSync();
Thread.sleep(2000);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
}
public void testShowMap() throws InterruptedException {
EasyMock.expect(item.getItemId()).andReturn(R.string.menu_map);
EasyMock.replay(item);
cacheListActivity.onOptionsItemSelected(item);
EasyMock.verify(item);
instrumentation.waitForIdleSync();
Thread.sleep(2000);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
}
public void testShowAllCaches() throws InterruptedException {
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_LEFT);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_ENTER);
Thread.sleep(2000);
}
public void testSync() {
EasyMock.expect(item.getItemId()).andReturn(R.string.menu_sync);
EasyMock.replay(item);
cacheListActivity.onOptionsItemSelected(item);
EasyMock.verify(item);
instrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
instrumentation.waitForIdleSync();
}
}
| 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.searchonline;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.ActivityRestorer;
import com.google.code.geobeagle.activity.MenuActionStub;
import android.content.Context;
import android.test.ActivityInstrumentationTestCase2;
public class SearchOnlineActivityTest extends
ActivityInstrumentationTestCase2<SearchOnlineActivity> {
public SearchOnlineActivityTest() {
super("com.google.code.geobeagle", SearchOnlineActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
public void testCreate() {
final SearchOnlineActivity searchOnlineActivity = getActivity();
assertNotNull(searchOnlineActivity.getDistanceFormatterManager());
assertNotNull(searchOnlineActivity.getGpsWidgetAndUpdater());
assertNotNull(searchOnlineActivity.getCombinedLocationListener());
assertNotNull(searchOnlineActivity.getHelpContentsView());
assertEquals(R.id.help_contents, searchOnlineActivity
.getHelpContentsView().getId());
ActivityRestorer activityRestorer = searchOnlineActivity
.getActivityRestorer();
assertNotNull(activityRestorer);
assertEquals(searchOnlineActivity.getBaseContext()
.getSharedPreferences("GeoBeagle", Context.MODE_PRIVATE),
activityRestorer.getSharedPreferences());
assertNotNull(searchOnlineActivity.getJsInterface());
final MenuActionStub menuActionStub = new MenuActionStub();
getInstrumentation()
.addMonitor(searchOnlineActivity.getClass().getCanonicalName(),
null, false);
getInstrumentation().runOnMainSync(new Runnable() {
public void run() {
searchOnlineActivity.onOptionsItemSelected(menuActionStub);
}
});
getInstrumentation().waitForIdleSync();
}
}
| 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.
*/
/*
* maps.jar doesn't include all its dependencies; fake them out here for testing.
*/
package android.widget;
public class ZoomButtonsController {
}
| 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.compass.view;
import android.text.Editable;
import android.text.InputFilter;
class StubEditable implements Editable {
private final String mString;
public StubEditable(String s) {
mString = s;
}
public Editable append(char arg0) {
return null;
}
public Editable append(CharSequence arg0) {
return null;
}
public Editable append(CharSequence arg0, int arg1, int arg2) {
return null;
}
public char charAt(int index) {
return mString.charAt(index);
}
public void clear() {
}
public void clearSpans() {
}
public Editable delete(int arg0, int arg1) {
return null;
}
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) {
mString.getChars(srcBegin, srcEnd, dst, dstBegin);
}
public InputFilter[] getFilters() {
return null;
}
public int getSpanEnd(Object arg0) {
return 0;
}
public int getSpanFlags(Object arg0) {
return 0;
}
public <T> T[] getSpans(int arg0, int arg1, Class<T> arg2) {
return null;
}
public int getSpanStart(Object arg0) {
return 0;
}
public Editable insert(int arg0, CharSequence arg1) {
return null;
}
public Editable insert(int arg0, CharSequence arg1, int arg2, int arg3) {
return null;
}
public int length() {
return mString.length();
}
@SuppressWarnings("unchecked")
public int nextSpanTransition(int arg0, int arg1, Class arg2) {
return 0;
}
public void removeSpan(Object arg0) {
}
public Editable replace(int arg0, int arg1, CharSequence arg2) {
return null;
}
public Editable replace(int arg0, int arg1, CharSequence arg2, int arg3, int arg4) {
return null;
}
public void setFilters(InputFilter[] arg0) {
}
public void setSpan(Object arg0, int arg1, int arg2, int arg3) {
}
public CharSequence subSequence(int start, int end) {
return mString.subSequence(start, end);
}
@Override
public String toString() {
return mString;
}
}
| 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.database;
import android.content.ContentValues;
import android.database.Cursor;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
class DesktopSQLiteDatabase implements ISQLiteDatabase {
DesktopSQLiteDatabase() {
File db = new File("GeoBeagle.db");
db.delete();
}
@Override
public void beginTransaction() {
}
@Override
public void close() {
}
@Override
public int countResults(String table, String sql, String... args) {
return 0;
}
public String dumpSchema() {
return DesktopSQLiteDatabase.exec(".schema");
}
public String dumpTable(String table) {
return DesktopSQLiteDatabase.exec("SELECT * FROM " + table);
}
@Override
public void endTransaction() {
}
@Override
public void execSQL(String s, Object... bindArg1) {
if (bindArg1.length > 0)
throw new UnsupportedOperationException("bindArgs not yet supported");
System.out.print(DesktopSQLiteDatabase.exec(s));
}
@Override
public Cursor query(String table, String[] columns, String selection, String groupBy,
String having, String orderBy, String limit, String... selectionArgs) {
return null;
}
@Override
public Cursor rawQuery(String string, String[] object) {
// TODO Auto-generated method stub
return null;
}
@Override
public void setTransactionSuccessful() {
}
@Override
public boolean isOpen() {
// TODO Auto-generated method stub
return false;
}
@Override
public void delete(String table, String where, String bindArg) {
exec("DELETE FROM " + table + " WHERE " + where + "='" + bindArg + "'");
}
@Override
public void insert(String table, String[] columns, Object[] bindArgs) {
// Assumes len(bindArgs) > 0.
StringBuilder columnsAsString = new StringBuilder();
for (String column : columns) {
columnsAsString.append(", ");
columnsAsString.append(column);
}
StringBuilder values = new StringBuilder();
for (Object bindArg : bindArgs) {
values.append(", ");
values.append("'" + bindArg + "'");
}
values.substring(2);
exec("REPLACE INTO " + table + "( " + columnsAsString.substring(2) + ") VALUES ("
+ values.substring(2) + ")");
}
@Override
public boolean hasValue(String table, String[] columns, String[] selectionArgs) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" WHERE " + columns[0] + "=");
stringBuilder.append("'" + selectionArgs[0] + "'");
for (int ix = 1; ix < columns.length; ix++) {
stringBuilder.append(" AND ");
stringBuilder.append(columns[ix]);
stringBuilder.append("=");
stringBuilder.append("'" + selectionArgs[ix] + "'");
}
String s = "SELECT COUNT(*) FROM " + table + stringBuilder.toString();
String result = exec(s);
return Integer.parseInt(result.trim()) != 0;
}
/**
* <pre>
*
* version 8
* same as version 7 but rebuilds everything because a released version mistakenly puts
* *intent* into imported caches.
*
* version 9
* fixes bug where INDEX wasn't being created on upgrade.
*
* version 10
* adds GPX table
*
* version 11
* adds new CACHES columns: CacheType, Difficulty, Terrain, and Container
*
* version 12: 4/21/2010
* adds new TAGS table:
* </pre>
*
* @throws IOException
*/
static String convertStreamToString(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
return sb.toString();
}
static String exec(String s) {
String output = null;
try {
ProcessBuilder processBuilder = new ProcessBuilder("sqlite3", "GeoBeagle.db", s);
processBuilder.redirectErrorStream(true);
InputStream shellIn = null;
Process shell = processBuilder.start();
shellIn = shell.getInputStream();
int result = shell.waitFor();
output = DesktopSQLiteDatabase.convertStreamToString(shellIn);
if (result != 0)
throw (new RuntimeException(output));
} catch (InterruptedException e) {
throw (new RuntimeException(e + "\n" + output));
} catch (IOException e) {
throw (new RuntimeException(e + "\n" + output));
}
return output;
}
@Override
public Cursor query(String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit) {
// TODO Auto-generated method stub
return null;
}
@Override
public void update(String string,
ContentValues contentValues,
String whereClause,
String[] strings) {
// TODO Auto-generated method stub
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dbcreator.common;
/**
* @author yrtimid
*
*/
public interface INotificationManager {
public abstract void notify(int id, Notification2 notification);
} | Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dbcreator.common;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.logging.Logger;
import il.yrtimid.osm.osmpoi.ImportSettings;
import il.yrtimid.osm.osmpoi.ItemPipe;
import il.yrtimid.osm.osmpoi.dal.IDbCachedFiller;
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.Way;
import il.yrtimid.osm.osmpoi.pbf.OsmImporter;
import il.yrtimid.osm.osmpoi.pbf.ProgressNotifier;
/**
* @author yrtimid
*
*/
public class DbCreator {
static final int IMPORT_TO_DB = 1;
public static final int BUILD_GRID = 40;
INotificationManager notificationManager;
IDbCachedFiller poiDbHelper;
IDbCachedFiller addressDbHelper;
private static final Logger LOG = Logger.getLogger(DbCreator.class.getName());
/**
*
*/
public DbCreator(IDbCachedFiller poiDB, IDbCachedFiller addrDB, INotificationManager notificationManager) {
this.poiDbHelper = poiDB;
this.addressDbHelper = addrDB;
this.notificationManager = notificationManager;
}
/**
* @throws Exception
*
*/
public void createEmptyDatabases() throws Exception {
poiDbHelper.create();
addressDbHelper.create();
}
public void importToDB(String sourceFilePath, ImportSettings settings) {
try {
LOG.finest("Importing file: "+sourceFilePath);
File sourceFile = new File(sourceFilePath);
if ((sourceFile.exists() && sourceFile.canRead())){
long startTime = System.currentTimeMillis();
final Notification2 notif = new Notification2("Importing file into DB", System.currentTimeMillis());
notif.flags |= Notification2.FLAG_ONGOING_EVENT | Notification2.FLAG_NO_CLEAR;
notif.setLatestEventInfo("PBF Import", "Clearing DB...");
notificationManager.notify(IMPORT_TO_DB, notif);
if (settings.isClearBeforeImport()){
poiDbHelper.clearAll();
addressDbHelper.clearAll();
}
notif.setLatestEventInfo("PBF Import", "Importing in progress...");
notificationManager.notify(IMPORT_TO_DB, notif);
InputStream input;
if (settings.isImportRelations()){
input = new BufferedInputStream(new FileInputStream(sourceFile));
importRelations(input, notif, settings);
LOG.finest("Finished importing relations");
}
if (settings.isImportWays()){
input = new BufferedInputStream(new FileInputStream(sourceFile));
importWays(input, notif, settings);
LOG.finest("Finished importing ways");
}
if (settings.isImportNodes()){
input = new BufferedInputStream(new FileInputStream(sourceFile));
importNodes(input, notif, settings);
LOG.finest("Finished importing nodes");
}
notif.setLatestEventInfo("PBF Import", "Post-import calculations...");
notificationManager.notify(IMPORT_TO_DB, notif);
if(settings.isBuildGrid()){
notif.setLatestEventInfo("PBF Import", "Creating grid...");
notificationManager.notify(IMPORT_TO_DB, notif);
poiDbHelper.initGrid();
notif.setLatestEventInfo("PBF Import", "Optimizing grid...");
notificationManager.notify(IMPORT_TO_DB, notif);
poiDbHelper.optimizeGrid(settings.getGridCellSize());
}
long endTime = System.currentTimeMillis();
int workTime = Math.round((endTime-startTime)/1000/60);
Notification2 finalNotif = new Notification2("Importing file into DB", System.currentTimeMillis());
finalNotif.flags |= Notification2.FLAG_AUTO_CANCEL;
finalNotif.setLatestEventInfo("PBF Import", "Import done successfully. ("+workTime+"min.)");
notificationManager.notify(IMPORT_TO_DB, finalNotif);
}else {
Notification2 finalNotif = new Notification2("Importing file into DB", System.currentTimeMillis());
finalNotif.flags |= Notification2.FLAG_AUTO_CANCEL;
finalNotif.setLatestEventInfo("PBF Import", "Import failed. File not found.");
notificationManager.notify(IMPORT_TO_DB, finalNotif);
}
} catch (Exception ex) {
ex.printStackTrace();
LOG.severe("Exception while importing PBF into DB. "+ ex.toString());
}
}
protected Long importRelations(final InputStream input, final Notification2 notif, final ImportSettings settings) {
Long count = 0L;
try{
poiDbHelper.beginAdd();
addressDbHelper.beginAdd();
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);
if (settings.isImportAddresses() && settings.isAddress(item))
addressDbHelper.addEntity(item);
}
}catch(Exception e){
e.printStackTrace();
}
}
}, new ProgressNotifier() {
@Override
public void onProgressChange(Progress progress) {
notif.setLatestEventInfo("PBF Import", "Importing relations: " + progress.toString());
notificationManager.notify(IMPORT_TO_DB, notif);
}
});
if (count == -1L){
notif.setLatestEventInfo("PBF Import", "Relations import failed");
}
poiDbHelper.endAdd();
addressDbHelper.endAdd();
}catch(Exception ex){
ex.printStackTrace();
}
return count;
}
protected Long importWays(final InputStream input, final Notification2 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.isImportRelations()){
Way w = (Way)item;
poiDbHelper.addWayIfBelongsToRelation(w);
}
if (settings.isImportAddresses()){
if (settings.isAddress(item))
addressDbHelper.addEntity(item);
else if (settings.isImportRelations()){
Way w = (Way)item;
addressDbHelper.addWayIfBelongsToRelation(w);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}, new ProgressNotifier() {
@Override
public void onProgressChange(Progress progress) {
notif.setLatestEventInfo("PBF Import", "Importing ways: " + progress.toString());
notificationManager.notify(IMPORT_TO_DB, notif);
}
});
if (count == -1L){
notif.setLatestEventInfo("PBF Import", "Nodes import failed");
}
poiDbHelper.endAdd();
addressDbHelper.endAdd();
return count;
}
protected Long importNodes(final InputStream input, final Notification2 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.Node){
settings.cleanTags(item);
if (settings.isImportAddresses()){
if (settings.isAddress(item))
addressDbHelper.addEntity(item);
else {
Node n = (Node)item;
if (settings.isImportWays()){
addressDbHelper.addNodeIfBelongsToWay(n);
}
if (settings.isImportRelations()){
addressDbHelper.addNodeIfBelongsToRelation(n);
}
}
}
if (settings.isPoi(item))
poiDbHelper.addEntity(item);
else {
Node n = (Node)item;
if (settings.isImportWays()){
poiDbHelper.addNodeIfBelongsToWay(n);
}
if (settings.isImportRelations()){
poiDbHelper.addNodeIfBelongsToRelation(n);
}
}
}else if (item.getType() == EntityType.Bound){
poiDbHelper.addEntity(item);
}
}catch(Exception e){
e.printStackTrace();
}
}
}, new ProgressNotifier() {
@Override
public void onProgressChange(Progress progress) {
notif.setLatestEventInfo("PBF Import", "Importing nodes: " + progress.toString());
notificationManager.notify(IMPORT_TO_DB, notif);
}
});
if (count == -1L){
notif.setLatestEventInfo("PBF Import", "Nodes import failed");
}
addressDbHelper.endAdd();
poiDbHelper.endAdd();
return count;
}
public void rebuildGrid(final ImportSettings settings){
try {
long startTime = System.currentTimeMillis();
final Notification2 notif = new Notification2("Rebuilding grid", System.currentTimeMillis());
notif.flags |= Notification2.FLAG_ONGOING_EVENT | Notification2.FLAG_NO_CLEAR;
notif.setLatestEventInfo("Rebuilding grid", "Clearing old grid...");
notificationManager.notify(BUILD_GRID, notif);
notif.setLatestEventInfo("Rebuilding grid", "Creating grid...");
notificationManager.notify(BUILD_GRID, notif);
poiDbHelper.initGrid();
notif.setLatestEventInfo("Rebuilding grid", "Optimizing grid...");
notificationManager.notify(BUILD_GRID, notif);
poiDbHelper.optimizeGrid(settings.getGridCellSize());
long endTime = System.currentTimeMillis();
int workTime = Math.round((endTime-startTime)/1000/60);
Notification2 finalNotif = new Notification2("Rebuilding grid", System.currentTimeMillis());
finalNotif.flags |= Notification2.FLAG_AUTO_CANCEL;
finalNotif.setLatestEventInfo("Rebuilding grid", "Done successfully. ("+workTime+"min)");
notificationManager.notify(IMPORT_TO_DB, finalNotif);
} catch (Exception ex) {
LOG.severe("Exception while rebuilding grid. "+ex.toString());
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dbcreator.common;
/**
* @author yrtimid
*
*/
public class Notification2 {
public String tickerText;
public String title;
public String text;
public long when;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if you want the LED on for this notification.
* <ul>
* <li>To turn the LED off, pass 0 in the alpha channel for colorARGB
* or 0 for both ledOnMS and ledOffMS.</li>
* <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li>
* <li>To flash the LED, pass the number of milliseconds that it should
* be on and off to ledOnMS and ledOffMS.</li>
* </ul>
* <p>
* Since hardware varies, you are not guaranteed that any of the values
* you pass are honored exactly. Use the system defaults (TODO) if possible
* because they will be set to values that work on any given hardware.
* <p>
* The alpha channel must be set for forward compatibility.
*
*/
public static final int FLAG_SHOW_LIGHTS = 0x00000001;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if this notification is in reference to something that is ongoing,
* like a phone call. It should not be set if this notification is in
* reference to something that happened at a particular point in time,
* like a missed phone call.
*/
public static final int FLAG_ONGOING_EVENT = 0x00000002;
/**
* Bit to be bitwise-ored into the {@link #flags} field that if set,
* the audio will be repeated until the notification is
* cancelled or the notification window is opened.
*/
public static final int FLAG_INSISTENT = 0x00000004;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if you want the sound and/or vibration play each time the
* notification is sent, even if it has not been canceled before that.
*/
public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if the notification should be canceled when it is clicked by the
* user.
*/
public static final int FLAG_AUTO_CANCEL = 0x00000010;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if the notification should not be canceled when the user clicks
* the Clear all button.
*/
public static final int FLAG_NO_CLEAR = 0x00000020;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if this notification represents a currently running service. This
* will normally be set for you by {@link Service#startForeground}.
*/
public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
public int flags;
public Notification2(String tickerText, long when) {
this.tickerText = tickerText;
this.when = when;
}
public void setLatestEventInfo(String title, String text) {
this.title = title;
this.text = text;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.pbf;
/**
* Maintains state about execution progress. It calculates when the next update
* is due, and provides statistics on execution.
*
* @author Brett Henderson
*/
public class ProgressTracker {
private int interval;
private boolean initialized;
private long firstUpdateTimestamp;
private long lastUpdateTimestamp;
private long objectCount;
private double objectsPerSecond;
/**
* Creates a new instance.
*
* @param interval
* The interval between logging progress reports in milliseconds.
*/
public ProgressTracker(int interval) {
this.interval = interval;
initialized = false;
}
/**
* Indicates if an update is due. This should be called once per object that
* is processed.
*
* @return True if an update is due.
*/
public boolean updateRequired() {
if (!initialized) {
lastUpdateTimestamp = System.currentTimeMillis();
firstUpdateTimestamp = System.currentTimeMillis();
objectCount = 0;
objectsPerSecond = 0;
initialized = true;
return false;
} else {
long currentTimestamp;
long duration;
// Calculate the time since the last update.
currentTimestamp = System.currentTimeMillis();
duration = currentTimestamp - lastUpdateTimestamp;
// Increment the processed object count.
objectCount++;
if (duration > interval || duration < 0) {
lastUpdateTimestamp = currentTimestamp;
// Calculate the number of objects processed per second.
objectsPerSecond = (double) objectCount * 1000 / (currentTimestamp-firstUpdateTimestamp);
return true;
} else {
return false;
}
}
}
/**
* Provides the number of objects processed per second. This only becomes
* valid after updateRequired returns true for the first time.
*
* @return The number of objects processed per second in the last timing
* interval.
*/
public double getObjectsPerSecond() {
return objectsPerSecond;
}
}
| Java |
package il.yrtimid.osm.osmpoi.pbf;
import il.yrtimid.osm.osmpoi.ItemPipe;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
public class EntityHandler implements Sink {
ItemPipe<Entity> itemPipe;
int maximumEntries = Integer.MAX_VALUE;
public EntityHandler(ItemPipe<Entity> itemPipe) {
this.itemPipe = itemPipe;
}
public void setMaximumEntries(int max) {
this.maximumEntries = max;
}
@Override
public void complete() {
// TODO Auto-generated method stub
}
@Override
public void release() {
// TODO Auto-generated method stub
}
@Override
public void process(Entity entity) {
if (maximumEntries > 0) {
this.itemPipe.pushItem(entity);
maximumEntries--;
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.pbf;
import org.openstreetmap.osmosis.core.task.v0_6.SinkSource;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
/**
* @author yrtimid
*
*/
public class PeriodicProgressNotifier implements SinkSource {
private Sink sink;
private ProgressTracker progressTracker;
private ProgressNotifier progressNotifier;
private Long count = 0L;
public PeriodicProgressNotifier(int interval, ProgressNotifier notifier) {
progressTracker = new ProgressTracker(interval);
progressNotifier = notifier;
}
public Long getCount(){
return count;
}
public void process(Entity entity) {
count++;
if (progressTracker.updateRequired() && progressNotifier != null) {
progressNotifier.onProgressChange(new ProgressNotifier.Progress(count, (int)progressTracker.getObjectsPerSecond()+ " obj/sec"));
}
sink.process(entity);
}
public void complete() {
if (progressNotifier != null){
progressNotifier.onProgressChange(new ProgressNotifier.Progress(count, count, (int)progressTracker.getObjectsPerSecond()+ " obj/sec"));
}
sink.complete();
}
public void release() {
sink.release();
}
public void setSink(Sink sink) {
this.sink = sink;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.pbf;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.Tag;
import il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher;
/**
* @author yrtimid
*
*/
public class EntityMatcher {
TagMatcher tagMatcher;
public EntityMatcher(TagMatcher tagMatcher) {
this.tagMatcher = tagMatcher;
}
public boolean isMatch(Entity entity){
for(Tag t:entity.getTags()){
if (tagMatcher.isMatch(t.getKey(), t.getValue()))
return true;
}
return false;
}
}
| Java |
package il.yrtimid.osm.osmpoi.pbf;
import il.yrtimid.osm.osmpoi.ItemPipe;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.NullSink;
import java.io.InputStream;
import crosby.binary.file.BlockInputStream;
import crosby.binary.osmosis.OsmosisBinaryParser;
public class OsmImporter {
public static Long countEntities(InputStream input, ProgressNotifier progressNotifier){
Long result = 0L;
try {
OsmosisBinaryParser parser = new OsmosisBinaryParser();
PeriodicProgressNotifier counter = new PeriodicProgressNotifier(5000, progressNotifier);
parser.setSink(counter);
counter.setSink(new NullSink());
BlockInputStream stream = new BlockInputStream(input, parser);
stream.process();
stream.close();
result = counter.getCount();
}catch(Exception ioe){
ioe.printStackTrace();
result = -1L;
}
return result;
}
public static Long processAll(InputStream input, ItemPipe<Entity> newItemNotifier, ProgressNotifier progressNotifier){
Long result = 0L;
try {
OsmosisBinaryParser parser = new OsmosisBinaryParser();
PeriodicProgressNotifier counter = new PeriodicProgressNotifier(5000, progressNotifier);
EntityHandler handler = new EntityHandler(newItemNotifier);
parser.setSink(counter);
counter.setSink(handler);
BlockInputStream stream = new BlockInputStream(input, parser);
stream.process();
stream.close();
result = counter.getCount();
}catch(Exception ioe){
ioe.printStackTrace();
result = -1L;
}
return result;
}
}
| Java |
package il.yrtimid.osm.osmpoi.pbf;
public interface ProgressNotifier {
public void onProgressChange(Progress newProgress);
public class Progress{
private Long count;
private String message;
private Long maximum;
public Progress(Long count){
this.count = count;
}
public Progress(Long count, Long maximum){
this.count = count;
this.maximum = maximum;
}
public Progress(Long count, String message){
this.count = count;
this.message = message;
}
public Progress(Long count, Long maximum, String message){
this.count = count;
this.maximum = maximum;
this.message = message;
}
public Progress(String message){
this.message = message;
}
public Long getCount(){return count;}
public String getMessage(){return message;}
public Long getMaximum(){return maximum;}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder();
if (count != null) b.append(count);
if (maximum != null) b.append("/").append(maximum);
if (message != null) b.append("; ").append(message);
return b.toString();
}
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package crosby.binary.osmosis;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.openstreetmap.osmosis.core.OsmosisConstants;
import org.openstreetmap.osmosis.core.OsmosisRuntimeException;
import crosby.binary.BinaryParser;
import crosby.binary.Osmformat;
import crosby.binary.Osmformat.DenseInfo;
/** Class that reads and parses binary files and sends the contained entities to the sink. */
public class OsmosisBinaryParser extends BinaryParser {
@Override
public void complete() {
sink.complete();
sink.release();
}
/** The magic number used to indicate no version number metadata for this entity. */
static final int NOVERSION = -1;
/** The magic number used to indicate no changeset metadata for this entity. */
static final int NOCHANGESET = -1;
@Override
protected void parseNodes(List<Osmformat.Node> nodes) {
for (Osmformat.Node i : nodes) {
List<Tag> tags = new ArrayList<Tag>();
for (int j = 0; j < i.getKeysCount(); j++) {
tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j))));
}
// long id, int version, Date timestamp, OsmUser user,
// long changesetId, Collection<Tag> tags,
// double latitude, double longitude
Node tmp;
long id = i.getId();
double latf = parseLat(i.getLat()), lonf = parseLon(i.getLon());
if (i.hasInfo()) {
Osmformat.Info info = i.getInfo();
tmp = new Node(new CommonEntityData(id, getDate(info), tags), latf, lonf);
} else {
tmp = new Node(new CommonEntityData(id, NODATE, tags), latf, lonf);
}
sink.process(tmp);
}
}
@Override
protected void parseDense(Osmformat.DenseNodes nodes) {
long lastId = 0, lastLat = 0, lastLon = 0;
int j = 0; // Index into the keysvals array.
// Stuff for dense info
long lasttimestamp = 0, lastchangeset = 0;
int lastuserSid = 0, lastuid = 0;
DenseInfo di = null;
if (nodes.hasDenseinfo()) {
di = nodes.getDenseinfo();
}
for (int i = 0; i < nodes.getIdCount(); i++) {
Node tmp;
List<Tag> tags = new ArrayList<Tag>(0);
long lat = nodes.getLat(i) + lastLat;
lastLat = lat;
long lon = nodes.getLon(i) + lastLon;
lastLon = lon;
long id = nodes.getId(i) + lastId;
lastId = id;
double latf = parseLat(lat), lonf = parseLon(lon);
// If empty, assume that nothing here has keys or vals.
if (nodes.getKeysValsCount() > 0) {
while (nodes.getKeysVals(j) != 0) {
int keyid = nodes.getKeysVals(j++);
int valid = nodes.getKeysVals(j++);
tags.add(new Tag(getStringById(keyid), getStringById(valid)));
}
j++; // Skip over the '0' delimiter.
}
// Handle dense info.
if (di != null) {
int uid = di.getUid(i) + lastuid; lastuid = uid;
int userSid = di.getUserSid(i) + lastuserSid; lastuserSid = userSid;
long timestamp = di.getTimestamp(i) + lasttimestamp; lasttimestamp = timestamp;
@SuppressWarnings("unused")
int version = di.getVersion(i);
long changeset = di.getChangeset(i) + lastchangeset; lastchangeset = changeset;
Date date = new Date(date_granularity * timestamp);
tmp = new Node(new CommonEntityData(id, date, tags), latf, lonf);
} else {
tmp = new Node(new CommonEntityData(id, NODATE, tags), latf, lonf);
}
sink.process(tmp);
}
}
@Override
protected void parseWays(List<Osmformat.Way> ways) {
for (Osmformat.Way i : ways) {
List<Tag> tags = new ArrayList<Tag>();
for (int j = 0; j < i.getKeysCount(); j++) {
tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j))));
}
long lastId = 0;
List<Node> nodes = new ArrayList<Node>();
for (long j : i.getRefsList()) {
nodes.add(new Node(j + lastId));
lastId = j + lastId;
}
long id = i.getId();
// long id, int version, Date timestamp, OsmUser user,
// long changesetId, Collection<Tag> tags,
// List<WayNode> wayNodes
Way tmp;
if (i.hasInfo()) {
Osmformat.Info info = i.getInfo();
tmp = new Way(new CommonEntityData(id, getDate(info), tags), nodes);
} else {
tmp = new Way(new CommonEntityData(id, NODATE, tags), nodes);
}
sink.process(tmp);
}
}
@Override
protected void parseRelations(List<Osmformat.Relation> rels) {
for (Osmformat.Relation i : rels) {
List<Tag> tags = new ArrayList<Tag>();
for (int j = 0; j < i.getKeysCount(); j++) {
tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j))));
}
long id = i.getId();
long lastMid = 0;
List<RelationMember> nodes = new ArrayList<RelationMember>();
for (int j = 0; j < i.getMemidsCount(); j++) {
long mid = lastMid + i.getMemids(j);
lastMid = mid;
String role = getStringById(i.getRolesSid(j));
EntityType etype = null;
if (i.getTypes(j) == Osmformat.Relation.MemberType.NODE) {
etype = EntityType.Node;
} else if (i.getTypes(j) == Osmformat.Relation.MemberType.WAY) {
etype = EntityType.Way;
} else if (i.getTypes(j) == Osmformat.Relation.MemberType.RELATION) {
etype = EntityType.Relation;
} else {
assert false; // TODO; Illegal file?
}
nodes.add(new RelationMember(mid, etype, role));
}
// long id, int version, TimestampContainer timestampContainer,
// OsmUser user,
// long changesetId, Collection<Tag> tags,
// List<RelationMember> members
Relation tmp;
if (i.hasInfo()) {
Osmformat.Info info = i.getInfo();
tmp = new Relation(new CommonEntityData(id, getDate(info), tags), nodes);
} else {
tmp = new Relation(new CommonEntityData(id, NODATE, tags), nodes);
}
sink.process(tmp);
}
}
@Override
public void parse(Osmformat.HeaderBlock block) {
for (String s : block.getRequiredFeaturesList()) {
if (s.equals("OsmSchema-V0.6")) {
continue; // We can parse this.
}
if (s.equals("DenseNodes")) {
continue; // We can parse this.
}
throw new OsmosisRuntimeException("File requires unknown feature: " + s);
}
if (block.hasBbox()) {
String source = OsmosisConstants.VERSION;
if (block.hasSource()) {
source = block.getSource();
}
double multiplier = .000000001;
double rightf = block.getBbox().getRight() * multiplier;
double leftf = block.getBbox().getLeft() * multiplier;
double topf = block.getBbox().getTop() * multiplier;
double bottomf = block.getBbox().getBottom() * multiplier;
Bound bounds = new Bound(rightf, leftf, topf, bottomf, source);
sink.process(bounds);
}
}
/**
* {@inheritDoc}
*/
public void setSink(Sink sink) {
this.sink = sink;
}
private Sink sink;
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
@SuppressWarnings("serial")
public class SortedProperties extends Properties {
/**
* Overrides, called by the store method.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public synchronized Enumeration keys() {
Enumeration keysEnum = super.keys();
Vector keyList = new Vector();
while(keysEnum.hasMoreElements()){
keyList.add(keysEnum.nextElement());
}
Collections.sort(keyList);
return keyList.elements();
}
}
| Java |
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
public class AndMatcher extends BinaryMatcher {
public AndMatcher(TagMatcher left, TagMatcher right) {
this.left = left;
this.right = right;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return left.isMatch(key,value) && right.isMatch(key,value);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
return left.isMatch(entity) && right.isMatch(entity);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.tagmatchers;
import java.util.ArrayList;
import java.util.List;
/**
* @author yrtimid
*
*/
public abstract class BinaryMatcher extends TagMatcher {
protected TagMatcher left;
protected TagMatcher right;
public TagMatcher getLeft() {
return left;
}
public TagMatcher getRight() {
return right;
}
/**
* Returns all sibling items of same operator. For ex: ((a|b)|(c&d)|e) will return a,b,(c&d),e
* @return
*/
public List<TagMatcher> getAllSiblings() {
List<TagMatcher> list = new ArrayList<TagMatcher>();
getAllSiblings(this, list);
return list;
}
private void getAllSiblings(BinaryMatcher matcher, List<TagMatcher> list) {
if (this.getClass().isInstance(matcher.left))
getAllSiblings((BinaryMatcher)matcher.left, list);
else
list.add(matcher.left);
if (this.getClass().isInstance(matcher.right))
getAllSiblings((BinaryMatcher)matcher.right, list);
else
list.add(matcher.right);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.domain.EntityType;
/**
* @author yrtimid
*
*/
public class AssociatedMatcher extends TagMatcher {
EntityType entityType;
Long id;
public AssociatedMatcher(EntityType type, Long id) {
this.entityType = type;
this.id = id;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return false;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
switch (entity.getType()){
case Node:
break;
case Way:
if (this.entityType.equals(EntityType.Node)){
for(Node n : ((Way)entity).getNodes()){
if (n.getId() == id) return true;
}
}
break;
case Relation:
for(RelationMember m : ((Relation)entity).getMembers()){
if (this.entityType.equals(m.getMemberType()) && this.id == m.getMemberId()) return true;
}
break;
}
return false;
}
/**
* @return the entityType
*/
public EntityType getEntityType() {
return entityType;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
}
| Java |
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
public class OrMatcher extends BinaryMatcher {
public OrMatcher(TagMatcher left, TagMatcher right) {
this.left = left;
this.right = right;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return left.isMatch(key, value) || right.isMatch(key, value);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
return left.isMatch(entity) || right.isMatch(entity);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.EntityType;
/**
* @author yrtimid
*
*/
public class IdMatcher extends TagMatcher {
EntityType entityType;
Long id;
public IdMatcher(EntityType type, Long id) {
this.entityType = type;
this.id = id;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return false;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
return entity.getType() == entityType && entity.getId() == id;
}
/**
* @return the entityType
*/
public EntityType getEntityType() {
return entityType;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
}
| Java |
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
public class NotMatcher extends TagMatcher {
TagMatcher matcher;
public NotMatcher(TagMatcher matcher) {
this.matcher = matcher;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return !matcher.isMatch(key, value);
}
public TagMatcher getMatcher(){
return matcher;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
return !matcher.isMatch(entity);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;
/**
* Base class for all entity filters
*
* @author yrtimiD
*/
public abstract class TagMatcher {
public abstract Boolean isMatch(CharSequence key, CharSequence value);
public static TagMatcher parse(CharSequence expression) throws InvalidParameterException {
String e = expression.toString();
if (e.length() == 0)
return new KeyValueMatcher("*", "*");
//trim braces
if (e.startsWith(Character.toString(OPEN_BRACE)) && e.endsWith(Character.toString(CLOSE_BRACE))){
e = e.substring(1, e.length()-1);
}
char op = '&';
String[] parts = splitBy(e, op);// (X | Y) & Z will become "(X | Y)", "Z"
if (parts.length == 1){
op = '|';
parts = splitBy(e, op);// (X & Y) | Z will become "(X & Y)", "Z"
}
if (parts.length == 1){
op = '!';
parts = splitBy(e, op);// !(X & Y) will become "", "(X & Y)"
}
if (parts.length == 1){
op = '=';
parts = splitBy(e, op);// X=Y Z will become "X", "Y Z"
}
if (parts.length == 1) { //no &,|,=
if (!e.contains("*")) e = "*"+e+"*";
return new KeyValueMatcher("*", e);
}else if (parts.length == 2 && op == '='){
if (parts[0].toLowerCase().equals("node_id"))
return new IdMatcher(EntityType.Node, Long.parseLong(parts[1]));
else if (parts[0].toLowerCase().equals("way_id"))
return new IdMatcher(EntityType.Way, Long.parseLong(parts[1]));
else if (parts[0].toLowerCase().equals("relation_id"))
return new IdMatcher(EntityType.Relation, Long.parseLong(parts[1]));
else
return new KeyValueMatcher(parts[0], parts[1]);
} else if (parts.length == 2 && op == '!') {
return new NotMatcher(parse(parts[1]));
} else {
if ((op=='&') || (op=='|')) {
TagMatcher left = parse(parts[0]);
for (int i = 1; i < parts.length; i++) { //operator index
TagMatcher right = parse(parts[i]);
if (op == '&'){
left = new AndMatcher(left, right);
} else if (op=='|'){
left = new OrMatcher(left, right);
} else {
throw new IllegalArgumentException("something goes wrong while parsing '"+e+"'");
}
}
return left;
}
else {
throw new InvalidParameterException("Unknown operator "+parts[1]+" in '"+e+"'");
}
}
}
enum States
{
NORMAL_PROGRESS,
MATCHING_BRACE_SEARCHING,
FOUND_END_OF_PART
}
private static final char OPEN_BRACE = '(';
private static final char CLOSE_BRACE = ')';
public static String[] splitBy(String expression, char separator)
{
List<String> parts = new ArrayList<String>();
States state = States.NORMAL_PROGRESS;
int index = 0;
int braces = 0;
boolean canProgress = true;
boolean canAppend = true;
StringBuilder currentPart = new StringBuilder();
while (index < expression.length())
{
char c = expression.charAt(index);
canProgress = true;
canAppend = true;
switch (state)
{
case NORMAL_PROGRESS:
if (c == OPEN_BRACE)
{
state = States.MATCHING_BRACE_SEARCHING;
braces++;
}
else if (c == separator)
{
state = States.FOUND_END_OF_PART;
canProgress = false;
canAppend = false;
}
break;
case MATCHING_BRACE_SEARCHING:
if (c == OPEN_BRACE)
braces++;
if (c == CLOSE_BRACE)
braces--;
if (braces == 0)
state = States.NORMAL_PROGRESS;
break;
case FOUND_END_OF_PART:
parts.add(currentPart.toString().trim());
currentPart.delete(0, currentPart.length());
state = States.NORMAL_PROGRESS;
canAppend = false;
break;
default:
break;
}
if (canAppend)
currentPart.append(c);
if (canProgress)
index++;
}
parts.add(currentPart.toString().trim());
return parts.toArray(new String[parts.size()]);
}
public abstract Boolean isMatch(Entity entity);
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return this.toString().equals(obj.toString());
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.toString().hashCode();
}
}
| Java |
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.Tag;
public class KeyValueMatcher extends TagMatcher {
private String k;
private String v;
/**
* Creates new matcher which will match tags with exact name of the key and
* exact value '*' may be used to match any key or any value. Example: *=* -
* matches all nodes with at least one tag name=* - matches nodes which has
* name tag with any value *=test - matches nodes which has any tag with the
* "test" value
*
* @param key
* - '*' for any
* @param value
* - '*' for any
*/
public KeyValueMatcher(String key, String value) {
this.k = key.replace('%', '*');
this.v = value.replace('%', '*');
}
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return (isMatchPattern(key, k) && isMatchPattern(value, v));
}
private Boolean isMatchPattern(CharSequence value, CharSequence pattern) {
String pat = pattern.toString();
if (pattern.equals("*"))
return true;
boolean isExactMatch = !pat.contains("*");
boolean isBegins = false, isEnds = false, isContains = false;
if (pat.startsWith("*")) {
isBegins = true;
pat = pat.substring(1);
}
if (pat.endsWith("*")) {
isEnds = true;
pat = pat.substring(0, pat.length() - 1);
}
if (isBegins && isEnds) {
isContains = true;
isBegins = false;
isEnds = false;
}
if (isExactMatch) {
return value.toString().equalsIgnoreCase(pat);
}
else {
if (isBegins)
return value.toString().toLowerCase().startsWith(pat.toLowerCase());
else if (isEnds)
return value.toString().toLowerCase().endsWith(pat.toLowerCase());
else if (isContains)
return value.toString().toLowerCase().contains(pat.toLowerCase());
}
return false;
}
public String getKey() {
return k;
}
public String getValue() {
return v;
}
public boolean isKeyExactMatch() {
return !(k.contains("*"));
}
public boolean isValueExactMatch() {
return !(v.contains("*"));
}
/*
* (non-Javadoc)
*
* @see
* il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi
* .domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
for (Tag t : entity.getTags()) {
if (isMatch(t.getKey(), t.getValue()))
return true;
}
return false;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "key:"+k+"=value:"+v;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import il.yrtimid.osm.osmpoi.domain.Tag;
import il.yrtimid.osm.osmpoi.tagmatchers.KeyValueMatcher;
import il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher;
/**
* @author yrtimid
*
*/
public class ImportSettings {
HashMap<EntityType, List<KeyValueMatcher>> tagsInclude = new HashMap<EntityType, List<KeyValueMatcher>>();// allowed tags by entity
HashMap<EntityType, List<KeyValueMatcher>> tagsExclude = new HashMap<EntityType, List<KeyValueMatcher>>();// forbidden tags by entity
HashMap<EntityType, HashSet<KeyValueMatcher>> addressTags = new HashMap<EntityType, HashSet<KeyValueMatcher>>();// matchers collection to check if entity may be used for address search
HashSet<String> excludedKeys = new HashSet<String>(); // these keys will not be imported
// boolean onlyWithTags = false; // if entity have no tags - it will be excluded
Boolean isBuildGrid = true;
Boolean isClearBeforeImport = true;
Boolean importAddresses = false;
Integer gridCellSize = Integer.MAX_VALUE;
public ImportSettings() {
excludedKeys.add("created_by");
excludedKeys.add("source");
tagsInclude.put(EntityType.Node, new ArrayList<KeyValueMatcher>());
tagsInclude.put(EntityType.Way, new ArrayList<KeyValueMatcher>());
tagsInclude.put(EntityType.Relation, new ArrayList<KeyValueMatcher>());
tagsExclude.put(EntityType.Node, new ArrayList<KeyValueMatcher>());
tagsExclude.put(EntityType.Way, new ArrayList<KeyValueMatcher>());
tagsExclude.put(EntityType.Relation, new ArrayList<KeyValueMatcher>());
addressTags.put(EntityType.Node, new HashSet<KeyValueMatcher>());
addressTags.put(EntityType.Way, new HashSet<KeyValueMatcher>());
addressTags.put(EntityType.Relation, new HashSet<KeyValueMatcher>());
addressTags.get(EntityType.Node).add(new KeyValueMatcher("addr:*","*"));
addressTags.get(EntityType.Node).add(new KeyValueMatcher("place","*"));
addressTags.get(EntityType.Way).add(new KeyValueMatcher("addr:*","*"));
addressTags.get(EntityType.Way).add(new KeyValueMatcher("highway","*"));
addressTags.get(EntityType.Way).add(new KeyValueMatcher("place","*"));
addressTags.get(EntityType.Relation).add(new KeyValueMatcher("addr:*","*"));
addressTags.get(EntityType.Relation).add(new KeyValueMatcher("highway","*"));
addressTags.get(EntityType.Relation).add(new KeyValueMatcher("place","*"));
}
/**
* Creates settings instance with default configuration
* @return
*/
public static ImportSettings getDefault(){
ImportSettings settings = new ImportSettings();
settings.setBuildGrid(true);
settings.setClearBeforeImport(true);
settings.setKey(EntityType.Node, "name*", true);
settings.setKey(EntityType.Node, "highway", false);
settings.setKey(EntityType.Node, "building",false);
settings.setKey(EntityType.Node, "barrier", false);
//settings.setKey(EntityType.Node, "*", false);//excluding * will exclude all items of this type
settings.setKey(EntityType.Way, "name*", true);
settings.setKey(EntityType.Way, "building",true);
settings.setKey(EntityType.Way, "highway",false);
//settings.setKey(EntityType.Way, "*", false);//excluding * will exclude all items of this type
//settings.setKey(EntityType.Relation, "name*", true);
settings.setKeyValue(EntityType.Relation, "type","associatedStreet", false);
settings.setKey(EntityType.Relation, "boundary",false);
settings.setKeyValue(EntityType.Relation, "type", "bridge", true);
settings.setKeyValue(EntityType.Relation, "type", "destination_sign", false);
settings.setKeyValue(EntityType.Relation, "type", "enforcement", false);
settings.setKeyValue(EntityType.Relation, "type", "multipolygon", false);
settings.setKeyValue(EntityType.Relation, "type", "public_transport", true);
settings.setKeyValue(EntityType.Relation, "type", "relatedStreet", false);
settings.setKeyValue(EntityType.Relation, "type", "associatedStreet", false);
settings.setKeyValue(EntityType.Relation, "type", "restriction", false);
settings.setKeyValue(EntityType.Relation, "type", "network", true);
settings.setKeyValue(EntityType.Relation, "type", "operators", true);
settings.setKeyValue(EntityType.Relation, "type", "health", true);
settings.setKey(EntityType.Relation, "landuse",false);
settings.setKey(EntityType.Relation, "natural",false);
settings.setKey(EntityType.Relation, "leisure",false);
settings.setKey(EntityType.Relation, "area",false);
settings.setKey(EntityType.Relation, "waterway",false);
settings.setKey(EntityType.Relation, "type", false);
//settings.setKey(EntityType.Relation, "*",false);//excluding * will exclude all items of this type
settings.setImportAddresses(false);
settings.setGridCellSize(50000);
return settings;
}
public boolean isImportNodes(){
return !tagsInclude.get(EntityType.Node).isEmpty();
}
public boolean isImportWays(){
return !tagsInclude.get(EntityType.Way).isEmpty();
}
public boolean isImportRelations(){
return !tagsInclude.get(EntityType.Relation).isEmpty();
}
public void setBuildGrid(boolean isCreateGrid){
this.isBuildGrid = isCreateGrid;
}
public boolean isBuildGrid(){
return this.isBuildGrid;
}
public void setClearBeforeImport(boolean isClearBeforeImport) {
this.isClearBeforeImport = isClearBeforeImport;
}
public boolean isClearBeforeImport() {
return isClearBeforeImport;
}
public Boolean isImportAddresses() {
return importAddresses;
}
public void reset(EntityType type){
tagsInclude.get(type).clear();
tagsExclude.get(type).clear();
}
/*
* Removes key both from include and exclude lists
*/
public void resetKey(EntityType type, String key){
KeyValueMatcher matcher = new KeyValueMatcher(key,"*");
tagsInclude.get(type).remove(matcher);
tagsExclude.get(type).remove(matcher);
}
/*
* Removes key-value both from include and exclude lists
*/
public void resetKeyValue(EntityType type, String key, String value){
KeyValueMatcher matcher = new KeyValueMatcher(key, value);
tagsInclude.get(type).remove(matcher);
tagsExclude.get(type).remove(matcher);
}
public void setKey(EntityType type, String key, Boolean include){
resetKey(type, key);
KeyValueMatcher matcher = new KeyValueMatcher(key,"*");
if (include){
tagsInclude.get(type).add(matcher);
}else{
tagsExclude.get(type).add(matcher);
}
}
public void setKeyValue(EntityType type, String key, String value, Boolean include){
resetKeyValue(type, key, value);
KeyValueMatcher matcher = new KeyValueMatcher(key, value);
if (include)
tagsInclude.get(type).add(matcher);
else
tagsExclude.get(type).add(matcher);
}
public void setImportAddresses(boolean importAddresses) {
this.importAddresses = importAddresses;
}
public int getGridCellSize() {
return gridCellSize;
}
public void setGridCellSize(int gridCellSize) {
this.gridCellSize = gridCellSize;
}
public void cleanTags(Entity entity){
Collection<Tag> tagsToRemove = new ArrayList<Tag>();
for (Tag t : entity.getTags()) {
if (excludedKeys.contains(t.getKey())) {
tagsToRemove.add(t);
}
}
for(Tag t:tagsToRemove){
entity.getTags().remove(t);
}
}
public Boolean isPoi(Entity entity){
Boolean include=false;
Boolean exclude=false;
for(TagMatcher matcher : tagsExclude.get(entity.getType())){
Boolean match = matcher.isMatch(entity);
if (match){
exclude = true;
break;
}
}
if (exclude)
return false;
for(TagMatcher matcher : tagsInclude.get(entity.getType())){
Boolean match = matcher.isMatch(entity);
if (match){
include = true;
break;
}
}
if (include)
return true;
return false;
}
public Boolean isAddress(Entity entity){
for(TagMatcher check:addressTags.get(entity.getType())){
if (check.isMatch(entity))
return true;
}
return false;
}
public void writeToProperties(Properties props){
props.setProperty("import.isBuildGrid", isBuildGrid.toString());
props.setProperty("import.gridCellSize", gridCellSize.toString());
props.setProperty("import.importAddresses", importAddresses.toString());
for(EntityType entityType : tagsInclude.keySet()){
List<KeyValueMatcher> tags = tagsInclude.get(entityType);
for(KeyValueMatcher tm : tags){
props.setProperty("import.include."+entityType+"."+tm.getKey(), tm.getValue());
}
}
for(EntityType entityType : tagsExclude.keySet()){
List<KeyValueMatcher> tags = tagsExclude.get(entityType);
for(KeyValueMatcher tm : tags){
props.setProperty("import.exclude."+entityType+"."+tm.getKey(), tm.getValue());
}
}
}
public static ImportSettings createFromProperties(Properties props){
ImportSettings settings = new ImportSettings();
settings.setBuildGrid(Boolean.parseBoolean(props.getProperty("import.isBuildGrid", "true")));
settings.setGridCellSize(Integer.parseInt(props.getProperty("import.gridCellSize", new Integer(Integer.MAX_VALUE).toString())));
settings.setImportAddresses(Boolean.parseBoolean(props.getProperty("import.importAddresses", "false")));
for(Object key : props.keySet()){
String[] tokens = key.toString().split("\\.");
if (tokens.length != 4 || !tokens[0].equals("import"))
continue;
EntityType entityType = EntityType.valueOf(tokens[2]);
String k = tokens[3];
if (tokens[1].equals("include")){
settings.setKeyValue(entityType, k, props.getProperty(key.toString()), true);
}else if (tokens[1].equals("exclude")){
settings.setKeyValue(entityType, k, props.getProperty(key.toString()), false);
}
}
return settings;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
/**
* @author yrtimid
*
*/
public class Pair<A, B> {
private A a;
private B b;
public Pair(A a, B b){
this.a = a;
this.b = b;
}
/**
* @return the a
*/
public A getA() {
return a;
}
/**
* @return the b
*/
public B getB() {
return b;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
import java.sql.SQLException;
import il.yrtimid.osm.osmpoi.domain.Node;
import il.yrtimid.osm.osmpoi.domain.Way;
/**
* @author yrtimid
*
*/
public interface IDbCachedFiller extends IDbFiller{
public abstract void beginAdd();
public abstract void endAdd();
public abstract void addNodeIfBelongsToWay(Node node) throws SQLException;
public abstract void addNodeIfBelongsToRelation(Node node) throws SQLException;
public abstract void addWayIfBelongsToRelation(Way way) throws SQLException;
} | Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
/**
* @author yrtimid
*
*/
public class Queries {
public static final String BOUNDS_TABLE = "bounds";
public static final String NODES_TABLE = "nodes";
public static final String NODES_TAGS_TABLE = "node_tags";
public static final String WAYS_TABLE = "ways";
public static final String WAY_TAGS_TABLE = "way_tags";
public static final String WAY_NODES_TABLE = "way_nodes";
public static final String RELATIONS_TABLE = "relations";
public static final String RELATION_TAGS_TABLE = "relation_tags";
public static final String MEMBERS_TABLE = "members";
public static final String GRID_TABLE = "grid";
public static final String INLINE_QUERIES_TABLE = "inline_queries";
public static final String INLINE_RESULTS_TABLE = "inline_results";
public static final String STARRED_TABLE = "starred";
public static final String SQL_CREATE_BOUNDS_TABLE = "CREATE TABLE IF NOT EXISTS bounds ("+
"top REAL NOT NULL," +
"bottom REAL NOT NULL," +
"left REAL NOT NULL," +
"right REAL NOT NULL" +
")";
public static final String SQL_CREATE_NODE_TABLE = "CREATE TABLE IF NOT EXISTS nodes ("
+" id INTEGER NOT NULL PRIMARY KEY,"
+" timestamp TEXT,"
+" lon REAL NOT NULL,"
+" lat REAL NOT NULL,"
+" grid_id INTEGER NOT NULL DEFAULT (0)"
+")";
public static final String SQL_CREATE_NODE_TAGS_TABLE = "CREATE TABLE IF NOT EXISTS node_tags ("
+" node_id INTEGER NOT NULL,"
+" k TEXT,"
+" v TEXT"
+")";
public static final String SQL_NODE_TAGS_IDX = "CREATE UNIQUE INDEX IF NOT EXISTS node_tags_node_id_k_idx ON node_tags(node_id,k)";
public static final String SQL_CREATE_WAYS_TABLE = "CREATE TABLE IF NOT EXISTS ways ("
+" id INTEGER NOT NULL PRIMARY KEY,"
+" timestamp TEXT"
+")";
public static final String SQL_CREATE_WAY_TAGS_TABLE = "CREATE TABLE IF NOT EXISTS way_tags ("
+" way_id INTEGER NOT NULL,"
+" k TEXT,"
+" v TEXT"
+")";
public static final String SQL_WAY_TAGS_IDX = "CREATE UNIQUE INDEX IF NOT EXISTS way_tags_way_id_k_idx ON way_tags(way_id,k)";
public static final String SQL_CREATE_WAY_NODES_TABLE = "CREATE TABLE IF NOT EXISTS way_nodes ("
+" way_id INTEGER NOT NULL,"
+" node_id INTEGER NOT NULL"
+")";
public static final String SQL_WAY_NODES_WAY_NODE_IDX = "CREATE UNIQUE INDEX IF NOT EXISTS way_nodes_way_id_node_id_idx ON way_nodes(way_id,node_id)";
public static final String SQL_WAY_NODES_WAY_IDX = "CREATE INDEX IF NOT EXISTS way_nodes_way_id_idx ON way_nodes(way_id ASC)";
public static final String SQL_WAY_NODES_NODE_IDX = "CREATE INDEX IF NOT EXISTS way_nodes_node_id_idx ON way_nodes(node_id ASC)";
public static final String SQL_CREATE_RELATIONS_TABLE = "CREATE TABLE IF NOT EXISTS relations ("
+" id INTEGER NOT NULL PRIMARY KEY,"
+" timestamp TEXT"
+")";
public static final String SQL_CREATE_RELATION_TAGS_TABLE = "CREATE TABLE IF NOT EXISTS relation_tags ("
+" relation_id INTEGER NOT NULL,"
+" k TEXT,"
+" v TEXT"
+")";
public static final String SQL_RELATION_TAGS_IDX = "CREATE UNIQUE INDEX IF NOT EXISTS relation_tags_rel_id_k_idx ON relation_tags(relation_id,k)";
public static final String SQL_CREATE_MEMBERS_TABLE = "CREATE TABLE IF NOT EXISTS members ("
+" relation_id INTEGER NOT NULL,"
+" type TEXT,"
+" ref INTEGER NOT NULL,"
+" role TEXT"
+")";
public static final String SQL_RELATION_MEMBERS_IDX = "CREATE UNIQUE INDEX IF NOT EXISTS relation_members_rel_id_type_ref_role_idx ON members(relation_id,type,ref,role)";
public static final String SQL_CREATE_GRID_TABLE = "CREATE TABLE IF NOT EXISTS grid ("
+" id INTEGER PRIMARY KEY AUTOINCREMENT,"
+" minLat REAL NOT NULL,"
+" minLon REAL NOT NULL,"
+" maxLat REAL NOT NULL,"
+" maxLon REAL NOT NULL"
+")";
public static final String SQL_CREATE_INLINE_QUERIES_TABLE = "CREATE TABLE IF NOT EXISTS inline_queries (id INTEGER PRIMARY KEY AUTOINCREMENT, query TEXT NOT NULL, [select] TEXT NOT NULL)";
public static final String SQL_CREATE_INLINE_RESULTS_TABLE = "CREATE TABLE IF NOT EXISTS inline_results (query_id INTEGER NOT NULL, value TEXT)";
public static final String SQL_CREATE_STARRED_TABLE = "CREATE TABLE IF NOT EXISTS starred (type TEXT NOT NULL, id INTEGER NOT NULL, title TEXT NOT NULL)";
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
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.Way;
import java.sql.SQLException;
/**
* @author yrtimid
*
*/
public interface IDbFiller extends IDatabase{
public abstract void clearAll() throws Exception;
public abstract void initGrid() throws SQLException;
public abstract void addEntity(Entity entity) throws SQLException;
public abstract void addBound(Bound bound) throws SQLException;
public abstract void addNode(Node node) throws SQLException;
//public abstract void addNodes(Collection<Node> nodes);
public abstract void addNodeTags(Node node) throws SQLException;
//public abstract void addNodeTag(long nodeId, Tag tag);
//public abstract void addNodesTags(Collection<Node> nodes);
public abstract void addWay(Way way) throws SQLException;
//public abstract void addWayTag(long wayId, Tag tag);
public abstract void addWayTags(Way way) throws SQLException;
//public abstract void addWayNode(long wayId, int index, Node wayNode);
public abstract void addWayNodes(Way way) throws SQLException;
public abstract void addRelation(Relation rel) throws SQLException;
//public abstract void addRelationTag(long relId, Tag tag);
public abstract void addRelationTags(Relation rel) throws SQLException;
//public abstract void addRelationMember(long relId, int index, RelationMember mem);
public abstract void addRelationMembers(Relation rel) throws SQLException;
/**
* Splits large cells until no cells with node count greater than maxItems least
* @param maxItems
*/
public abstract void optimizeGrid(Integer maxItems) throws SQLException;
} | Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
/**
* @author yrtimid
*
*/
public interface IDatabase {
void create() throws Exception;
void drop();
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
/**
* A data class representing a single OSM tag.
*
* @author Brett Henderson
*/
public class Tag implements Comparable<Tag>{
/**
* The key identifying the tag.
*/
private String key;
/**
* The value associated with the tag.
*/
private String value;
protected Tag(){}
/**
* Creates a new instance.
*
* @param key
* The key identifying the tag.
* @param value
* The value associated with the tag.
*/
public Tag(String key, String value) {
this.key = key;
this.value = value;
}
/**
* Compares this tag to the specified tag. The tag comparison is based on a
* comparison of key and value in that order.
*
* @param tag
* The tag to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
public int compareTo(Tag tag) {
int keyResult;
keyResult = this.key.compareTo(tag.key);
if (keyResult != 0) {
return keyResult;
}
return this.value.compareTo(tag.value);
}
/**
* @return The key.
*/
public String getKey() {
return key;
}
/**
* @return The value.
*/
public String getValue() {
return value;
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
return "Tag('" + getKey() + "'='" + getValue() + "')";
}
}
| 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.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* 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 CommonEntityData {
protected long id;
protected long timestamp;
protected TagCollection tags;
protected CommonEntityData(){}
public CommonEntityData(long id) {
this(id, 0, new ArrayList<Tag>());
}
public CommonEntityData(long id, Date date) {
this(id, date.getTime(), new ArrayList<Tag>());
}
public CommonEntityData(long id, Date date, Collection<Tag> tags) {
this(id, date.getTime(), tags);
}
public CommonEntityData(long id, long timestamp) {
this(id, timestamp, new ArrayList<Tag>());
}
public CommonEntityData(long id, long timestamp, Collection<Tag> tags) {
this.id = id;
this.timestamp = timestamp;
this.tags = new TagCollection(tags);
}
/**
* Gets the identifier.
*
* @return The id.
*/
public long getId() {
return id;
}
/**
* Sets the identifier.
*
* @param id
* The identifier.
*/
public void setId(long id) {
this.id = id;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
/**
* Returns the attached tags. If the class is read-only, the collection will
* be read-only.
*
* @return The tags.
*/
public TagCollection getTags() {
return tags;
}
/**
* Compares the tags on this entity to the specified tags. The tag
* comparison is based on a comparison of key and value in that order.
*
* @param comparisonTags
* The tags to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
protected int compareTags(Collection<Tag> comparisonTags) {
List<Tag> tags1;
List<Tag> tags2;
tags1 = new ArrayList<Tag>(tags);
tags2 = new ArrayList<Tag>(comparisonTags);
Collections.sort(tags1);
Collections.sort(tags2);
// The list with the most tags is considered bigger.
if (tags1.size() != tags2.size()) {
return tags1.size() - tags2.size();
}
// Check the individual tags.
for (int i = 0; i < tags1.size(); i++) {
int result = tags1.get(i).compareTo(tags2.get(i));
if (result != 0) {
return result;
}
}
// There are no differences.
return 0;
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.Collection;
/**
* A data class representing a single OSM node.
*
* @author Brett Henderson
*/
public class Node extends Entity implements Comparable<Node>{
protected double latitude;
protected double longitude;
protected Node(){
this(new CommonEntityData(), 0.0, 0.0);
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
* @param latitude
* The geographic latitude.
* @param longitude
* The geographic longitude.
*/
public Node(CommonEntityData entityData, double latitude, double longitude) {
super(entityData);
this.latitude = latitude;
this.longitude = longitude;
}
public Node(long nodeId){
this(new CommonEntityData(nodeId, -1), 0L, 0L);
}
/**
* {@inheritDoc}
*/
@Override
public EntityType getType() {
return EntityType.Node;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (o instanceof Node) {
return compareTo((Node) o) == 0;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
/*
* As per the hashCode definition, this doesn't have to be unique it just has to return the
* same value for any two objects that compare equal. Using both id and version will provide
* a good distribution of values but is simple to calculate.
*/
return (int) getId();
}
/**
* Compares this node to the specified node. The node comparison is based on a comparison of id,
* version, latitude, longitude, timestamp and tags in that order.
*
* @param comparisonNode
* The node to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered "bigger".
*/
public int compareTo(Node comparisonNode) {
if (this.getId() < comparisonNode.getId()) {
return -1;
}
if (this.getId() > comparisonNode.getId()) {
return 1;
}
if (this.latitude < comparisonNode.latitude) {
return -1;
}
if (this.latitude > comparisonNode.latitude) {
return 1;
}
if (this.longitude < comparisonNode.longitude) {
return -1;
}
if (this.longitude > comparisonNode.longitude) {
return 1;
}
if (this.getTimestamp()<comparisonNode.getTimestamp()){
return -1;
}
if (this.getTimestamp()>comparisonNode.getTimestamp()){
return 1;
}
return compareTags(comparisonNode.getTags());
}
/**
* Gets the latitude.
*
* @return The latitude.
*/
public double getLatitude() {
return latitude;
}
/**
* Sets the latitude.
*
* @param latitude
* The latitude.
*/
public void setLatitude(double latitude) {
this.latitude = latitude;
}
/**
* Gets the longitude.
*
* @return The longitude.
*/
public double getLongitude() {
return longitude;
}
/**
* Sets the longitude.
*
* @param longitude
* The longitude.
*/
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public boolean hasTags(){
return this.getTags().size()>0;
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
String name = null;
Collection<Tag> tags = getTags();
for (Tag tag : tags) {
if (tag.getKey() != null && tag.getKey().equalsIgnoreCase("name")) {
name = tag.getValue();
break;
}
}
if (name != null) {
return "Node(id=" + getId() + ", #tags=" + getTags().size() + ", name='" + name + "')";
}
return "Node(id=" + getId() + ", #tags=" + getTags().size() + ")";
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
/**
* @author yrtimid
*
*/
public class TagCollection extends ArrayList<Tag> {
private static final long serialVersionUID = -3930512868581794286L;
/**
* Creates a new instance.
*/
public TagCollection() {
super();
}
/**
* Creates a new instance.
*
* @param tags
* The initial tags.
*/
public TagCollection(Collection<? extends Tag> tags) {
super(tags);
}
public Map<String, String> buildMap() {
Map<String, String> tagMap;
tagMap = new HashMap<String, String>(size());
for (Tag tag : this) {
tagMap.put(tag.getKey(), tag.getValue());
}
return tagMap;
}
static final Comparator<Tag> COMPARATOR = new Comparator<Tag>(){
@Override
public int compare(Tag object1, Tag object2) {
return object1.compareTo(object2);
}
};
public Collection<Tag> getSorted(){
ArrayList<Tag> copy = new ArrayList<Tag>(this);
Collections.sort(copy, COMPARATOR);
return copy;
}
}
| 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.Collection;
import java.util.Iterator;
import java.util.List;
/**
* A data class representing a single OSM way.
*
* @author Brett Henderson
*/
public class Way extends Entity implements Comparable<Way> {
private List<Node> nodes;
private List<WayNode> wayNodes;
protected Way() {
this(new CommonEntityData());
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
*/
public Way(CommonEntityData entityData) {
super(entityData);
this.nodes = new ArrayList<Node>();
this.wayNodes = new ArrayList<WayNode>();
}
public Way(long wayId){
this(new CommonEntityData(wayId));
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
* @param wayNodes
* The way nodes to apply to the object
*/
public Way(CommonEntityData entityData, List<Node> nodes) {
super(entityData);
this.nodes = new ArrayList<Node>(nodes);
this.wayNodes = new ArrayList<WayNode>();
}
/**
* {@inheritDoc}
*/
@Override
public EntityType getType() {
return EntityType.Way;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (o instanceof Way) {
return compareTo((Way) o) == 0;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return (int) getId();
}
/**
* Compares this node list to the specified node list. The comparison is
* based on a direct comparison of the node ids.
*
* @param comparisonWayNodes
* The node list to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
protected int compareNodes(List<Node> comparisonWayNodes) {
Iterator<Node> i;
Iterator<Node> j;
// The list with the most entities is considered bigger.
if (nodes.size() != comparisonWayNodes.size()) {
return nodes.size() - comparisonWayNodes.size();
}
// Check the individual way nodes.
i = nodes.iterator();
j = comparisonWayNodes.iterator();
while (i.hasNext()) {
int result = i.next().compareTo(j.next());
if (result != 0) {
return result;
}
}
// There are no differences.
return 0;
}
/**
* Compares this way to the specified way. The way comparison is based on a
* comparison of id, version, timestamp, wayNodeList and tags in that order.
*
* @param comparisonWay
* The way to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
public int compareTo(Way comparisonWay) {
int wayNodeListResult;
if (this.getId() < comparisonWay.getId()) {
return -1;
}
if (this.getId() > comparisonWay.getId()) {
return 1;
}
if (this.getTimestamp()<comparisonWay.getTimestamp()) {
return -1;
}
if (this.getTimestamp()>comparisonWay.getTimestamp()) {
return 1;
}
wayNodeListResult = compareNodes(
comparisonWay.getNodes()
);
if (wayNodeListResult != 0) {
return wayNodeListResult;
}
return compareTags(comparisonWay.getTags());
}
public List<Node> getNodes() {
return nodes;
}
public List<WayNode> getWayNodes() {
return wayNodes;
}
/**
* Is this way closed? (A way is closed if the first node id equals the last node id.)
*
* @return True or false
*/
public boolean isClosed() {
return nodes.get(0).getId() == nodes.get(nodes.size() - 1).getId();
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
String name = null;
Collection<Tag> tags = getTags();
for (Tag tag : tags) {
if (tag.getKey() != null && tag.getKey().equalsIgnoreCase("name")) {
name = tag.getValue();
break;
}
}
if (name != null) {
return "Way(id=" + getId() + ", #tags=" + getTags().size() + ", name='" + name + "')";
}
return "Way(id=" + getId() + ", #tags=" + getTags().size() + ")";
}
}
| 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.Collection;
import java.util.Iterator;
import java.util.List;
/**
* A data class representing a single OSM relation.
*
* @author Brett Henderson
*/
public class Relation extends Entity implements Comparable<Relation>{
private List<RelationMember> members;
protected Relation(){
this(new CommonEntityData());
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
*/
public Relation(CommonEntityData entityData) {
super(entityData);
this.members = new ArrayList<RelationMember>();
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
* @param members
* The members to apply to the object.
*/
public Relation(CommonEntityData entityData, List<RelationMember> members) {
super(entityData);
this.members = new ArrayList<RelationMember>(members);
}
public Relation(long relationId){
this(new CommonEntityData(relationId, -1));
}
/**
* {@inheritDoc}
*/
@Override
public EntityType getType() {
return EntityType.Relation;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (o instanceof Relation) {
return compareTo((Relation) o) == 0;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
/*
* As per the hashCode definition, this doesn't have to be unique it
* just has to return the same value for any two objects that compare
* equal. Using both id and version will provide a good distribution of
* values but is simple to calculate.
*/
return (int) getId();
}
/**
* Compares this member list to the specified member list. The bigger list
* is considered bigger, if that is equal then each relation member is
* compared.
*
* @param comparisonMemberList
* The member list to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
protected int compareMemberList(Collection<RelationMember> comparisonMemberList) {
Iterator<RelationMember> i;
Iterator<RelationMember> j;
// The list with the most entities is considered bigger.
if (members.size() != comparisonMemberList.size()) {
return members.size() - comparisonMemberList.size();
}
// Check the individual node references.
i = members.iterator();
j = comparisonMemberList.iterator();
while (i.hasNext()) {
int result = i.next().compareTo(j.next());
if (result != 0) {
return result;
}
}
// There are no differences.
return 0;
}
/**
* Compares this relation to the specified relation. The relation comparison
* is based on a comparison of id, version, timestamp, and tags in that order.
*
* @param comparisonRelation
* The relation to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
public int compareTo(Relation comparisonRelation) {
int memberListResult;
if (this.getId() < comparisonRelation.getId()) {
return -1;
}
if (this.getId() > comparisonRelation.getId()) {
return 1;
}
if (this.getTimestamp()<comparisonRelation.getTimestamp()) {
return -1;
}
if (this.getTimestamp()>comparisonRelation.getTimestamp()) {
return 1;
}
memberListResult = compareMemberList(
comparisonRelation.members
);
if (memberListResult != 0) {
return memberListResult;
}
return compareTags(comparisonRelation.getTags());
}
public List<RelationMember> getMembers() {
return members;
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
String type = null;
Collection<Tag> tags = getTags();
for (Tag tag : tags) {
if (tag.getKey() != null && tag.getKey().equalsIgnoreCase("type")) {
type = tag.getValue();
break;
}
}
if (type != null) {
return "Relation(id=" + getId() + ", #tags=" + getTags().size() + ", type='" + type + "')";
}
return "Relation(id=" + getId() + ", #tags=" + getTags().size() + ")";
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.security.InvalidParameterException;
/**
* A data class representing a single member within a relation entity.
*
* @author Brett Henderson
*/
public class RelationMember implements Comparable<RelationMember>{
private String memberRole;
private Entity member = null;
protected RelationMember(){}
public RelationMember(Entity member, String memberRole) {
this.memberRole = memberRole;
this.member = member;
}
public RelationMember(long memberId, EntityType memberType, String memberRole) {
this.memberRole = memberRole;
switch(memberType){
case Node:
this.member = new Node(memberId);
break;
case Way:
this.member = new Way(memberId);
break;
case Relation:
this.member = new Relation(memberId);
break;
default:
throw new InvalidParameterException("Unsupported member type: "+memberType.name());
}
}
/**
* Compares this relation member to the specified relation member. The
* relation member comparison is based on a comparison of member type, then
* member id, then role.
*
* @param relationMember
* The relation member to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
public int compareTo(RelationMember relationMember) {
long result;
// Compare the member type.
result = this.getMemberType().compareTo(relationMember.getMemberType());
if (result > 0) {
return 1;
} else if (result < 0) {
return -1;
}
// Compare the member id.
result = this.getMemberId() - relationMember.getMemberId();
if (result > 0) {
return 1;
} else if (result < 0) {
return -1;
}
// Compare the member role.
result = this.memberRole.compareTo(relationMember.memberRole);
if (result > 0) {
return 1;
} else if (result < 0) {
return -1;
}
// No differences detected.
return 0;
}
/**
* Returns the id of the member entity.
*
* @return The member id.
*/
public long getMemberId() {
return member.getId();
}
/**
* Returns the type of the member entity.
*
* @return The member type.
*/
public EntityType getMemberType() {
return member.getType();
}
/**
* Returns the role that this member forms within the relation.
*
* @return The role.
*/
public String getMemberRole() {
return memberRole;
}
/**
* @param memberRole the memberRole to set
*/
public void setMemberRole(String memberRole) {
this.memberRole = memberRole;
}
/**
* @return the member
*/
public Entity getMember() {
return member;
}
/**
* @param member the member to set
*/
public void setMember(Entity member) {
this.member = member;
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
return "RelationMember(" + getMemberType() + " with id " + getMemberId() + " in the role '" + getMemberRole()
+ "')";
}
}
| Java |
package il.yrtimid.osm.osmpoi.domain;
public class WayNode extends Entity {
protected WayNode(){
this(new CommonEntityData());
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
*/
public WayNode(CommonEntityData entityData) {
super(entityData);
}
public WayNode(long nodeId) {
super(new CommonEntityData(nodeId));
}
@Override
public EntityType getType() {
return EntityType.NodeRef;
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.Collection;
/**
* A data class representing a single OSM entity. All top level data types
* inherit from this class.
*
* @author Brett Henderson
*/
public abstract class Entity{
protected CommonEntityData entityData;
protected Entity(){}
/**
* Creates a new instance.
*
* @param entityData
* The data to store in the entity. This instance is used directly and is not cloned.
*/
public Entity(CommonEntityData entityData) {
this.entityData = entityData;
}
/**
* Returns the specific data type represented by this entity.
*
* @return The entity type enum value.
*/
public abstract EntityType getType();
/**
* Gets the identifier.
*
* @return The id.
*/
public long getId() {
return entityData.getId();
}
/**
* Sets the identifier.
*
* @param id
* The identifier.
*/
public void setId(long id) {
entityData.setId(id);
}
/**
* Gets the timestamp in date form. This is the standard method for
* retrieving timestamp information.
*
* @return The timestamp.
*/
public long getTimestamp() {
return entityData.getTimestamp();
}
/**
* Sets the timestamp in date form. This is the standard method of updating a timestamp.
*
* @param timestamp
* The timestamp.
*/
public void setTimestamp(long timestamp) {
entityData.setTimestamp(timestamp);
}
/**
* Returns the attached tags. If the class is read-only, the collection will
* be read-only.
*
* @return The tags.
*/
public TagCollection getTags() {
return entityData.getTags();
}
/**
* Compares the tags on this entity to the specified tags. The tag
* comparison is based on a comparison of key and value in that order.
*
* @param comparisonTags
* The tags to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
protected int compareTags(Collection<Tag> comparisonTags) {
return entityData.compareTags(comparisonTags);
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.Date;
/**
* A data class representing an OSM data bound element.
*
* @author Karl Newman
*/
public class Bound extends Entity {
private static final double MIN_LATITUDE = -90.0;
private static final double MAX_LATITUDE = 90.0;
private static final double MIN_LONGITUDE = -180.0;
private static final double MAX_LONGITUDE = 180.0;
private double right;
private double left;
private double top;
private double bottom;
private String origin;
/**
* Creates a new instance which covers the entire planet.
*
* @param origin
* The origin (source) of the data, typically a URI
*
*/
public Bound(String origin) {
this(MAX_LONGITUDE, MIN_LONGITUDE, MAX_LATITUDE, MIN_LATITUDE, origin);
}
/**
* Creates a new instance with the specified boundaries.
*
* @param right
* The longitude coordinate of the right (East) edge of the bound
* @param left
* The longitude coordinate of the left (West) edge of the bound
* @param top
* The latitude coordinate of the top (North) edge of the bound
* @param bottom
* The latitude coordinate of the bottom (South) edge of the bound
* @param origin
* The origin (source) of the data, typically a URI
*/
public Bound(double right, double left, double top, double bottom, String origin) {
super(new CommonEntityData(0, new Date())); // minimal underlying entity
// Check if any coordinates are out of bounds
if (Double.compare(right, MAX_LONGITUDE + 1.0d) > 0
|| Double.compare(right, MIN_LONGITUDE - 1.0d) < 0
|| Double.compare(left, MAX_LONGITUDE + 1.0d) > 0
|| Double.compare(left, MIN_LONGITUDE - 1.0d) < 0
|| Double.compare(top, MAX_LATITUDE + 1.0d) > 0
|| Double.compare(top, MIN_LATITUDE - 1.0d) < 0
|| Double.compare(bottom, MAX_LATITUDE + 1.0d) > 0
|| Double.compare(bottom, MIN_LATITUDE - 1.0d) < 0) {
throw new IllegalArgumentException("Bound coordinates outside of valid range");
}
if (Double.compare(top, bottom) < 0) {
throw new IllegalArgumentException("Bound top < bottom");
}
if (origin == null) {
throw new IllegalArgumentException("Bound origin is null");
}
this.right = right;
this.left = left;
this.top = top;
this.bottom = bottom;
this.origin = origin;
}
/**
* {@inheritDoc}
*/
@Override
public EntityType getType() {
return EntityType.Bound;
}
/**
* @return The right (East) bound longitude
*/
public double getRight() {
return right;
}
/**
* @return The left (West) bound longitude
*/
public double getLeft() {
return left;
}
/**
* @return The top (North) bound latitude
*/
public double getTop() {
return top;
}
/**
* @return The bottom (South) bound latitude
*/
public double getBottom() {
return bottom;
}
/**
* @return the origin
*/
public String getOrigin() {
return origin;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
/*
* As per the hashCode definition, this doesn't have to be unique it
* just has to return the same value for any two objects that compare
* equal. Using both id and version will provide a good distribution of
* values but is simple to calculate.
*/
return (int) getId();
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
return "Bound(top=" + getTop() + ", bottom=" + getBottom() + ", left=" + getLeft() + ", right=" + getRight()
+ ")";
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
/**
* An enum representing the different data types in the OSM data model.
*
* @author Brett Henderson
*/
public enum EntityType {
None,
/**
* Representation of the latitude/longitude bounding box of the entity stream.
*/
Bound,
/**
* Represents a geographical point.
*/
Node,
/**
* Represents a set of segments forming a path.
*/
Way,
/**
* Represents a relationship between multiple entities.
*/
Relation,
NodeRef
}
| Java |
package il.yrtimid.osm.osmpoi;
public interface ItemPipe<T> {
public void pushItem(T item);
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.xml.v0_6.impl;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import java.util.HashMap;
import java.util.Map;
import org.openstreetmap.osmosis.core.OsmosisRuntimeException;
/**
* Parses the xml representation of a relation member type into an entity type
* object.
*
* @author Brett Henderson
*/
public class MemberTypeParser {
private static final Map<String, EntityType> MEMBER_TYPE_MAP = new HashMap<String, EntityType>();
static {
MEMBER_TYPE_MAP.put("node", EntityType.Node);
MEMBER_TYPE_MAP.put("way", EntityType.Way);
MEMBER_TYPE_MAP.put("relation", EntityType.Relation);
}
/**
* Parses the database representation of a relation member type into an
* entity type object.
*
* @param memberType
* The database value of member type.
* @return A strongly typed entity type.
*/
public EntityType parse(String memberType) {
if (MEMBER_TYPE_MAP.containsKey(memberType)) {
return MEMBER_TYPE_MAP.get(memberType);
} else {
throw new OsmosisRuntimeException("The member type " + memberType + " is not recognised.");
}
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.xml.v0_6.impl;
/**
* Defines some common constants shared between various xml processing classes.
*
* @author Brett Henderson
*/
public final class XmlConstants {
/**
* This class cannot be instantiated.
*/
private XmlConstants() {
}
/**
* Defines the version number to be stored in osm xml files. This number
* will also be applied to osmChange files.
*/
public static final String OSM_VERSION = "0.6";
/**
* The default URL for the production API.
*/
public static final String DEFAULT_URL = "http://www.openstreetmap.org/api/0.6";
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.lifecycle;
/**
* Classes that hold heavyweight resources that can't wait for garbage
* collection should implement this interface. It provides a release method that
* should be called by all clients when the class is no longer required. This
* release method is guaranteed not to throw exceptions and should always be
* called within a finally clause.
*
* @author Brett Henderson
*/
public interface Releasable {
/**
* Performs resource cleanup tasks such as closing files, or database
* connections. This must be called after all processing is complete and may
* be called multiple times. Implementations must call release on any nested
* Releasable objects. It should be called within a finally block to ensure
* it is called in exception scenarios.
*/
void release();
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.lifecycle;
/**
* Some class implementations persist information and require notification to
* complete all output prior to being released. In this case, clients of those
* classes should call the complete method.
*
* @author Brett Henderson
*/
public interface Completable extends Releasable {
/**
* Ensures that all information is fully persisted. This includes database
* commits, file buffer flushes, etc. Implementations must call complete on
* any nested Completable objects. Where the releasable method of a
* Releasable class should be called within a finally block, this method
* should typically be the final statement within the try block.
*/
void complete();
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core;
/**
* Constants shared across the Osmosis application.
*
* @author Brett Henderson
*/
public final class OsmosisConstants {
/**
* This class cannot be instantiated.
*/
private OsmosisConstants() {
}
/**
* Defines the version of the Osmosis application.
*/
public static final String VERSION = "0.39-70-g0d3a7b7";
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.task.v0_6;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
import org.openstreetmap.osmosis.core.task.common.Task;
/**
* Defines the interface for tasks producing OSM data types.
*
* @author Brett Henderson
*/
public interface Source extends Task {
/**
* Sets the osm sink to send data to.
*
* @param sink
* The sink for receiving all produced data.
*/
void setSink(Sink sink);
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.task.v0_6;
/**
* Extends the basic Source interface with the Runnable capability. Runnable
* is not applied to the Source interface because tasks that act as filters
* do not require Runnable capability.
*
* @author Brett Henderson
*/
public interface RunnableSource extends Source, Runnable {
// This interface combines Source and Runnable but doesn't introduce
// methods of its own.
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.task.v0_6;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
/**
* Defines the interface for combining sink and source functionality. This is
* typically used by classes performing some form of translation on an input
* source before sending along to the output. This includes filtering tasks and
* modification tasks.
*
* @author Brett Henderson
*/
public interface SinkSource extends Sink, Source {
// Interface only combines functionality of its extended interfaces.
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.task.common;
/**
* Defines the root of the interface inheritance hierarchy for all task types.
*
* @author Brett Henderson
*/
public interface Task {
// Interface only exists to provide a common hierarchy root for all task
// types.
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core;
/**
* The root of the unchecked exception hierarchy for the application. All typed
* runtime exceptions subclass this exception.
*
* @author Brett Henderson
*/
public class OsmosisRuntimeException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new exception with <code>null</code> as its detail message.
*/
public OsmosisRuntimeException() {
super();
}
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message.
*/
public OsmosisRuntimeException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified cause and a detail
* message of <tt>(cause==null ? null : cause.toString())</tt> (which
* typically contains the class and detail message of <tt>cause</tt>).
*
* @param cause the cause.
*/
public OsmosisRuntimeException(Throwable cause) {
super(cause);
}
/**
* Constructs a new exception with the specified detail message and
* cause.
*
* @param message the detail message.
* @param cause the cause.
*/
public OsmosisRuntimeException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6;
import il.yrtimid.osm.osmpoi.domain.Entity;
/**
* @author yrtimid
*
*/
public class NullSink implements Sink {
/* (non-Javadoc)
* @see org.openstreetmap.osmosis.core.lifecycle.Completable#complete()
*/
@Override
public void complete() {
}
/* (non-Javadoc)
* @see org.openstreetmap.osmosis.core.lifecycle.Releasable#release()
*/
@Override
public void release() {
}
/* (non-Javadoc)
* @see org.openstreetmap.osmosis.core.task.v0_6.Sink#process(org.openstreetmap.osmosis.core.container.v0_6.EntityContainer)
*/
@Override
public void process(Entity entity) {
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6;
import il.yrtimid.osm.osmpoi.domain.Entity;
import org.openstreetmap.osmosis.core.lifecycle.Completable;
import org.openstreetmap.osmosis.core.task.common.Task;
/**
* Defines the interface for tasks consuming OSM data types.
*
* @author Brett Henderson
*/
public interface Sink extends Task, Completable {
/**
* Process the entity.
*
* @param entityContainer
* The entity to be processed.
*/
void process(Entity entity);
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.db;
import il.yrtimid.osm.osmpoi.dal.IDatabase;
import il.yrtimid.osm.osmpoi.dal.Queries;
import java.io.File;
import java.sql.*;
/**
* @author yrtimid
*
*/
public class SqliteJDBCCreator extends SqliteJDBCDatabase implements IDatabase {
protected Connection conn;
/**
* @throws Exception
*
*/
public SqliteJDBCCreator(String filePath) throws Exception {
super(filePath);
this.conn = getConnection();
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.IDatabase#create(java.lang.String)
*/
@Override
public void create() throws Exception {
this.conn = getConnection();
createAllTables();
}
protected void execSQL(String query) throws SQLException{
Statement statement = null;
try {
statement = conn.createStatement();
statement.executeUpdate(query);
}finally{
if (statement!=null)
statement.close();
}
}
private void createAllTables() throws SQLException{
execSQL(Queries.SQL_CREATE_BOUNDS_TABLE);
execSQL(Queries.SQL_CREATE_NODE_TABLE);
execSQL(Queries.SQL_CREATE_NODE_TAGS_TABLE);
execSQL(Queries.SQL_NODE_TAGS_IDX);
execSQL(Queries.SQL_CREATE_WAYS_TABLE);
execSQL(Queries.SQL_CREATE_WAY_TAGS_TABLE);
execSQL(Queries.SQL_WAY_TAGS_IDX);
execSQL(Queries.SQL_CREATE_WAY_NODES_TABLE);
execSQL(Queries.SQL_WAY_NODES_WAY_NODE_IDX);
execSQL(Queries.SQL_WAY_NODES_WAY_IDX);
execSQL(Queries.SQL_WAY_NODES_NODE_IDX);
execSQL(Queries.SQL_CREATE_RELATIONS_TABLE);
execSQL(Queries.SQL_CREATE_RELATION_TAGS_TABLE);
execSQL(Queries.SQL_RELATION_TAGS_IDX);
execSQL(Queries.SQL_CREATE_MEMBERS_TABLE);
execSQL(Queries.SQL_RELATION_MEMBERS_IDX);
execSQL(Queries.SQL_CREATE_GRID_TABLE);
execSQL(Queries.SQL_CREATE_INLINE_QUERIES_TABLE);
execSQL(Queries.SQL_CREATE_INLINE_RESULTS_TABLE);
}
@Override
public void drop() {
new File(filePath).delete();
this.conn = null;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import il.yrtimid.osm.osmpoi.Pair;
import il.yrtimid.osm.osmpoi.dal.IDbFiller;
import il.yrtimid.osm.osmpoi.dal.Queries;
import il.yrtimid.osm.osmpoi.Log;
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;
/**
* @author yrtimid
*
*/
public class SqliteJDBCFiller extends SqliteJDBCCreator implements IDbFiller {
public SqliteJDBCFiller(String filePath) throws Exception {
super(filePath);
}
@Override
public void clearAll() throws Exception {
drop();
//dropAllTables(db);
create();
}
@Override
public void initGrid() throws SQLException{
//db.execSQL("UPDATE "+NODES_TABLE+" SET grid_id=1");
execSQL("DROP TABLE IF EXISTS "+Queries.GRID_TABLE);
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);
execSQL(sql_generate_grid);
String updateNodesGrid = "UPDATE nodes SET grid_id = 1 WHERE grid_id <> 1";
Log.d(updateNodesGrid);
execSQL(updateNodesGrid);
}
@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);
}
public void addBound(Bound bound) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT INTO "+Queries.BOUNDS_TABLE+" (top, bottom, left, right) VALUES(?,?,?,?)");
statement.setDouble(1, bound.getTop());
statement.setDouble(2, bound.getBottom());
statement.setDouble(3, bound.getLeft());
statement.setDouble(4, bound.getRight());
int res = statement.executeUpdate();
if (res != 1)
throw new SQLException("Bound was not inserted");
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addNode(Node node) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.NODES_TABLE+" (id, timestamp, lat, lon, grid_id) VALUES(?,?,?,?,?)");
statement.setLong(1, node.getId());
statement.setLong(2, node.getTimestamp());
statement.setDouble(3, node.getLatitude());
statement.setDouble(4, node.getLongitude());
statement.setInt(5, 1);
statement.executeUpdate();
addNodeTags(node);
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addNodeTags(Node node) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.NODES_TAGS_TABLE+" (node_id, k, v) VALUES(?,?,?)");
final long id = node.getId();
statement.setLong(1, id);
for(Tag tag:node.getTags()){
statement.setString(2, tag.getKey());
statement.setString(3, tag.getValue());
statement.executeUpdate();
}
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addWay(Way way) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.WAYS_TABLE+" (id, timestamp) VALUES(?,?)");
statement.setLong(1, way.getId());
statement.setLong(2, way.getTimestamp());
statement.executeUpdate();
addWayTags(way);
addWayNodes(way);
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addWayTags(Way way) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.WAY_TAGS_TABLE+" (way_id, k, v) VALUES(?,?,?)");
statement.setLong(1, way.getId());
for(Tag tag : way.getTags()){
statement.setString(2, tag.getKey());
statement.setString(3, tag.getValue());
statement.executeUpdate();
}
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addWayNodes(Way way) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.WAY_NODES_TABLE+" (way_id, node_id) VALUES(?,?)");
statement.setLong(1, way.getId());
for(Node node : way.getNodes()){
statement.setLong(2, node.getId());
statement.executeUpdate();
}
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addRelation(Relation rel) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.RELATIONS_TABLE+" (id, timestamp) VALUES(?,?)");
statement.setLong(1, rel.getId());
statement.setLong(2, rel.getTimestamp());
statement.executeUpdate();
addRelationTags(rel);
addRelationMembers(rel);
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addRelationTags(Relation rel) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.RELATION_TAGS_TABLE+" (relation_id, k, v) VALUES(?,?,?)");
final long id = rel.getId();
statement.setLong(1, id);
for(Tag tag : rel.getTags()){
statement.setString(2, tag.getKey());
statement.setString(3, tag.getValue());
statement.executeUpdate();
}
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addRelationMembers(Relation rel) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.MEMBERS_TABLE+" (relation_id, type, ref, role) VALUES(?,?,?,?)");
statement.setLong(1, rel.getId());
for(RelationMember mem : rel.getMembers()){
statement.setString(2, mem.getMemberType().name());
statement.setLong(3, mem.getMemberId());
statement.setString(4, mem.getMemberRole());
statement.executeUpdate();
}
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void optimizeGrid(Integer maxItems) throws SQLException {
Collection<Pair<Integer,Integer>> cells = null;
conn.setAutoCommit(false);
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());
conn.commit();
}
}while(cells.size() > 0);
}
/**
* finds cells which have nodes count greater than minItems
* @param minItems
* @return
* @throws SQLException
*/
private Collection<Pair<Integer,Integer>> getBigCells(Integer minItems) throws SQLException{
Statement statement = null;
Collection<Pair<Integer,Integer>> gridIds = new ArrayList<Pair<Integer,Integer>>();
ResultSet cur = null;
try{
statement = conn.createStatement();
String sql = "SELECT grid_id, count(id) [count] FROM "+Queries.NODES_TABLE+" GROUP BY grid_id HAVING count(id)>"+minItems.toString();
cur = statement.executeQuery(sql);
while(cur.next()){
Integer id = cur.getInt("grid_id");
Integer count = cur.getInt("count");
gridIds.add(new Pair<Integer, Integer>(id, count));
}
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
}
return gridIds;
}
/**
* Splits cell into 4 pieces and updates theirs nodes with the new split
* @param id ID of the cell to split
* @throws SQLException
*/
private void splitGridCell(Integer id) throws SQLException{
Statement statement = null;
PreparedStatement prepStatement = null;
ResultSet cur = null;
try {
statement = conn.createStatement();
Log.d("splitGridCell id:"+id);
//calc new cell size to be 1/2 of the old one
String getNewCellSizeSql = "SELECT round((maxLat-minLat)/2,7) dLat, round((maxLon-minLon)/2,7) dLon from "+Queries.GRID_TABLE+" WHERE id="+id.toString();
cur = statement.executeQuery(getNewCellSizeSql);
cur.next();
Double newCellSizeLat = cur.getDouble(1);
Double newCellSizeLon = cur.getDouble(2);
cur.close();
statement.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);
prepStatement = conn.prepareStatement(create4NewCellsSql);
prepStatement.executeUpdate();
prepStatement.close();
//delete old cell
statement = conn.createStatement();
String deleteOldCellSql = "DELETE FROM "+Queries.GRID_TABLE+" WHERE id="+id.toString();
Log.d(deleteOldCellSql);
int deleteResult = statement.executeUpdate(deleteOldCellSql);
Log.d("deleted "+deleteResult+" cells");
statement.close();
//update nodes to use new cells
statement = conn.createStatement();
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);
statement.executeUpdate(updateNodesSql);
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
if (prepStatement != null)
prepStatement.close();
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.db;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import il.yrtimid.osm.osmpoi.dal.IDbCachedFiller;
import il.yrtimid.osm.osmpoi.dal.Queries;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.Node;
import il.yrtimid.osm.osmpoi.domain.Way;
/**
* @author yrtimid
*
*/
public class SqliteJDBCCachedFiller extends SqliteJDBCFiller implements IDbCachedFiller {
private static int MAX_UNCOMMITTED_ITEMS = 10000;
int uncommittedItems = 0;
/**
* @param filePath
* @throws Exception
*/
public SqliteJDBCCachedFiller(String filePath) throws Exception {
super(filePath);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#beginAdd()
*/
@Override
public void beginAdd() {
try {
conn.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#endAdd()
*/
@Override
public void endAdd() {
try {
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.db.SqliteJDBCFiller#addEntity(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public void addEntity(Entity entity) throws SQLException {
super.addEntity(entity);
uncommittedItems++;
if (uncommittedItems>=MAX_UNCOMMITTED_ITEMS){
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
uncommittedItems = 0;
}
}
@Override
public void addNodeIfBelongsToWay(Node node) throws SQLException{
Statement statement = null;
ResultSet cur = null;
boolean exists = false;
try {
statement = conn.createStatement();
String sql = "SELECT way_id from "+Queries.WAY_NODES_TABLE+" WHERE node_id="+node.getId();
cur = statement.executeQuery(sql);
if (cur.next()){
long way_id = cur.getLong(1);
exists = true;
}
cur.close();
statement.close();
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
}
if (exists)
addEntity(node);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#addNodeIfBelongsToRelation(il.yrtimid.osm.osmpoi.domain.Node)
*/
@Override
public void addNodeIfBelongsToRelation(Node node) throws SQLException{
Statement statement = null;
ResultSet cur = null;
boolean exists = false;
try {
statement = conn.createStatement();
String sql = "SELECT relation_id from "+Queries.MEMBERS_TABLE+" WHERE type='Node' AND ref="+node.getId();
cur = statement.executeQuery(sql);
if (cur.next()){
long way_id = cur.getLong(1);
exists = true;
}
cur.close();
statement.close();
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
}
if (exists)
addEntity(node);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#addWayIfBelongsToRelation(il.yrtimid.osm.osmpoi.domain.Way)
*/
@Override
public void addWayIfBelongsToRelation(Way way) throws SQLException{
Statement statement = null;
ResultSet cur = null;
boolean exists = false;
try {
statement = conn.createStatement();
String sql = "SELECT relation_id from "+Queries.MEMBERS_TABLE+" WHERE type='Way' AND ref="+way.getId();
cur = statement.executeQuery(sql);
if (cur.next()){
long way_id = cur.getLong(1);
exists = true;
}
cur.close();
statement.close();
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
}
if (exists)
addEntity(way);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.db;
import il.yrtimid.osm.osmpoi.dal.Queries;
import il.yrtimid.osm.osmpoi.domain.GridCell;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author yrtimid
*
*/
public class SqliteJDBCGridReader extends SqliteJDBCDatabase {
/**
* @throws ClassNotFoundException
*
*/
public SqliteJDBCGridReader(String filePath) throws ClassNotFoundException {
super(filePath);
}
public Collection<GridCell> getGrid() throws SQLException{
Connection conn = getConnection();
Statement statement = null;
ResultSet cur = null;
Collection<GridCell> cells = new ArrayList<GridCell>();
try {
statement = conn.createStatement();
cur = statement.executeQuery("SELECT * FROM "+Queries.GRID_TABLE);
while(cur.next()){
Integer id = cur.getInt("id");
double minLat = cur.getDouble("minLat");
double maxLat = cur.getDouble("maxLat");
double minLon = cur.getDouble("minLon");
double maxLon = cur.getDouble("maxLon");
cells.add(new GridCell(id, minLat, minLon, maxLat, maxLon));
}
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
if (conn != null)
conn.close();
}
return cells;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* @author yrtimid
*
*/
public class SqliteJDBCDatabase {
String filePath;
/**
* @throws ClassNotFoundException
*
*/
public SqliteJDBCDatabase(String filePath) throws ClassNotFoundException {
this.filePath = filePath;
Class.forName("org.sqlite.JDBC");
}
protected Connection getConnection() throws SQLException{
return DriverManager.getConnection("jdbc:sqlite:" + filePath);
}
}
| Java |
package il.yrtimid.osm.osmpoi.dbcreator;
import il.yrtimid.osm.osmpoi.ImportSettings;
import il.yrtimid.osm.osmpoi.SortedProperties;
import il.yrtimid.osm.osmpoi.db.SqliteJDBCCachedFiller;
import il.yrtimid.osm.osmpoi.db.SqliteJDBCGridReader;
import il.yrtimid.osm.osmpoi.dbcreator.common.DbCreator;
import il.yrtimid.osm.osmpoi.domain.GridCell;
import il.yrtimid.osm.osmpoi.domain.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Collection;
/**
*
*/
/**
* @author yrtimid
*
*/
public class DbCreatorConsole {
private static final String PROPERTIES_FILE_NAME = "dbcreator.properties";
private static ImportSettings settings = null;
private static final String ARGUMENT_CREATE = "--create";
private static final String ARGUMENT_SAVE_GRID = "--save-grid";
private static final String ARGUMENT_REBUILD_GRID = "--rebuild-grid";
/**
* @param args
*/
public static void main(String[] args) {
createSettings();
//////////////DEBUG/////////////////////
// args = new String[2];
// args[0] = "--create";
// args[1] = "israel_and_palestine.osm.pbf";
if (args.length == 2) {
if (ARGUMENT_CREATE.equals(args[0])) {
create(args[1]);
return;
} else if (ARGUMENT_SAVE_GRID.equals(args[0])) {
saveGrid(args[1]);
return;
} else if (ARGUMENT_REBUILD_GRID.equals(args[0])){
rebuildGrid(args[1]);
return;
}
}
printHelp();
}
private static void printHelp() {
System.out.println("Usage:");
System.out.println(ARGUMENT_CREATE + " <pbf file name>\tcreate new DB from PBF file");
System.out.println(ARGUMENT_SAVE_GRID + " <db file>\toutputs grid from DB in poly format (dev option)");
System.out.println(ARGUMENT_REBUILD_GRID + " <db file>\trebuilds grid (dev option)");
System.out.println("");
}
private static void createSettings() {
try {
File propsFile = new File(PROPERTIES_FILE_NAME);
SortedProperties props = new SortedProperties();
if (propsFile.exists()) {
props.load(new FileInputStream(propsFile));
settings = ImportSettings.createFromProperties(props);
} else {
settings = ImportSettings.getDefault();
settings.writeToProperties(props);
props.store(new FileOutputStream(propsFile), "OsmPoi-Db-Creator default settings");
System.out.println("New " + PROPERTIES_FILE_NAME + " file created with default settings");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param dbFilePath path to the db file with grid
*/
private static void saveGrid(String dbFilePath) {
PrintStream stream = System.out;
try {
File dbFile = new File(dbFilePath);
if (dbFile.canRead()) {
stream.println(dbFile.getName().replace('.', '_'));
SqliteJDBCGridReader gridReader = new SqliteJDBCGridReader(dbFilePath);
Collection<GridCell> cells = gridReader.getGrid();
for(GridCell c : cells){
stream.println(c.getId());
for(int i=0;i<4;i++){
Point p = c.getVertex(i);
stream.println("\t"+p.getLongitude()+"\t"+p.getLatitude());
}
stream.println("END");
}
stream.println("END");
} else {
System.err.println("Can't read db file: " + dbFilePath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param sourceFilePath path to the *.pbf file to import from
*/
private static void create(String sourceFilePath) {
String poiDbName = "poi.db";
String addrDbName = "addr.db";
File poiDbFile = new File(poiDbName);
File addrDbFile = new File(addrDbName);
if (poiDbFile.exists()) {
System.out.println("Deleting old poi db");
poiDbFile.delete();
}
if (addrDbFile.exists()) {
System.out.println("Deleting old addr db");
addrDbFile.delete();
}
System.out.println("Processing file " + sourceFilePath);
System.out.println(new File(".").getAbsolutePath());
DbCreator creator;
try {
creator = new DbCreator(new SqliteJDBCCachedFiller(poiDbName), new SqliteJDBCCachedFiller(addrDbName), new ConsoleNotificationManager());
//creator.createEmptyDatabases();
creator.importToDB(sourceFilePath, settings);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done.");
}
private static void rebuildGrid(String dbFilePath) {
try {
File dbFile = new File(dbFilePath);
if (dbFile.canRead()) {
DbCreator creator = new DbCreator(new SqliteJDBCCachedFiller(dbFilePath), null, new ConsoleNotificationManager());
creator.rebuildGrid(settings);
} else {
System.err.println("Can't read db file: " + dbFilePath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dbcreator;
import il.yrtimid.osm.osmpoi.dbcreator.common.*;
/**
* @author yrtimid
*
*/
public class ConsoleNotificationManager implements INotificationManager {
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dbcreator.INotificationManager#notify(int, il.yrtimid.osm.osmpoi.dbcreator.Notification)
*/
@Override
public void notify(int id, Notification2 notification){
System.out.println(notification.title+": "+notification.text);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
/**
* @author yrtimid
* use setprop log.tag.OsmPoi VERBOSE to enable logging
*/
public class Log {
static final String TAG = "OsmPoi";
public static void i(String string) {
System.out.println(TAG+": "+string);
}
public static void w(String string) {
System.out.println(TAG+": "+string);
}
public static void e(String string) {
System.out.println(TAG+": "+string);
}
public static void d(String string) {
System.out.println(TAG+": "+string);
}
public static void v(String string) {
System.out.println(TAG+": "+string);
}
public static void wtf(String message, Throwable throwable) {
System.out.println(TAG+": "+message);
throwable.printStackTrace(System.out);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.domain;
/**
* @author yrtimid
*
*/
public class GridCell {
int id;
double minLat, minLon, maxLat, maxLon;
/**
* @param id
* @param minLat
* @param minLon
* @param maxLat
* @param maxLon
*/
public GridCell(int id, double minLat, double minLon, double maxLat, double maxLon) {
super();
this.id = id;
this.minLat = minLat;
this.minLon = minLon;
this.maxLat = maxLat;
this.maxLon = maxLon;
}
/**
*
* @param 0-based vertex index [0..3]
* @return
* @throws Exception
*/
public Point getVertex(int index) throws Exception{
switch(index){
case 0:
return new Point(minLat, minLon);
case 1:
return new Point(minLat, maxLon);
case 2:
return new Point(maxLat, maxLon);
case 3:
return new Point(maxLat, minLon);
default:
throw new Exception("Only index from 0 to 3 inclusive is supported");
}
}
/**
* @return the id
*/
public int getId() {
return id;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.