Simple example reverse geocoding osmdroid - dictionary

im looking for a simple example of reverse geocoding using osmdroid.
Do have i to use the nominatimAPI with JSON and more ?
i heard that using the Geocoder class do the same thing but it seems too easy...
Is it normal that the class RequestBuilder is not recognize when im attemping to do a request
to nominatim ?
Thanks

You can use OSMBonusPack GeocoderNominatim class.

Here is an example using OSMBonusPack:
// declare your map somewhere in the Activity
map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setMultiTouchControls(true);
// create a GeoPoint
final GeoPoint startPoint = new GeoPoint(36.716999, 3.042076);
// Retreive Geocoding data (add this code to an event click listener on a button)
new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... voids) {
// Reverse Geocoding
GeocoderNominatim geocoder = new GeocoderNominatim(userAgent);
String theAddress;
try {
List<Address> addresses = geocoder.getFromLocation(startPoint.getLatitude(), startPoint.getLongitude(), 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
int n = address.getMaxAddressLineIndex();
Log.d("Test", "CountryName: " + address.getCountryName());
Log.d("Test", "CountryCode: " + address.getCountryCode());
Log.d("Test", "PostalCode " + address.getPostalCode());
// Log.d("Test", "FeatureName " + address.getFeatureName()); //null
Log.d("Test", "City: " + address.getAdminArea());
Log.d("Test", "Locality: " + address.getLocality());
Log.d("Test", "Premises: " + address.getPremises()); //null
Log.d("Test", "SubAdminArea: " + address.getSubAdminArea());
Log.d("Test", "SubLocality: " + address.getSubLocality());
// Log.d("Test", "SubThoroughfare: " + address.getSubThoroughfare()); //null
// Log.d("Test", "getThoroughfare: " + address.getThoroughfare()); //null
Log.d("Test", "Locale: " + address.getLocale());
for (int i=0; i<=n; i++) {
if (i!=0)
sb.append(", ");
sb.append(address.getAddressLine(i));
}
theAddress = sb.toString();
} else {
theAddress = null;
}
} catch (IOException e) {
theAddress = null;
}
if (theAddress != null) {
Log.d("Test", "Address: " + theAddress);
}
return null;
}
}.execute();
More tutorials can be found in the wiki page:
https://github.com/MKergall/osmbonuspack/wiki
Hope this helps.

Related

ProcessBuilder&Runtime exec could not find or load main class in Spring Project

I want to compile a java file and exec its class in another class ( ← This class is a #service of a Spring MVC project ).
The service code is:
#Service
public class MRServiceImp implements MRService {
#Override
public String submitMR(int id, String fd) {
try {
// compile the java file
String[] cmd = {"javac", "P" + id + ".java"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(fd));
Process p = pb.start();
// exec the class file
String[] execmd = {"java", "P" + pz_id};
ProcessBuilder epb = new ProcessBuilder(execmd);
epb.directory(new File(fd));
p = epb.start();
// get normal output
BufferedReader pin = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ptmp = pin.readLine();
while (ptmp != null) {
pout = pout == null ? ptmp + '\n' : pout + ptmp + '\n';
ptmp = pin.readLine();
}
// get error output
pin = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String wout = null;
ptmp = pin.readLine();
while (ptmp != null) {
wout = wout == null ? ptmp + '\n' : wout + ptmp + '\n';
ptmp = pin.readLine();
}
// print output
System.out.println(pout);
System.out.println(wout);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; // for test
}
When this Service is invoked, I always get a Error: Could not find or load main class: P[id]
I cd theFilePath, the P[id].class file is existing.
And I can run java P[id] successfully in theFilePath.
And I try to replace ProcessBuilder with Runtime, like:
#Service
public class MRServiceImp implements MRService {
#Override
public String submitMR(int id, String fd) {
try {
// compile the java file
String[] cmd = {"javac", "P" + id + ".java"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(fd));
Process p = pb.start();
// exec the class file
String execmd = "java", fd + "/P" + pz_id;
p = Runtime.getRuntime().exec(execmd);
// get normal output
BufferedReader pin = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ptmp = pin.readLine();
while (ptmp != null) {
pout = pout == null ? ptmp + '\n' : pout + ptmp + '\n';
ptmp = pin.readLine();
}
// get error output
pin = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String wout = null;
ptmp = pin.readLine();
while (ptmp != null) {
wout = wout == null ? ptmp + '\n' : wout + ptmp + '\n';
ptmp = pin.readLine();
}
// print output
System.out.println(pout);
System.out.println(wout);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; // for test
}
I get the same Error again T^T
IDE is sts-bundle, server is tomcat8
I know what is wrong here.
pb.start(); does not mean the command of pb will be executed immediately.
So if I set pb of command javac hello.java; set epb of command java hello
And I call pb.start(); epb.start(); continuously, I will get an Error: could not find or load main class: hello, because when I exec epb.start(); The former command(pb.start) may have not been executed!
I got 2 solution:
First: set a finally field and exec epb.start() in this field, like:
#Service
public class MRServiceImp implements MRService {
#Override
public String submitMR(int id, String fd) {
try {
// compile the java file
String[] cmd = {"javac", "P" + id + ".java"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(fd));
Process p = pb.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// exec the class file
String[] execmd = {"java", "P" + pz_id};
ProcessBuilder epb = new ProcessBuilder(execmd);
epb.directory(new File(fd));
Process p = epb.start();
}
return null; // for test
}
Second: a trick of bash
#Service
public class MRServiceImp implements MRService {
#Override
public String submitMR(int id, String fd) {
try {
// compile & exec the java file
String[] cmd = {"/bin/bash"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(fd));
Process p = pb.start();
BufferedWriter pbw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
pbw.write("javac *.java;java P" + pz_id+";exit;");
pbw.newLine();
pbw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; // for test
}
I use the second one.

Handle file name duplication when creating files in alfresco

I have a Java-backed webscript in repo tier that creates files (with given name) in a given folder in Alfresco.
To handle the file name duplication issue I wrote this code:
NodeRef node = null;
try {
node = createNode(fullName, folderNodeRefId);
} catch (DuplicateChildNodeNameException e) {
System.out.println("Catched");
boolean done = false;
for (int i = 1; !done; i++) {
String newName = filename + "_" + i + "." + fileFormat;
System.out.println("Duplicate Name. Trying: " + newName);
try {
node = createNode(newName, folderNodeRefId);
done = true;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
System.out.println("Done");
ContentWriter writer = serviceRegistry.getContentService().getWriter(node, ContentModel.PROP_CONTENT, true);
writer.setMimetype(getFileFormatMimetype(fileFormat));
writer.putContent(inputStream);
writer.guessEncoding();
and
private NodeRef createNode(String filename, String folderNodeRefId)
throws InvalidNodeRefException, InvalidTypeException, InvalidQNameException {
System.out.println("In " + filename);
NodeRef folderNodeRef = new NodeRef(folderNodeRefId);
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, filename);
return serviceRegistry.getNodeService()
.createNode(folderNodeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, filename), ContentModel.TYPE_CONTENT,
props)
.getChildRef();
}
The codes work very fine if there is no file name duplication (a new name). But it does nothing when there is a duplication, although it executes without any errors! When I test it it doesn't throw any exceptions but no file is created either!
Any hints about the cause of that?
Thanks,
I tested this code , It's working fine
#Test
public void createNode() {
AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER_NAME);
NodeRef node = null;
String fileFormat = "txt";
String filename = "test";
NodeRef folderNodeRef = getCompanyHome();
//Create first node
node = createNode(filename, folderNodeRef);
try {
node = createNode(filename, folderNodeRef);
} catch (DuplicateChildNodeNameException e) {
System.out.println("Catched");
boolean done = false;
for (int i = 1; !done; i++) {
String newName = filename + "_" + i + "." + fileFormat;
System.out.println("Duplicate Name. Trying: " + newName);
try {
node = createNode(newName, folderNodeRef);
done = true;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
System.out.println("Done");
}
private NodeRef getCompanyHome() {
return nodeLocatorService.getNode("companyhome", null, null);
}
private NodeRef createNode(String filename, NodeRef folderNodeRef) throws InvalidNodeRefException, InvalidTypeException, InvalidQNameException {
System.out.println("In " + filename);
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, filename);
return serviceRegistry.getNodeService().createNode(folderNodeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, filename), ContentModel.TYPE_CONTENT,props).getChildRef();
}

Dynamic Query Builder for Asp.net This Code is Useful Or Not?

I am using this code for dynamic query. Is this useful or not?
This Code for Dynamic Query
I'm using this type code for query builder
This is for Select statement:
public static string SelectQuery(List<string> NoofColumns, string TableName, Dictionary<string, string> WhereCondition)
{
string SqlQuery = string.Empty;
if (NoofColumns.Count == 0)
{
return null; //Columns are not supplied
}
else
{
SqlQuery += "Select ";
foreach (string key in NoofColumns)
{
SqlQuery += key + ", ";
}
SqlQuery = SqlQuery.Remove(SqlQuery.LastIndexOf(","));
//SqlQuery = SqlQuery.Remove(SqlQuery.Length - 1);
SqlQuery += " from " + TableName;
}
if (WhereCondition.Count == 0)
{
return SqlQuery;
}
else
{
SqlQuery += " where ";
foreach (KeyValuePair<string, string> key in WhereCondition)
{
if (key.Value != "")
{
SqlQuery += key.Key + " = '" + key.Value + "'" + " and ";
}
else
{
SqlQuery += key.Key + " and ";
}
}
SqlQuery = SqlQuery.Remove(SqlQuery.LastIndexOf("and"));
return SqlQuery;
}
}
This is for Delete statement:
public static string DeleteQuery(Dictionary<string, string> fields, string TableName, Dictionary<string, string> WhereCondition)
{
string SqlQuery = string.Empty;
if (fields.Count == 0)
{
SqlQuery += "Delete from ";
SqlQuery += TableName + " ";
}
else
{
return null;
}
if (WhereCondition.Count == 0)
{
return SqlQuery;
}
else
{
SqlQuery += " where ";
foreach (KeyValuePair<string, string> key in WhereCondition)
{
SqlQuery += key.Key + " = '" + key.Value + "'" + " and ";
}
SqlQuery = SqlQuery.Remove(SqlQuery.LastIndexOf("and"));
return SqlQuery;
}
}
**//----for Insert ----**
Hashtable args = new Hashtable();
string table;
/// <summary>
/// Constructs Insert object
/// </summary>
/// <param name="table">table name to insert to</param>
public DataLogics(string table)
{
this.table = table;
}
/// <summary>
/// Adds item to Insert object
/// </summary>
/// <param name="name">item name</param>
/// <param name="val">item value</param>
public void Add(string name, object val)
{
args.Add(name, val);
}
/// <summary>
/// Removes item from Insert object
/// </summary>
/// <param name="name">item name</param>
public void Remove(string name)
{
try
{
args.Remove(name);
}
catch
{
throw (new Exception("No such item"));
}
}
This for making query:
/// <summary>
/// Test representation of the Insert object (SQL query)
/// </summary>
/// <returns>System.String</returns>
public string ToString(string Operation, string wherecondition)
{
try
{
StringBuilder s1 = new StringBuilder();
StringBuilder s2 = new StringBuilder();
string query = "";
IDictionaryEnumerator enumInterface = args.GetEnumerator();
bool first = true;
if (Operation == "Insert")
{
while (enumInterface.MoveNext())
{
if (first) first = false;
else
{
s1.Append(", ");
s2.Append(", ");
}
s1.Append(enumInterface.Key.ToString());
if (enumInterface.Value is DateTime)
{
s2.Append("'" + enumInterface.Value + "'");
}
else if (enumInterface.Value is String)
{
s2.Append("'" + Convert.ToString(enumInterface.Value) + "'");
}
else if (enumInterface.Value is Double)
{
s2.Append(Convert.ToDouble(enumInterface.Value.ToString()));
}
else
{
s2.Append(enumInterface.Value.ToString());
}
}
}
if (Operation == "Update")
{
while (enumInterface.MoveNext())
{
if (first) first = false;
else
{
}
//s1.Append("=");
// s2.Append(",");
if (enumInterface.Value is DateTime)
{
//s2.Append("'" + enumInterface.Value + "'");
s1.Append(enumInterface.Key.ToString() + "=" + "'" + enumInterface.Value + "'" + ",");
}
//else if (enumInterface.Value is Int32)
//{
// //s2.Append(enumInterface.Value.ToString());
// s1.Append(enumInterface.Key.ToString() + "=" + enumInterface.Value.ToString() + ",");
//}
//else if (enumInterface.Value is Double)
//{
// //s2.Append(Convert.ToDouble(enumInterface.Value.ToString()));
// s1.Append(enumInterface.Key.ToString() + "=" + Convert.ToDouble(enumInterface.Value.ToString() + ","));
//}
else
{
//s2.Append("'" + Convert.ToString(enumInterface.Value) + "'");
s1.Append(enumInterface.Key.ToString() + "=" + "'" + Convert.ToString(enumInterface.Value) + "'" + ",");
}
query = "Update " + table + " Set " + s1;
}
}
if (Operation == "Update")
{
query = query.Remove(query.LastIndexOf(","));
query = query + " Where " + wherecondition;
}
if (Operation == "Insert")
{
query = "INSERT INTO " + table + " (" + s1 + ") VALUES (" + s2 + ");";
}
SqlConnection con = Create_Connection.Open_Connection();
SqlCommand cmd = new SqlCommand(query, con);
int id = cmd.ExecuteNonQuery();
args.Clear();
con.Close();
string retu = "";
if (id == 1)
{
retu = "1";
}
else if (id == -1)
{
retu = "-1";
}
return retu;
}
catch
{
return "0";
}
}
/// <summary>
/// Gets or sets item into Insert object
/// </summary>
object this[string key]
{
get
{
Debug.Assert(args.Contains(key), "Key not found");
return args[key];
}
set { args[key] = value; }
}

How to used a http conection for send a string like email to a server? on Blackberry

I have a little trouble, i need to create a way to send a string to a server, i a kinda system of complains
try {
String errMsg = validateData();
if(errMsg == null){
String mailURL = CLIENT_CONTACT_URL_MAIL_SERVICE;
mailURL = Utils.replaceAll(mailURL, "#toAddress", TO_DEFAULT_ADDRESS);
String content = "";
content = "Nombre: " + this.names.getText() + "\n";
content += "Apellido: " + this.surname.getText() + "\n";
content += "Email: " + this.email.getText() + "\n";
content += "Telefono: " + this.phone.getText() + "\n";
content += "Mensaje: " + this.complains.getText() + "\n";
mailURL = Utils.replaceAll(mailURL, "#bodyContent", URLUTF8Encoder.encode(content));
Utils.getWebData(mailURL, this);
}else{
Dialog.alert(errMsg);
}
} catch (IOException e) {
Logger.logErrorEvent("Error while sending client contact mail");
}
break;
The following code will send data to server.
static String responce;
static String httpURL;
httpURL=your_server_url+content; //here add your server url like- http://www.google.com/ then append the string content.
try {
if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
&& RadioInfo
.areWAFsSupported(RadioInfo.WAF_WLAN)) {
httpURL += ";interface=wifi"+";ConnectionTimeout=30000";
}
//Dialog.alert(httpURL);
HttpConnection httpConn;
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.POST);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
responce = res.trim();
//Dialog.alert(responce);
httpConn.close();
}catch (Exception e) {
Dialog.alert("Connection Time out");
}
return responce;

How to make a STS using Gmail OAuth

We want to make an STS that outsources the authentication to google.
Following the steps stated in https://developers.google.com/accounts/docs/OAuth2Login?hl=es-ES we have the following code in the Login.aspx generated by the sts web site template in vs2010:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null)
{
//I'm coming from google, already authenticated
FormsAuthentication.SetAuthCookie(GetUserName(Request.QueryString["code"]), false);
Response.Redirect("default.aspx");
}
else
{
//I want to authenticate
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=988046895016.apps.googleusercontent.com&" +
"redirect_uri=" + HttpUtility.UrlEncode("https://localhost/GmailSTS/login.aspx") + "&" +
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email")
);
}
}
But I get an error beacuse wa is not specified in the QueryString, debugging the samples and the generated template I saw that wa,wtrealm,wctx and wct are the parameters needed so I used the state parameter so they roundtrip and get them back:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null)
{
//I'm coming from google, already authenticated
FormsAuthentication.SetAuthCookie("johannsw", false);
String lQueryStrings = HttpUtility.UrlDecode(Request.QueryString["state"]);
lQueryStrings.Replace('?', '&');
Response.Redirect("default.aspx" + "?" + lQueryStrings);
}
else
{
//I want to authenticate
String lState = String.Empty;
foreach (var key in Request.QueryString.AllKeys)
{
if (String.Equals("wa", key) ||
String.Equals("wtrealm", key) ||
String.Equals("wctx", key) ||
String.Equals("wct", key))
lState += key + "=" + Request.QueryString[key] + "&";
}
lState = lState.Remove(lState.Length - 1);
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=988046895016.apps.googleusercontent.com&" +
"redirect_uri=" + HttpUtility.UrlEncode("https://localhost/GmailSTS/login.aspx") + "&" +
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email") + "&" +
"state=" + HttpUtility.UrlEncode(lState)
);
}
}
but now I get an error saying "The HTTP verb POST used to access path '/WebSite1/' is not allowed."
Any hints?
Thanks!
Well finally I made it. Here is how I solved it just in case it helps someone else:
Login.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["code"] != null && Request.QueryString["error"] != "access_denied")
{
// If I got code and no error then
// ask for access_code so I can get user email
//Here I ask for the access_code.
WebRequest requestLogIn = null;
Stream stream = null;
WebResponse response = null;
StreamReader reader = null;
string sendData = "code=" + Request.QueryString["code"] + "&";
sendData += "client_id=" + ObtenerClientID() + "&";
sendData += "client_secret=" + ObtenerClientSecret() + "&";
sendData += "redirect_uri=" + System.Configuration.ConfigurationManager.AppSettings["urlLogin"] + "&"; //TODO: ver si es necesario
sendData += "grant_type=authorization_code";
requestLogIn = WebRequest.Create("https://accounts.google.com/o/oauth2/token");
requestLogIn.Method = "POST";
requestLogIn.ContentType = "application/x-www-form-urlencoded";
byte[] arrayToSend = Encoding.UTF8.GetBytes(sendData);
requestLogIn.ContentLength = arrayToSend.Length;
stream = requestLogIn.GetRequestStream();
stream.Write(arrayToSend, 0, arrayToSend.Length);
stream.Close();
response = requestLogIn.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
reader = new StreamReader(stream);
string responseValue = reader.ReadToEnd();
reader.Close();
var lJSONResponse = new JavaScriptSerializer().Deserialize<JSONResponseToken>(responseValue);
//Now that I have the access_code ask for the user email so I can match him in my base and load claims.
WebRequest myRequest = WebRequest.Create("https://www.googleapis.com/oauth2/v2/userinfo");
myRequest.Method = "GET";
myRequest.Headers.Add("Authorization", "Bearer " + lJSONResponse.Access_Token);
response = myRequest.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
reader = new StreamReader(stream);
responseValue = reader.ReadToEnd();
var lUserMail = new JavaScriptSerializer().Deserialize<JSONResponseUserMail>(responseValue);
// User is authenticated
FormsAuthentication.SetAuthCookie(lUserMail.Email, false);
// default.aspx will load claims
Response.Redirect("default.aspx?" + Request.QueryString.ToString());
}
}
}
else
{
//redirect to google for login.
//Save original url in a cookie for later use.
Guid lGuid = Guid.NewGuid();
CreateContextCookie(lGuid.ToString(), this.Request.Url.AbsoluteUri);
Response.Redirect(
"https://accounts.google.com/o/oauth2/auth?" +
"response_type=code&" +
"client_id=" + ObtenerClientID() + "&" +
//I want to return here again
"redirect_uri=" + HttpUtility.UrlEncode(System.Configuration.ConfigurationManager.AppSettings["urlLogin"]) + "&" +
//Add scope so I can get user mail.
"scope=" + HttpUtility.UrlEncode("https://www.googleapis.com/auth/userinfo.email") + "&" +
//Reference to the cookie so I can get the original url again
"state=" + HttpUtility.UrlEncode(lGuid.ToString())
);
}
}
Default.aspx.cs:
protected void Page_PreRender(object sender, EventArgs e)
{
String lCode = Request.QueryString["code"];
String lSTate = Request.QueryString["state"];
var ctxCookie = this.Request.Cookies[lSTate];
var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(new Uri(ctxCookie.Value));
//Erase cookie
var contextCookie = new HttpCookie(lSTate)
{
Expires = DateTime.UtcNow.AddDays(-1)
};
//process login request
SecurityTokenService sts =
new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current);
SignInResponseMessage responseMessage =
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, this.User, sts);
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.Response);
this.Response.Cookies.Add(contextCookie);
}

Resources