I am newbie for such kind of social networking Application integration using blackberry API.
i want to develope such kind of application which can use the facebook or twitter social networking site integration using available blackberry api.
how to access the faceBook using blackberry API?
Is there any webservice available of facebook on which blackberry api can work and access it?
is there any application exist with whole source code for accessing the facebook using the blackberry api?
if anybody has any solution or any useful link or any code snippet,which would be appreciated.:)
Thanks,
Mishal
Facebook offers a webservice-based API that you can use - they provide information about it here:
http://wiki.developers.facebook.com/index.php/Platform_Basics
I would strongly recommend using the Sun Java Wireless Toolkit (Sun Java Wireless Toolkit 2.5.2_01 for CLDC available here: SJW Toolkit) - use the Utilities application when installed and then the "Stub Generator" - it will create J2ME classes and stubs for all web service calls that you can then bring into your BlackBerry project. I have used this without fail to call web services from the BlackBerry and it is much easier than creating your own web service call wrappers. Everything will be strong typed and any required objects and classes will all be created for you.
BlackBerry FaceBook Connect
See code sample provided by Eki Y. Baskoro: Facebook Connect on Blackberry
The following is a short HOWTO on using Facebook Connect on Blackberry. I created a simple Facade encapsulating the Facebook REST API as well as added 'rough' MVC approach for screen navigation. I have tested on JDE 4.5 using 8320 simulator. This is still work in progress and all work is GPLed.
BlackBerry Twitter Connect
And talking about twitter, there is a twitter api and opensource j2me client - jibjib to look at.
Sample to post status:
class Scr extends MainScreen implements FieldChangeListener {
BasicEditField musername;
BasicEditField mPassword;
BasicEditField mStatus;
ButtonField mUpdateStatus;
public Scr() {
add(musername = new BasicEditField("username: ", ""));
add(mPassword = new BasicEditField("password: ", ""));
add(mStatus = new BasicEditField("status: ", ""));
mUpdateStatus = new ButtonField(ButtonField.CONSUME_CLICK);
mUpdateStatus.setLabel("update status");
mUpdateStatus.setChangeListener(this);
add(mUpdateStatus);
}
public void fieldChanged(Field field, int context) {
if (mUpdateStatus == field) {
String username = musername.getText().trim();
String password = mPassword.getText().trim();
String status = mStatus.getText().trim();
updateStatus(username, password, status);
} else {
}
}
void updateStatus(String username, String password, String status) {
String response = "";
try {
String query = "status=" + urlEncode(status);
String len = String.valueOf(query.length());
SocketConnection hc = (SocketConnection) Connector
.open("socket://twitter.com:80");
DataOutputStream dout =
new DataOutputStream(hc.openOutputStream());
DataInputStream din = new DataInputStream(hc.openInputStream());
String userPass = username + ":" + password;
byte[] encoded = Base64OutputStream.encode(userPass.getBytes(), 0,
userPass.length(), false, false);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String request = "POST /statuses/update.json HTTP/1.1\r\n"
+ "Host: twitter.com:80\r\n"
+ "User-Agent: curl/7.18.0 (i486-pc-linux-gnu) " +
"libcurl/7.18.0 OpenSSL/0.9.8g zlib/1.2.3.3 " +
"libidn/1.1\r\n"
+ "Accept: */*\r\n"
+ "Content-Type: application/x-www-form-urlencoded\r\n"
+ "Content-Length: " + len + "\r\nAuthorization: Basic "
+ new String(encoded) + "\r\n\r\n";
bos.write(request.getBytes());
bos.write(query.getBytes());
dout.write(bos.toByteArray());
dout.flush();
dout.close();
byte[] bs = new byte[900];
din.readFully(bs);
bos = new ByteArrayOutputStream();
bos.write(bs);
din.close();
hc.close();
response = bos.toString();
} catch (Exception ex) {
System.out.println(ex.getMessage()+" "+response);
}
}
public static String urlEncode(String s) {
if (s != null) {
try {
s = new String(s.getBytes("UTF-8"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
}
StringBuffer tmp = new StringBuffer();
try {
for (int i = 0; i < s.length(); i++) {
int b = (int) s.charAt(i);
if ((b >= 0x30 && b <= 0x39) || (b >= 0x41 && b <= 0x5A)
|| (b >= 0x61 && b <= 0x7A)) {
tmp.append((char) b);
} else if (b == 0x20) {
tmp.append("+");
} else {
tmp.append("%");
if (b <= 0xf) {
tmp.append("0");
}
tmp.append(Integer.toHexString(b));
}
}
} catch (Exception e) {
}
return tmp.toString();
}
return null;
}
}
UPDATE
Twitter API ME lib v.1.8 for RIM is available on Project Kenai
Twitter Basic Auth method is deprecated starting today.
You must now use OAuth ...
for connecting to Facebook from blackberry using native apps you can use Facebook sdk for blackberry. you can download from github.com. search for Facebook sdk. it will also comes with some samples which clearly demonstrates the usage of Facebook api.
Related
I'm using Microsoft Bot Framework using the channel registration product and the REST API. I have setup the "messaging endpoint" and everything works fine for sending and receiving messages.
But I don't just want to send/receive messages. Something as simple as setting up a welcome message seems impossible because my endpoint receives nothing other than messaging events (when the bot is in the channel / conversation.)
Is there something I have missed?
I would like to setup several endpoints, or use the same, whatever, to listen to other types of events.
You need to implement in the MessageController something like these:
Pay attention in the else if. The funcition in the controller is HandleSystemMessage.
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels
IConversationUpdateActivity update = message;
var cliente = new ConnectorClient(new System.Uri(message.ServiceUrl), new MicrosoftAppCredentials());
if (update.MembersAdded != null && update.MembersAdded.Count > 0)
{
foreach(var member in update.MembersAdded)
{
if(member.Id != message.Recipient.Id)
{
//var username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
var username = message.From.Name;
var reply = message.CreateReply();
//string dir = System.AppDomain.CurrentDomain.BaseDirectory + "Images" + Path.DirectorySeparatorChar + "cajamar.png";
string dir = HttpRuntime.AppDomainAppPath + "Images" + Path.DirectorySeparatorChar + "cajamar.png";
reply.Attachments.Add(new Attachment(
contentUrl: dir,
contentType: "image/png",
name: "cajamar.png"
));
reply.Text = $"Bienvenido {username} al ChatBot de convenios:";
cliente.Conversations.ReplyToActivity(reply);
//var reply = message.CreateReply();
//reply.Text = $"El directorio base es: {HttpRuntime.AppDomainAppPath}";
//cliente.Conversations.ReplyToActivityAsync(reply);
}
}
}
}
I'm looking now in Bloomberg Data License Web Services. Note, that this is different from Bloomberg API ( Session/Service/Request, b-pipe, etc ). It is SOAP-based solution to retrieve reference data from Bloomberg DBs. I created a test application just to quickly evaluate this solution:
var client = new PerSecurityWSClient("PerSecurityWSPort");
client.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2("{path-to-certificate}", "{password}");
client.ClientCredentials.UserName.UserName = "";
client.ClientCredentials.UserName.Password = "";
client.ClientCredentials.Windows.ClientCredential.Domain = "";
var companyFields = new string[] { "ID_BB_COMPANY", "ID_BB_ULTIMATE_PARENT_CO_NAME" , /* ... all other fields I'm interested in */ };
var getCompanyRequest = new SubmitGetCompanyRequest {
headers = new GetCompanyHeaders { creditrisk = true },
instruments = new Instruments {
instrument = new Instrument[] {
new Instrument { id = "AAPL US", yellowkey = MarketSector.Equity, yellowkeySpecified = true },
new Instrument { id = "PRVT US", yellowkey = MarketSector.Equity, yellowkeySpecified = true }
}
},
fields = companyFields
};
var response = client.submitGetCompanyRequest(getCompanyRequest);
if(response.statusCode.code != SUCCESS) {
System.Console.Error.WriteLine("Response status is " + response.statusCode);
return;
}
var retrieve = new RetrieveGetCompanyRequest { responseId = response.responseId };
RetrieveGetCompanyResponse getCompanyResponse = null;
do {
System.Console.Write("*");
Thread.Sleep(1000);
getCompanyResponse = client.retrieveGetCompanyResponse(retrieve);
} while (getCompanyResponse.statusCode.code == DATA_NOT_AVAILABLE);
if (getCompanyResponse.statusCode.code != SUCCESS) {
System.Console.Error.WriteLine("Response status is " + response.statusCode);
return;
}
System.Console.WriteLine();
foreach (var instrumentData in getCompanyResponse.instrumentDatas) {
Console.WriteLine("Data for: " + instrumentData.instrument.id + " [" + instrumentData.instrument.yellowkey + "]");
int fieldIndex = 0;
foreach (var dataEntry in instrumentData.data) {
if (dataEntry.isArray) {
Console.WriteLine(companyFields[fieldIndex] + ":");
foreach(var arrayEntry in dataEntry.bulkarray) {
foreach(var arrayEntryData in arrayEntry.data) {
Console.WriteLine("\t" + arrayEntryData.value);
}
}
}
else {
Console.WriteLine(companyFields[fieldIndex] + ": " + dataEntry.value);
}
++fieldIndex;
}
System.Console.WriteLine("-- -- -- -- -- -- -- -- -- -- -- -- --");
}
The code looks somewhat bloated (well, it is indeed, SOAP-based in 2015). Hence is my question -- I assume there should be some wrappers, helpers, anything else to facilitate reference data retrieval, but even on SO there is only one question regarding BB DLWS. Is here anyone using DLWS? Are there any known libraries around BB DLWS? Is it supposed to be that slow?
Thanks.
I'm just getting into this myself. There are two options for requesting data: SFTP and Web Services. To my understanding, the SFTP option requires a Bloomberg application ("Request Builder") in order to retrieve data.
The second option (Web Services) doesn't seem well-documented, at least for those working with R (like myself). So, I doubt a library exists for Web Services at this point. Bloomberg provides an authentication certificate in order to gain access to their network, as well as their web services host and port information. Now, in terms of using this information to connect and download data, that is still beyond me.
If you or anyone else has been able to successfully connect and extract data using Bloomberg Web Services and R, please post the detailed code to this Blog!
I have already tried a lot of approaches to send a xml file as string + pictures with a POST request using GWT on the client side. I can send the strings successfully, but I do not know how to send files (pictures) using the RequestBuilder, I am just able to send the strings.
Do someone know how to send files with a multipart/form-data POST request using GWT Client (RequestBuilder)?
P.S.: As I am not wishing to upload files, I don't need a uploader or something similar. I am developing a mobile app with Phonegap, and making pictures, which should be sent per POST request to a server (a third party service).
Thanks in advance!
Here some code:
public void sendPost() throws RequestException {
String boundary = createBoundary();
String xml = "<note> <to>Müller</to> <from>Jani</from> <heading>Erinnerung</heading> <body>Ich wohne in der Leipzigerstraße</body> </note>";
String requestData = getRequestData(boundary, xml);
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, "http://localhost:8080/xxx/yyy");
builder.setHeader("Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary);
builder.setHeader("Content-Length", Long.toString(requestData.length()));
try {
builder.sendRequest(requestData, new RequestCallback() {
public void onResponseReceived(Request request, Response response) {
}
public void onError(Request request, Throwable exception) {
exception.printStackTrace();
}
});
} catch (RequestException e) {
e.printStackTrace();
}
}
private String getRequestData(String boundary, String xml) {
String s = "";
s += "--" + boundary + "\r\n";
s += getRequestParameter("xml", xml + "");
s += "--" + boundary + "--\r\n"; // end
return s;
}
private String getRequestParameter(String key, String value) {
return "Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n"
+ value + "\r\n";
}
private String createBoundary() {
return "----GoneVerticalBoundary" + getRandomStr() + getRandomStr();
}
private String getRandomStr() {
return Long.toString(random.nextLong(), 36); //random -> DEFINED IN THE CLASS BODY
}
If you are using gwt + phonegap you should be using gwt-phonegap, right?
What I do in my apps, is to use gwtupload for the desktop version, and phonegap file transfer in the mobile. I use gwtupload servlet in the server side for both cases.
This is my code using gwt-phonegap:
FileUploadOptions options = new FileUploadOptions();
options.setFileKey("file");
options.setFileName("my_file.txt");
options.setMimeType("text/plain");
phonegap.getFile().createFileTransfer().upload(
"file:///my_path/my_file.txt",
"http://my-gwtupload-servlet/servlet.gupld",
options,
new FileUploadCallback() {
#Override
public void onSuccess(FileUploadResult result) {
if (result.getResponseCode() == 200) {
} else {
}
}
#Override
public void onFailure(FileTransferError error) {
Window.alert("Error sending the file, error-code: " + error.getCode());
}
});
I use deferred binding for selecting the appropriate implementation using phonegap.env:
<replace-with class="...UploadFilePhoneGap">
<when-type-is class="....UploadFile" />
<when-property-is name="phonegap.env" value="yes" />
</replace-with>
If you are looking for pure gwt solution then you need to work with FileUpload
If you do not mind using third party open source jar then you can try gwtupload
For locale issues just ensure you are using UTF-8 and GWT locale cookies and locale settings.
For all the people who wants to manage files and pictures on the client side, before sending them to the server, as Manolo has recommended, I suggest lib-gwt-file.
For people working with PhoneGap, I suggest enconding the pictures using Base64, and decoding on the server side (see class Base64Util)
I searched lot and I can see some questions same as mine in StackOverflow too but didn't get answer.
I need to get user(google+ and facebook) messages whatever posted by him under his/her account and give it as xml response to a mobile app which is going to show user posts as better format/design - so here I need to fetch the posts from google+/facebook using the profile-id/username.
Eg: Like from twitter I can able to see status from
https://api.twitter.com/1/statuses/user_timeline.xml?include_entities=true&include_rts=true&screen_name=screenname&count=2
Is there any library or any particular way by which i can get it?
Thanks in Advance.
I can only speak to Facebook and Twitter, as they are the only two Social Media API's I have utilized.
Both API's are RESTful services. For Twitter and Facebook, you will need to create applications on the perspective platforms in order to obtain an OAuth token for your applications that will be fetching the data via the RESTful services.
For FaceBook, you can utilize the Graph API explorer for development. This enables you to develope without creating an application on the FaceBook platform.
Both FaceBook and Twitter have community driven projects for accessing these web services in various languages. Since you are doing this for the Android, I assume you would like your program for fetching this data in Java.
RestFB is my recommendation for a Java FaceBook library
FacebookClient facebookClient = new DefaultFacebookClient(authToken);
User facebookUser = facebookClient.fetchObject("me", User.class);
Twitter4j is a great Java Twitter library
For FaceBook, core concepts is a great place to start.
For more information on Twitter on see the overview documentation
You can use the activities API for Google+. This is currently restricted to public posts but should be enough to get you started. The profile ID comes from a user's profile. There are other ways you can get this content as well, including the search API.
The documentation and simple examples from various languages can be found on the Google plus page (https://developers.google.com/+/api/latest/activities) and the following JavaScript example could be helpful for justing seeing how things work:
// globals used for auth, showing debugging
var debug = true;
var key = "your api key from https://code.google.com/apis/console";
function handleRequestIssue(request){
// For now, just show the error
console.log("Error, status:" + request.status + " / response:" + request.responseText);
}
function performXHR(URL){
var objReturn = "";
var request = new XMLHttpRequest();
request.open('GET', URL, false);
request.send(); // because of "false" above, will block until the request is done
// and status is available. Not recommended, however it works for simple cases.
if (request.status === 200) {
if (debug) console.log(request.responseText);
var objReturn = jQuery.parseJSON(request.responseText).items;
if (debug){
for (value in objReturn){
console.log(value);
}
}
}else{
handleRequestIssue(request);
}
return objReturn;
}
// Gets the activities for a profile
function getActivities(profileID){
var activities = null;
var URL = "https://www.googleapis.com/plus/v1/people/" + profileID + "/activities/public?alt=json&key=" + key;
activities = performXHR(URL);
console.log(activities.length);
return activities;
}
You can at this point see the activities in your debugger. You could always render the content as HTML inside a div or something.
function renderActsComments(activities, identifier, filter){
var renderMe = "";
console.log("activities retrieved: " + activities.length);
for (var i=0; i < activities.length; i++) {
var render = true;
console.log("trying to do something with an activity: " + i);
var activity = activities[i];
if (filter != null && filter.length > 0){
if (activity.crosspostSource.indexOf(filter) == -1){
render = false;
}
}
if (render == true){
renderMe += "<br/><div class=\"article\"><p>" + activity.title + "</p>";
console.log(activity.id);
// get comments
var comments = getCommentsForActivity(activity.id);
var left = true;
for (var j=0; j<comments.length; j++){
if (left){
left = false;
renderMe += "<br/><p class=\"speech\">" + comments[j].object.content + "</p>";
renderMe += "" + comments[j].actor.displayName + "";
renderMe += "<a href=\"" + comments[j].actor.image.url.replace(/\?.*/, "") + "\">";
renderMe += " <img border=0 src=\"" + comments[j].actor.image.url + "\"/></a>";
renderMe += "</p>";
}else{
renderMe += "<br/><p class=\"speechAlt\">" + comments[j].object.content + "</p>";
left = true;
renderMe += "<p class=\"profileAlt\">";
renderMe += "<a href=\"" + comments[j].actor.image.url.replace(/\?.*/, "") + "\">";
renderMe += "<img border=0 src=\"" + comments[j].actor.image.url + "\"/></a>";
renderMe += " " + comments[j].actor.displayName + "";
renderMe += "</p>";
}
}
renderMe += "</div>";
}
}
console.log("I'm done");
document.getElementById(identifier).innerHTML = renderMe;
return renderMe;
}
In my application image has to post to Facebook,mail.Sorry i am new to windows phone.i don't have a idea.please help me.what i can do first.
If you want to share a status you can use your facebook account on your phone using Share link task (with this method you can only post on your wall) http://msdn.microsoft.com/en-us/library/hh394027%28v=vs.92%29.aspx
To post (pictures, messages or others) on every wall you have access you need some things :
First you need to create a facebook application using this link :
Facebook developers
After that you need to identify yourself using a WebBrowser control with the link related to your application. The application requests authorization to perform certain actions such as posting. You need to detail the authorizations like this :
Dictionary<string, string> uriParams = new Dictionary<string, string>() {
{"client_id", "your app id"},
{"response_type", "token"},
{"scope", "user_about_me, offline_access, publish_stream"}, //The rights
{"redirect_uri", "http://www.facebook.com/connect/login_success.html"},
{"display", "touch"}
};
The Dictionary also contains the redirection uri to define if the operation was successful.
Finally you are authentified and receive an access token. Now you can use a WebRequest POST to post a message using this token :
WebRequest request = HttpWebRequest.Create("https://graph.facebook.com/" + the id of your wall + "/feed");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream((reqResult) =>
{
using (Stream strm = request.EndGetRequestStream(reqResult))
using (StreamWriter writer = new StreamWriter(strm))
{
writer.Write(client.AccessToken);
writer.Write("&message=" + HttpUtility.UrlEncode(status));
}
request.BeginGetResponse((result) =>
{
try
{
var response = request.EndGetResponse(result);
using (var rstrm = response.GetResponseStream())
{
var serializer = new DataContractJsonSerializer(typeof(FacebookPostResponse));
var postResponse = serializer.ReadObject(rstrm) as FacebookPostResponse;
callback(true, null);
}
}
catch (Exception ex)
{
callback(false, ex);
}
}, null);
}, null);
Here is how to post a message on a facebook page,
You should give the Facebook C# SDK a try
Facebook C# SDK
I have built this in once in an app of mine. They have plenty examples available which should be useful.