J2ME App in Blackberry Network connectivity issue - jar

I have developed a J2ME App which i tried in Blackberry device. Application launched successfully but when i am making a network call its throwing exception. Currently the Blackberry device which i own doesn't have BIS(Blackberry Internet Service) plan enabled. I am testing it in Blackberry OS version less than six.
Here is my Coding for HTTP Get Method
public static Vector httpGet(String uri, String param) {
Vector buf = new Vector();
try {
String parameter = param;
String url = uri + "?" + parameter;
System.out.println("Passed URL:" + uri + "?" + parameter);
HttpConnection hc = (HttpConnection) Connector.open(url);
hc.setRequestMethod(HttpConnection.GET);
Commons.print(hc.getResponseCode() + ":" + HttpConnection.HTTP_OK
+ ":" + hc.getResponseMessage());
if (hc.getResponseCode() >= 400) {
hc = null;
return null;
}
InputStream inn = hc.openInputStream();
if (inn == null)
return null;
DataInputStream in = new DataInputStream(inn);
String st = "";
while ((st = readLine(in)) != null) {
buf.addElement(st);
}
if (in != null) {
in.close();
}
if (hc != null) {
hc.close();
setStatus(DataMembers.okStatus);
}
} catch (Exception ex) {
System.out.println("Error:" + ex.toString());
setStatus(DataMembers.failStatus);
buf = null;
}
return buf;
}
Does Blackberry requires BIS connection for making a network call? I am not appending any manual connection String to my URL.

Related

Openssl-aes-256-cbc encryption in iOS

I am working on Encryption,Decryption in swift OpenSSl AES-256-CBC. I have checked with many third- party libraries or pods i.e. CryptoSwift and many others. But I am always getting HMAc is Not valid from Php back end team.
Where as in android they have done this:
Following is my android method:
public EncryptedData encrypt(Object data) throws Exception {
String text;
if (data instanceof String) {
text = String.valueOf(data);
} else {
text = (new Gson()).toJson(data);
}
if (!this.doAction) {
return new EncryptedData(text, "");
} else {
this.ivspec = new IvParameterSpec(this.getIV1().getBytes());
this.keyspec = new SecretKeySpec(this.getKey1().getBytes(), "AES");
if (text != null && text.length() != 0) {
byte[] encrypted;
try {
this.cipher.init(Cipher.ENCRYPT_MODE, this.keyspec, this.ivspec);
encrypted = this.cipher.doFinal(this.padString(text).getBytes());
} catch (Exception var5) {
throw new Exception("[encrypt] " + var5.getMessage());
}
String encryptedData = new String(Base64.encode(encrypted, Base64.DEFAULT))
.replace("\n", "");
SecretKeySpec macKey = new SecretKeySpec(getKey1().getBytes(), "HmacSHA256");
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
hmacSha256.init(macKey);
hmacSha256.update((Base64.encodeToString(getIV1().getBytes(), Base64.DEFAULT).trim() + encryptedData.trim()).getBytes());
byte[] calcMac = hmacSha256.doFinal();
return new EncryptedData(encryptedData, bytesToHex(calcMac));
} else {
throw new Exception("Empty string");
}
}
}
Any one know how this will works in iOS.
Any help will be appreciated.
Thanks
Here is a simple HMAC implement in Swift 4:
0xa6a/HMAC
No third-party library is needed. Just create a bridging header and import <CommonCrypto/CommonCrypto.h> in it.
Have a try and happy coding.

Quickbooks Http Web Request code gives 400 Server error

I am using Quickbooks V3 SDK.It was also giving 400 error as In October 2014 they had changed their link from https://quickbooks.api.intuit.com/ to sandbox.quickbooks.api.intuit.com/, after correcting I can fetch results and can perform crud operations using its mentioned classes.
ServiceContext serviceContext = getServiceContext(profile);
serviceContext.IppConfiguration.BaseUrl.Qbo = "https://sandbox-quickbooks.api.intuit.com/";
QueryService<Item> ItemQueryService = new QueryService<Item>(serviceContext);
return ItemQueryService.Select(c => c).ToList();
This code works perfectly.
But when i try to perform the same operation as JSON request with HTTP web request, it gives me 400 error.
I am pasting HTTP Web request code below.
HttpContext.Current.Session["serviceEndPoint"] = "https://qb.sbfinance.intuit.com/v3/company/" + profile.RealmId +"/item&query=select * from item"; //
OAuthConsumerContext consumerContext = OAuthCR();
OAuthSession oSession = OAuthSession(consumerContext);
oSession.ConsumerContext.UseHeaderForOAuthParameters = true;
oSession.AccessToken = new TokenBase
{
Token = profile.OAuthAccessToken,
ConsumerKey = "qyprdB0F3beIfmSTdvpLG5J46xPGm2",
TokenSecret = profile.OAuthAccessTokenSecret
};
IConsumerRequest conReq = oSession.Request();
conReq = conReq.Post();
conReq.AcceptsType = "application/json";
conReq = conReq.ForUrl(HttpContext.Current.Session["serviceEndPoint"].ToString());
string header = conReq.Context.GenerateSignatureBase();
try
{
string res = conReq.ReadBody();
}
catch (WebException we)
{
HttpWebResponse rsp = (HttpWebResponse)we.Response;
if (rsp != null)
{
try
{
using (StreamReader reader = new StreamReader(rsp.GetResponseStream()))
{
string res2 = rsp.StatusCode + " | " + reader.ReadToEnd();
}
}
catch (Exception)
{
string res = "Status code: " + rsp.StatusCode;
}
}
else
{
string res = "Error Communicating with Mock Service" + we.Message;
}
}
}
They have mentioned wrong url on their sdk which is https://qb.sbfinance.intuit.com/v3/company/xxxxxxxxx/
but correct one is
https://sandbox-quickbooks.api.intuit.com/v3/company/xxxxxxxxxx/

Google Maps Works on Localhost, Fails in IIS

I have a google map application that runs perfectly fine on local host. When I publish the application on IIS, the google api key v2 returns a 404 error.
I do not have google key, I am running without a key on a .net 4.0 Framework. Is the error because of a setting in IIS or I would need a key to query google REST API.
Below is an excerpt of my code -
private string GetLatitudeLongitudeFromAddress(string url)
{
string latitudeLongitude = string.Empty;
WriteToFile(path, "Entering GetLatitudeLongitudeFromAddress - url in parameter = "+url);
try
{
WebResponse response = null;
bool is_geocoded = true;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
//WriteToFile(path, "request response = " + request.GetResponse().ToString());
response = request.GetResponse();
WriteToFile(path, "response returned = "+response.ToString());
string lat = "";
string lng = "";
string loc_type = "";
if (response != null)
{
XPathDocument document = new XPathDocument(response.GetResponseStream());
XPathNavigator navigator = document.CreateNavigator();
// get response status
XPathNodeIterator statusIterator = navigator.Select("/GeocodeResponse/status");
while (statusIterator.MoveNext())
{
if (statusIterator.Current.Value != "OK")
{
is_geocoded = false;
}
}
// get results
if (is_geocoded)
{
XPathNodeIterator resultIterator = navigator.Select("/GeocodeResponse/result");
while (resultIterator.MoveNext())
{
XPathNodeIterator geometryIterator = resultIterator.Current.Select("geometry");
while (geometryIterator.MoveNext())
{
XPathNodeIterator locationIterator = geometryIterator.Current.Select("location");
while (locationIterator.MoveNext())
{
XPathNodeIterator latIterator = locationIterator.Current.Select("lat");
while (latIterator.MoveNext())
{
lat = latIterator.Current.Value;
//Console.WriteLine("Latitude value = {0}", lat);
latitudeLongitude = lat;
}
XPathNodeIterator lngIterator = locationIterator.Current.Select("lng");
while (lngIterator.MoveNext())
{
lng = lngIterator.Current.Value;
//Console.WriteLine("Longitude value = {0}", lng);
latitudeLongitude = latitudeLongitude + "#" + lng;
}
XPathNodeIterator locationTypeIterator = geometryIterator.Current.Select("location_type");
while (locationTypeIterator.MoveNext())
{
loc_type = locationTypeIterator.Current.Value;
}
}
}
}
//Console.ReadLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error in Calculating Coordinates Address - {0}", ex.Message + "GetLatitudeLongitudeFromAddress");
}
WriteToFile(path, "Exiting GetLatitudeLongitudeFromAddress - value returned = "+ latitudeLongitude);
return latitudeLongitude;
}
developer license is not guaranteed to have high availability, so maybe that's the reason of why you're getting 404's.

Opening a http connection on a specific port on Blackberry

I know that you can open a connection to a URL when programming in Blackberry but is it possible to open a connection on a specific port ? For example I want to send some data to the echo port of the server to check if it is alive and measure the ping time. Any ideas ?
Try something like this;
// Create ConnectionFactory
ConnectionFactory factory = new ConnectionFactory();
// use the factory to get a connection descriptor
ConnectionDescriptor conDescriptor = factory.getConnection("socket://www.abc.com:portnumber");
You can specify the port number when specifying the url to open the connection.
try this code :-
String host = "Your address" ;
new Thread()
{
run()
{
try {
SocketConnection connection = (SocketConnection)Connector.open("socket://" + host + ":80");
OutputStream out = connection.openOutputStream();
InputStream in = connection.openInputStream();
// Standard HTTP GET request all in text
// Only the required Host header, no body
String request = "GET / HTTP/1.1\r\n" +
"Host:" + host + "\r\n" +
"\r\n" +
"\r\n";
out.write(request.getBytes());
out.flush();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int firstByte = in.read();
if (firstByte >= 0) {
baos.write((byte)firstByte);
int bytesAvailable = in.available();
while(bytesAvailable > 0) {
byte[] buffer = new byte[bytesAvailable];
in.read(buffer);
baos.write(buffer);
bytesAvailable = in.available();
}
}
baos.close();
connection.close();
final_OP(new String(baos.toByteArray()) );
} catch (IOException ex) {
final_OP(ex.getMessage());
}
}
}.start();
public void final_OP(final String message) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("Output" + message);
}
});
}

Blackberry HttpConnection failure on device

I'm after some BlackBerry suggestions again. I'm developing a REST based app using the standard BB code that appends to the URI connection string (I'll post if you like but don't want to take up space here as I suspect that those of you that know about this know exactly what I mean).
The code works fine in the emulator in MDS mode and is good on the phone too with straight WiFi.
Now, the problem is when I come to use 3G on an actual phone. At that point it fails. Is this some kind of transcoding problem?
I'm using a raw HttpConnection.
An HTTP POST works (with body info) but the GET (which uses a cookie for auth purposes as a header requestproperty) fails.
The failure is only with header (GET) based info on non WiFi connections on the mobile device.
Any suggestions would be most appreciated.
public static String httpGet(Hashtable params, String uriIn) {
String result = null;
LoginDetails loginDetails = LoginDetails.getInstance();
HttpConnection _connection;
String uri = uriIn + "?api_key=" + loginDetails.getApi_key();
Enumeration e = params.keys();
// iterate through Hashtable keys Enumeration
while (e.hasMoreElements()) {
String key = (String) (e.nextElement());
String value = (String) params.get(key);
uri += "&" + key + "=" + value;
}
uri = uri + HelperMethods.getConnectionString();
try {
_connection = (HttpConnection) Connector.open(uri);
_connection.setRequestMethod(HttpConnection.GET);
_connection.setRequestProperty("Content-Type",
"text/plain; charset=UTF-8");
_connection.setRequestProperty("x-rim-authentication-passthrough",
"true");
_connection.setRequestProperty("Cookie", loginDetails.getCookie());
_connection.setRequestProperty("Content-Type", "application/json");
String charset = "UTF-8";
_connection.setRequestProperty("Accept-Charset", charset);
_connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
OutputStream _outputStream = _connection.openOutputStream();
int rc = _connection.getResponseCode();
InputStream _inputStream = _connection.openInputStream();
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
while ((ch = _inputStream.read()) != -1) {
bytestream.write(ch);
}
result = new String(bytestream.toByteArray());
bytestream.close();
{
if (_outputStream != null)
try {
_outputStream.close();
} catch (Exception e1) {
}
if (_connection != null)
try {
_connection.close();
} catch (Exception e2) {
}
}
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
return result;
}
And this uses:
public synchronized static String getConnectionString() {
String connectionString = null;
// Simulator behaviour is controlled by the USE_MDS_IN_SIMULATOR
// variable.
if (DeviceInfo.isSimulator()) {
connectionString = ";deviceside=true";
}
// Wifi is the preferred transmission method
else if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = ";interface=wifi";
}
// Is the carrier network the only way to connect?
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the carrier's TCP
// network
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier BIBS
// request
connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
}
}
// Check for an MDS connection instead (BlackBerry Enterprise Server)
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid hassling the user
// unnecssarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
connectionString = "none";
}
// In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
else {
connectionString = ";deviceside=true";
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private synchronized static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}
Fixed - see above.
It turns out that there were spaces in the uri's.
Quite why this worked over WiFi & not 3G etc. is still puzzling.

Resources