REST API: pass parameters to preparedQuery in Vertx pgclient - rest

This is the response from my API:
"The number of parameters to execute should be consistent with the expected number of parameters = [2] but the actual number is [0]."
I use pgClient, Vert.x 3.9.3 and consume various REST API's without problems, but....in this query (probably it's wrong)
private static final String SELECT_CBA = "select art.leyenda, $1::numeric(10,3) as cantidad, uni.abreviatura, \r"
+ "round(((art.precio_costo * (art.utilidad_fraccionado/100)) + art.precio_costo) * $2::numeric(10,3),2) as totpagar \r"
+ "FROM public.articulos art join public.unidades uni on uni.idunidad = art.idunidad \r"
+ "WHERE (substring(art.codigobarra,1,2) = \'$3\' and substring(art.codigobarra,3,6) = \'$4\')";
Some explanation
$1 and $2 are the same parameters; $2 and $3 must be quoted parameters.
This is my rest verticle:
poolClient = PgPool.pool(vertx, options, poolOptions);
bizArticulo = new BizArticulo(poolClient);
Router router = Router.router(vertx);
router.route("/api/articulos*").handler(BodyHandler.create());
router.get("/api/articulos").handler(bizArticulo::getAll);
router.get("/api/articulos/:cantcomp1/:cantcomp2/:tipoprod/:prodpadre").handler(bizArticulo::getOneReadingBarcode);
Where :cantcomp1 -> $1, :cantcomp2 -> $2, :tipoprod -> $3 and $4 -> :prodpadre
and finally, this my "business"
public void getOneReadingBarcode(RoutingContext routingContext) {
HttpServerResponse response = routingContext.response();
pgClient
.preparedQuery(SELECT_CBA)
.execute(ar -> {
if (ar.succeeded()) {
RowSet<Row> rows = ar.result();
List<Articulo> articulos = new ArrayList<>();
rows.forEach(row -> {
articulos.add(fromBarCode(row));
});
response.putHeader("content-type", "application/json; charset=utf-8")
.setStatusCode(200)
.end(Json.encodePrettily(articulos));
} else {
System.out.println("Failure: " + ar.cause().getMessage());
response.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodePrettily(ar.cause().getMessage()));
}
});
}
In Postman, I wrote:
192.168.0.15:8092/api/articulos/0.750/0.750/20/021162; where I assume the parameters match, but it returns the error mentioned above.
¿What's wrong? Any help would be appreciated
Ernesto

Ok, I answer to myself...
First: little fix to my query (SELECT_CB), I put the parameters $1, $2... in parentheses..
private static final String SELECT_CBA = "select art.leyenda, ($1::numeric(10,3)) as cantidad, uni.abreviatura, \r"
+ "round(((art.precio_costo * (art.utilidad_fraccionado/100)) + art.precio_costo) * ($2::numeric(10,3)),2) as totpagar \r"
+ "FROM public.articulos art join public.unidades uni on uni.idunidad = art.idunidad \r"
+ "WHERE (substring(art.codigobarra,1,2) = ($3) and substring(art.codigobarra,3,6) = ($4))";
Second: got the params from context (see router.context in previous question)
Double cantComprada1 = Double.parseDouble(routingContext.request().getParam("cantcomp1"));
Double cantComprada2 = Double.parseDouble(routingContext.request().getParam("cantcomp2"));
String tipoProducto = routingContext.request().getParam("tipoprod");
String productoPadre = routingContext.request().getParam("prodpadre");
and Third: put the params as arguments
pgClient
.preparedQuery(SELECT_CBA)
.execute(Tuple.of(cantComprada1, cantComprada2, tipoProducto, productoPadre), ar -> {
......
......
}
All work's fine

Related

Is it possible to use the OpenStack.NET SDK with SoftLayer object storage?

SoftLayer Object Storage is based on the OpenStack Swift object store.
SoftLayer provide SDKs for their object storage in Python, Ruby, Java and PHP, but not in .NET. Searching for .NET SDKs for OpenStack, I came across OpenStack.NET.
Based on this question OpenStack.NET is designed for use with Rackspace by default, but can be made to work with other OpenStack providers using CloudIdentityWithProject and OpenStackIdentityProvider.
SoftLayer provide the following information for connecting to their Object Storage:
Authentication Endpoint
Public: https://mel01.objectstorage.softlayer.net/auth/v1.0/
Private: https://mel01.objectstorage.service.networklayer.com/auth/v1.0/
Username:
SLOS123456-1:email#example.com
API Key (Password):
1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
It's not obvious how this would map to the fields of CloudIdentityWithProject, and OpenStackIdentityProvider but I tried the following and a few other combinations of project name / username / uri:
var cloudIdentity = new CloudIdentityWithProject()
{
ProjectName = "SLOS123456-1",
Username = "email#example.com",
Password = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
};
var identityProvider = new OpenStackIdentityProvider(
new Uri("https://mel01.objectstorage.softlayer.net/auth/v1.0/"),
cloudIdentity);
var token = identityProvider.GetToken(null);
However, in all cases I received the following error:
Unable to authenticate user and retrieve authorized service endpoints
Based on reviewing the source code for SoftLayer's other language libraries and for OpenStack.NET, it looks like SoftLayer's object storage uses V1 auth, while OpenStack.NET is using V2 auth.
Based on this article from SoftLayer and this article from SwiftStack, V1 auth uses a /auth/v1.0/ path (like the one provided by SoftLayer), with X-Auth-User and X-Auth-Key headers as arguments, and with the response contained in headers like the following:
X-Auth-Token-Expires = 83436
X-Auth-Token = AUTH_tk1234567890abcdef1234567890abcdef
X-Storage-Token = AUTH_tk1234567890abcdef1234567890abcdef
X-Storage-Url = https://mel01.objectstorage.softlayer.net/v1/AUTH_12345678-1234-1234-1234-1234567890ab
X-Trans-Id = txbc1234567890abcdef123-1234567890
Connection = keep-alive
Content-Length = 1300
Content-Type = text/html; charset=UTF-8
Date = Wed, 14 Oct 2015 01:19:45 GMT
Whereas V2 auth (identity API V2.0) uses a /v2.0/tokens path, with the request and response in JSON objects in the message body.
Based on the OpenStackIdentityProvider class in OpenStack.NET I hacked together my own SoftLayerOpenStackIdentityProvider like this:
using JSIStudios.SimpleRESTServices.Client;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenStack.Authentication;
using System;
using System.Linq;
using System.Collections.Generic;
namespace OpenStackTest1
{
public class SoftLayerOpenStackIdentityProvider : CloudIdentityProvider
{
public SoftLayerOpenStackIdentityProvider(
Uri urlBase, CloudIdentity defaultIdentity)
: base(defaultIdentity, null, null, urlBase)
{
if (urlBase == null)
throw new ArgumentNullException("urlBase");
}
public override UserAccess GetUserAccess(
CloudIdentity identity, bool forceCacheRefresh = false)
{
identity = identity ?? DefaultIdentity;
Func<UserAccess> refreshCallback =
() =>
{
// Set up request headers.
Dictionary<string, string> headers =
new Dictionary<string, string>();
headers["X-Auth-User"] = identity.Username;
headers["X-Auth-Key"] = identity.APIKey;
// Make the request.
JObject requestBody = null;
var response = ExecuteRESTRequest<JObject>(
identity,
UrlBase,
HttpMethod.GET,
requestBody,
headers: headers,
isTokenRequest: true);
if (response == null || response.Data == null)
return null;
// Get response headers.
string authToken = response.Headers.Single(
h => h.Key == "X-Auth-Token").Value;
string storageUrl = response.Headers.Single(
h => h.Key == "X-Storage-Url").Value;
string tokenExpires = response.Headers.Single(
h => h.Key == "X-Auth-Token-Expires").Value;
// Convert expiry from seconds to a date.
int tokenExpiresSeconds = Int32.Parse(tokenExpires);
DateTimeOffset tokenExpiresDate =
DateTimeOffset.UtcNow.AddSeconds(tokenExpiresSeconds);
// Create UserAccess via JSON deseralization.
UserAccess access = JsonConvert.DeserializeObject<UserAccess>(
String.Format(
"{{ " +
" token: {{ id: '{0}', expires: '{1}' }}, " +
" serviceCatalog: " +
" [ " +
" {{ " +
" endpoints: [ {{ publicUrl: '{2}' }} ], " +
" type: 'object-store', " +
" name: 'swift' " +
" }} " +
" ], " +
" user: {{ }} " +
"}}",
authToken,
tokenExpiresDate,
storageUrl));
if (access == null || access.Token == null)
return null;
return access;
};
string key = string.Format("{0}:{1}", UrlBase, identity.Username);
var userAccess = TokenCache.Get(key, refreshCallback, forceCacheRefresh);
return userAccess;
}
protected override string LookupServiceTypeKey(IServiceType serviceType)
{
return serviceType.Type;
}
}
}
Because some of the members of UserAccess (like IdentityToken and Endpoint) have no way to set their fields (the objects have only a default constructor and only read-only members), I had to create the UserAccess object by deserializing some temporary JSON in a similar format as returned by the V2 API.
This works, ie I can now connect like this:
var cloudIdentity = new CloudIdentity()
{
Username = "SLOS123456-1:email#example.com",
APIKey = "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
};
var identityProvider = new SoftLayerOpenStackIdentityProvider(
new Uri("https://mel01.objectstorage.softlayer.net/auth/v1.0/"),
cloudIdentity);
var token = identityProvider.GetToken(null);
And then get access to files etc like this:
var cloudFilesProvider = new CloudFilesProvider(identityProvider);
var containers = cloudFilesProvider.ListContainers();
var stream = new MemoryStream();
cloudFilesProvider.GetObject("testcontainer", "testfile.dat", stream);
However, is there a better way than this to use SoftLayer Object Storage from .NET?
I briefly also looked at the OpenStack SDK for .NET (a different library to OpenStack.NET), but it too seems to be based on V2 auth.

401 when adding customer with QB Online API v3

I keep getting a 401 when I try to add a customer with QB Online API v3. The xml works in the API Explorer, and I'm able to query customers from my program. I just can't POST. What am I doing wrong?
string reqBody = "<Customer xmlns=\"http://schema.intuit.com/finance/v3\" domain=\"QBO\" sparse=\"false\"><DisplayName>Empire Records</DisplayName>"
+ "<BillAddr><Line1>201 S King St</Line1><City>Seattle</City><CountrySubDivisionCode>WA</CountrySubDivisionCode><PostalCode>98104</PostalCode></BillAddr>"
+ "<PrimaryPhone><FreeFormNumber>425-867-5309</FreeFormNumber></PrimaryPhone><PrimaryEmailAddr><Address>helpme#thefly.con</Address></PrimaryEmailAddr></Customer>";
IConsumerRequest req = session.Request();
req = req.Post().WithRawContentType("application/xml").WithRawContent(System.Text.Encoding.ASCII.GetBytes(reqBody));
req.AcceptsType = "application/xml";
string response = req.Post().ForUrl("https://quickbooks.api.intuit.com/v3/company/" + realmID + "/customer").ToString()
OAuthConsumerContext consumerContext1 = new OAuthConsumerContext
{
ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
SignatureMethod = SignatureMethod.HmacSha1,
ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"].ToString()
};
OAuthSession oSession1 = new OAuthSession(consumerContext1, "https://oauth.intuit.com/oauth/v1/get_request_token",
"https://workplace.intuit.com/Connect/Begin",
"https://oauth.intuit.com/oauth/v1/get_access_token");
oSession1.ConsumerContext.UseHeaderForOAuthParameters = true;

https://api.twitter.com/oauth/request_token Fails in Blackberry Native SDK

I am trying to connect to Twitter though oAuth.I am making a POST request to the API https://api.twitter.com/oauth/request_token.
Here is is example of my Base signature string
POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Fapi.ec2.phunware.com%252Fapi%252Ftwitter%26oauth_consumer_key%3D6jq5dNZcccoPbApAJ0sOaA%26oauth_nonce%3DN2ZiMjViYzhlMDUxNDIyZWIwYjQ4NmU0ZjM1MDg4NTY%3D%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1362843354%26oauth_version%3D1.0
I used the tool http://quonos.nl/oauthTester/ to verify my base signature.
Here is the corresponding header
OAuth oauth_callback="http%3A%2F%2Fapi.ec2.phunware.com%2Fapi%2Ftwitter",oauth_consumer_key="6jq5dNZcccoPbApAJ0sOaA",oauth_nonce="N2ZiMjViYzhlMDUxNDIyZWIwYjQ4NmU0ZjM1MDg4NTY=",oauth_signature_method="HMAC-SHA1",oauth_signature="7ney2RxElbHUl2t1Jnz57pQpmFs%3D",oauth_timestamp="1362843354",oauth_version="1.0"
I tried the following command in my MAC terminal
curl --request 'POST' 'https://api.twitter.com/oauth/request_token' --header 'Authorization: OAuth oauth_callback="http%3A%2F%2Fapi.ec2.phunware.com%2Fapi%2Ftwitter",oauth_consumer_key="6jq5dNZcccoPbApAJ0sOaA",oauth_nonce="N2ZiMjViYzhlMDUxNDIyZWIwYjQ4NmU0ZjM1MDg4NTY=",oauth_signature_method="HMAC-SHA1",oauth_signature="7ney2RxElbHUl2t1Jnz57pQpmFs%3D",oauth_timestamp="1362843354",oauth_version="1.0"' --verbose
And i get 401 unauthorized error. I tried to set the oauth_callback ="oob" but I still get the same error.
Please help. I am using Blackberry Native SDK to code. I am pasting the code here. I get 204 error when I try via Blackberry 10.1 Simulator.
QByteArray Twitter::generateTimeStamp()
{
QDateTime current = QDateTime::currentDateTime();
uint seconds = current.toTime_t();
return QString::number(seconds,10).toUtf8();
}
QByteArray Twitter::generateNonce()
{
QString nonce = QUuid::createUuid().toString();
nonce.remove(QRegExp("[^a-zA-Z\\d\\s]"));
qDebug()<< nonce.toUtf8();
return nonce.toUtf8().toBase64();
}
QByteArray Twitter::generateSignatureBase(const QUrl& url, HttpMethod method, const QByteArray& timestamp, const QByteArray& nonce,bool addCallbackURL)
{
QList<QPair<QByteArray, QByteArray> > urlParameters = url.encodedQueryItems();
QList<QByteArray> normParameters;
QListIterator<QPair<QByteArray, QByteArray> > i(urlParameters);
while(i.hasNext()){
QPair<QByteArray, QByteArray> queryItem = i.next();
QByteArray normItem = queryItem.first + '=' + queryItem.second;
normParameters.append(normItem);
}
//consumer key
normParameters.append(QByteArray("oauth_consumer_key=") + consumer->consumerKey());
//token
if(accessToken != NULL){
normParameters.append(QByteArray("oauth_token=") + accessToken->oauthToken());
}
//signature method, only HMAC_SHA1
normParameters.append(QByteArray("oauth_signature_method=HMAC-SHA1"));
//time stamp
normParameters.append(QByteArray("oauth_timestamp=") + timestamp);
//nonce
normParameters.append(QByteArray("oauth_nonce=") + nonce);
//version
normParameters.append(QByteArray("oauth_version=1.0"));
//callback url
if(addCallbackURL)
normParameters.append(QByteArray("oauth_callback=") + QByteArray(CALLBACK_URL).toPercentEncoding());
//OAuth spec. 9.1.1.1
qSort(normParameters);
qDebug()<<normParameters;
QByteArray normString;
QListIterator<QByteArray> j(normParameters);
while (j.hasNext()) {
normString += j.next().toPercentEncoding();
normString += "%26";
}
normString.chop(3);
qDebug()<<normString;
//OAuth spec. 9.1.2
QString urlScheme = url.scheme();
QString urlPath = url.path();
QString urlHost = url.host();
QByteArray normUrl = urlScheme.toUtf8() + "://" + urlHost.toUtf8() + urlPath.toUtf8();
QByteArray httpm;
switch (method)
{
case GET:
httpm = "GET";
break;
case POST:
httpm = "POST";
break;
case DELETE:
httpm = "DELETE";
break;
case PUT:
httpm = "PUT";
break;
}
qDebug()<<"signature base="<<httpm + '&' + normUrl.toPercentEncoding() + '&' + normString;
//OAuth spec. 9.1.3
return httpm + '&' + normUrl.toPercentEncoding() + '&' + normString;
}
QByteArray Twitter::generateAuthorizationHeader( const QUrl& url, HttpMethod method,bool addCallbackURL )
{
QByteArray timeStamp = generateTimeStamp();
QByteArray nonce = generateNonce();
QByteArray baseString = generateSignatureBase(url, method, timeStamp, nonce,addCallbackURL);
QByteArray key = consumer->consumerSecret() + '&';
if(accessToken != NULL)
key = key + accessToken->oauthTokenSecret();
QByteArray signature = HMACSH1::hmacSha1(key,baseString).toPercentEncoding();
QByteArray header;
header += "OAuth ";
if(addCallbackURL)
header += "oauth_callback=\"" + QByteArray(CALLBACK_URL).toPercentEncoding() + "\",";
header += "oauth_consumer_key=\"" + consumer->consumerKey() + "\",";
header += "oauth_nonce=\"" + nonce + "\",";
header += "oauth_signature_method=\"HMAC-SHA1\",";
header += "oauth_signature=\"" + signature + "\",";
header += "oauth_timestamp=\"" + timeStamp + "\",";
if(accessToken != NULL)
header += "oauth_token=\"" + accessToken->oauthToken() + "\",";
header += "oauth_version=\"1.0\"";
qDebug()<<"header =" <<header;
return header;
}
void Twitter::requestForToken()
{
QUrl url(TWITTER_REQUEST_TOKEN_URL);
QByteArray oauthHeader = generateAuthorizationHeader(url, POST,true);
QNetworkRequest req(url);
req.setRawHeader("Authorization", oauthHeader);
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
req.setHeader(QNetworkRequest::ContentLengthHeader,"0");
QNetworkReply *reply = networkAccessManager->post(req, QByteArray());
connect(networkAccessManager, SIGNAL(finished ( QNetworkReply*)), this, SLOT(tokenFetchSuccessfull(QNetworkReply*)));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(tokenFetchFailed(QNetworkReply::NetworkError)));
qDebug()<<"Request For Token";
}
You mentioned you are using the Native SDK, are you also using Cascades? If so, you may have better luck using the bb-cascades-oauth library from GitHub. It has built in support for OAuth1 and OAuth2.
Also, it seems that having incorrect timestamps can be a common problem, based on the tips found here, so make sure that your simulator has the correct date and time.
Another developer here found that the http://quonos.nl/oauthTester/ was requiring a double escaped header which was incorrect, and causing 401 errors when making an actual authentication request. I noticed you used the same tester, and also have the double escaping in your base signature string above, so you might want to try without the double escaping.

force.com callout exception Unable to tunnel through proxy

We make a callout from one Salesforce org to another Salesforce org using the REST API. That worked until end of november. We didn't make any changes at the affected classes or configuration.
Now, while sending a request to the rest api a callout exception will be thrown with the message : "Unable to tunnel through proxy. Proxy returns "HTTP/1.0 503 Service Unavailable".
The authorisation to the rest api is done by session id.
Does anyone have any idea what the problem is?
Here the code snipped:
final String WS_ENDPOINT = 'https://login.salesforce.com/services/Soap/c/24.0';
final String REST_ENDPOINT = 'https://eu2.salesforce.com/services/apexrest/UsageReporterService';
final String USERNAME = '*****';
final String PASSWORD = '*****';
HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
req.setMethod('POST');
req.setEndpoint(REST_ENDPOINT);
req.setHeader('Content-Type', 'application/json');
req.setTimeout(60000);
HTTP hLogin = new HTTP();
HTTPRequest reqLogin = new HTTPRequest();
reqLogin.setMethod('POST');
reqLogin.setEndpoint(WS_ENDPOINT);
reqLogin.setHeader('Content-Type', 'text/xml');
reqLogin.setHeader('SOAPAction', 'login');
reqLogin.setTimeout(60000);
reqLogin.setCompressed(false);
// get a valid session id
String sessionId;
String loginSoap = '<?xml version="1.0" encoding="UTF-8"?>';
loginSoap += '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:enterprise.soap.sforce.com">';
loginSoap += '<soapenv:Body>';
loginSoap += '<urn:login>';
loginSoap += '<urn:username>' + USERNAME + '</urn:username>';
loginSoap += '<urn:password>' + PASSWORD + '</urn:password>';
loginSoap += '</urn:login>';
loginSoap += '</soapenv:Body>';
loginSoap += '</soapenv:Envelope>';
reqLogin.setBody(loginSoap);
HTTPResponse respLogin;
try {
respLogin = hLogin.send(reqLogin);
} catch(CalloutException c){
return null;
}
System.debug('++++++'+respLogin.getStatus() + ': ' + respLogin.getBody());
Dom.Document doc = new Dom.Document();
doc.load(respLogin.getBody());
Dom.XMLNode root = doc.getRootElement();
String ns = root.getNamespace();
Dom.XMLNode bodyEl = root.getChildElements()[0];
if(bodyEl.getChildElements()[0].getName().equals('loginResponse')){
sessionId = bodyEl.getChildElements()[0].getChildElement('result', ns).getChildElement('sessionId', ns).getText();
}
// finished getting session Id
if(sessionId != null){ // login was successfull
req.setHeader('Authorization', 'Bearer ' + sessionId);
// serialize data into json string
UsageReporterModel usageReporterData = new UsageReporterModel();
String inputStr = usageReporterData.serialize();
req.setBody('{ "usageReportData" : ' + inputStr + '}');
// fire!
HTTPResponse resp;
try {
resp = h.send(req);
} catch(CalloutException c){
return null;
}
}
I suspect this will relate to a change of IP addresses for one of the org's which haven't been whitelisted correctly (or added to the "network access" object). With it being Salesforce to Salesforce I would hope that Salesforce.com support can assist?

google maps, cellid to location

According to this sample:
http://www.codeproject.com/KB/mobile/DeepCast.aspx
It's possible to request a gps coordinate (longitude & latitude) including range when sending cellid information (MCC, MNC, towerid, etc)
Can someone tell me the actual parameter to request/post to this address?
http://www.google.com/glm/mmap
It could be something like this
http://www.google.com/glm/mmap?mcc=xxx&mnc=xxx&towerid=xxx
And i would like to know what response we would get.
I have observe OpenCellid website and they provide some nice API to begin with, but i want to know about that in google map too (since they have more completed database).
OpenCellID API
Here is example for work with
#!/usr/bin/python
country = 'fr'
#device = 'Sony_Ericsson-K750'
device = "Nokia N95 8Gb"
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
mmap_url = 'http://www.google.com/glm/mmap'
geo_url = 'http://maps.google.com/maps/geo'
from struct import pack, unpack
from httplib import HTTP
import urllib2
def fetch_latlong_http(query):
http = HTTP('www.google.com', 80)
http.putrequest('POST', '/glm/mmap')
http.putheader('Content-Type', 'application/binary')
http.putheader('Content-Length', str(len(query)))
http.endheaders()
http.send(query)
code, msg, headers = http.getreply()
result = http.file.read()
return result
def fetch_latlong_urllib(query):
headers = { 'User-Agent' : user_agent }
req = urllib2.Request(mmap_url, query, headers)
resp = urllib2.urlopen(req)
response = resp.read()
return response
fetch_latlong = fetch_latlong_http
def get_location_by_cell(cid, lac, mnc=0, mcc=0, country='fr'):
b_string = pack('>hqh2sh13sh5sh3sBiiihiiiiii',
21, 0,
len(country), country,
len(device), device,
len('1.3.1'), "1.3.1",
len('Web'), "Web",
27, 0, 0,
3, 0, cid, lac,
0, 0, 0, 0)
bytes = fetch_latlong(b_string)
(a, b,errorCode, latitude, longitude, c, d, e) = unpack(">hBiiiiih",bytes)
latitude = latitude / 1000000.0
longitude = longitude / 1000000.0
return latitude, longitude
def get_location_by_geo(latitude, longitude):
url = '%s?q=%s,%s&output=json&oe=utf8' % (geo_url, str(latitude), str(longitude))
return urllib2.urlopen(url).read()
if __name__ == '__main__':
print get_location_by_cell(20465, 495, 3, 262)
print get_location_by_cell(20442, 6015)
print get_location_by_cell(1085, 24040)
print get_location_by_geo(40.714224, -73.961452)
print get_location_by_geo(13.749113, 100.565327)
You could use the Google Location API which is used by Firefox (Example see at http://www.mozilla.com/en-US/firefox/geolocation/ ) which has the url www.google.com/loc/json/. In fact this is JSON based webservice and a minimal Perl Example Look like this:
use LWP;
my $ua = LWP::UserAgent->new;
$ua->agent("TestApp/0.1 ");
$ua->env_proxy();
my $req = HTTP::Request->new(POST => 'https://www.google.com/loc/json');
$req->content_type('application/jsonrequest');
$req->content('{"cell_towers": [{"location_area_code": "8721", "mobile_network_code": "01", "cell_id": "7703", "mobile_country_code": "262"}], "version": "1.1.0", "request_address": "true"}');
# Pass request to the user agent and get a response back
my $res = $ua->request($req);
# Check the outcome of the response
if ($res->is_success) {
print $res->content;
} else {
print $res->status_line, "\n";
return undef;
}
Please keep in mind that Google has not officially opened this API for other uses...
The new place for the Google location API is the following :
https://developers.google.com/maps/documentation/geolocation/intro
With this API, you can retrieve a location from Cell information (cellid, mcc, mnc, and lac)
Base on GeolocationAPI, here are some parts of my code:
import java.io.IOException;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
//http://code.google.com/p/google-gson/
import com.google.gson.stream.JsonWriter;
...
/**
* Requests latitude and longitude from Google.
*
* #param gsmParams
* {#link GsmParams}
* #return an {#link HttpURLConnection} containing connection to Google
* lat-long data.
* #throws IOException
*/
public HttpURLConnection requestLatlongFromGoogle(GsmParams gsmParams)
throws IOException {
// prepare parameters for POST method
StringWriter sw = new StringWriter();
JsonWriter jw = new JsonWriter(sw);
try {
jw.beginObject();
jw.name("host").value("localhost");
jw.name("version").value("1.1.0");
jw.name("request_address").value(true);
jw.name("cell_towers");
jw.beginArray().beginObject();
jw.name("cell_id").value(gsmParams.getCid());
jw.name("location_area_code").value(gsmParams.getLac());
jw.name("mobile_network_code").value(gsmParams.getMnc());
jw.name("mobile_country_code").value(gsmParams.getMcc());
jw.endObject().endArray().endObject();
} finally {
try {
jw.close();
} catch (IOException ioe) {
}
try {
sw.close();
} catch (IOException ioe) {
}
}
final String JsonParams = sw.toString();
final String GoogleLocJsonUrl = "http://www.google.com/loc/json";
// post request
URL url = null;
HttpURLConnection conn = null;
url = new URL(GoogleLocJsonUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout((int) 30e3);
conn.setReadTimeout((int) 30e3);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.getOutputStream().write(JsonParams.getBytes());
conn.getOutputStream().flush();
conn.getOutputStream().close();
int resCode = conn.getResponseCode();
if (resCode == Http_BadRequest || resCode != Http_Ok) {
throw new IOException(String.format(
"Response code from Google: %,d", resCode));
}
return conn;
}
The object GsmParams is just a Java bean containing GSM parameters MCC, MNC, LAC, CID. I think you can create a same class easily.
After getting connection, you can call conn.getInputStream() and get results from Google Maps. Then use JsonReader to parse data...
As noted in other threads also check out https://labs.ericsson.com/apis/mobile-location/documentation/cell-id-look-up-api for a free cell-ID database to get coordinates from cellid, mcc, mnc, and lac .