Fetch Friends profile image from restfb - java

I am using below code to get profile image of friends using Resfb. I get the response too with name id and image. Please some one help me asap on how to get the image from this data.
Code
Connection<User> myFriends = facebookClient.fetchConnection("me/friends", User.class,Parameter.with("fields", "id, name,picture"));
Response
"data":[{"id":"554603591","name":"Arjun Rao","picture":"http:\/\/profile.ak.fbcdn.net\/hprofile-ak-snc4\/211391_554603591_2022493_q.jpg"}"
Thanks

You can use restfb to parse Json-Objects:
JsonObject obj = new JsonObject(SERVER_RESPONSE);
try {
String pictureURL = obj.getString("picture");
}
catch(JsonException e) {
// key 'picture' not found
e.printStackTrace();
}

Could it be that RestFB isn't up to date in sense how Graph API returns (some objects) inside "data" object?
I managed to work-around with this custom class:
public class DataPictureHolder {
#Facebook("data")
public ProfilePictureSource picture;
}

You know how to parse the response?
If yes, just get the URL of the image, open a URLConnection and do a getInputStream() (the code for this is in this SO answer).
With the InputStream, you can save to a file or send it to the client.

Related

Where should i add the Google API key when i try to get gps coordinates by address?

I think i added my maps google api key to the wrong place. Please help me:
The relevant api key also updated on resources:
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">AIzaSyAzSgqQEZ..........KMsLlN4</string>
#Override
protected String doInBackground(String... strings) {
String response;
try {
String address = strings[0];
HttpDataHandler http = new HttpDataHandler();
String url = String.format("http://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyAzSgqQEZS1K1...........KMsLlN4", address);
response = http.getHTTPData(url);
return response;
} catch (Exception ex) {
}
return null;
}
I don't get any results, i think my access still denied...
Where should i put it?
from the official documentation->
got to the gradle.properties file and add a value with name
GOOGLE_MAPS_API_KEY="your api key"
and rebuild project.After in your manifest file you will see api key.
P.S don`t forget about permissions
The solution is to enable Geocoding API in Google Api console and restrict to specific app!!!

How to download image using rest template?

I have the following code:
restTemplate.getForObject("http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.jpg", File.class);
I especially took image which doesn't require authorization and available absolutely for all.
when following code executes I see the following stacktrace:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class java.io.File] and content type [image/jpeg]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:108)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:559)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:512)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:243)
at com.terminal.controller.CreateCompanyController.handleFileUpload(CreateCompanyController.java:615)
what do I wrong?
Image is a byte array, so you need to use byte[].class object as a second argument for RestTemplate.getForObject:
String url = "http://img.championat.com/news/big/l/c/ujejn-runi_1439911080563855663.jpg";
byte[] imageBytes = restTemplate.getForObject(url, byte[].class);
Files.write(Paths.get("image.jpg"), imageBytes);
To make it work, you will need to configure a ByteArrayHttpMessageConverter in your application config:
#Bean
public RestTemplate restTemplate(List<HttpMessageConverter<?>> messageConverters) {
return new RestTemplate(messageConverters);
}
#Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
return new ByteArrayHttpMessageConverter();
}
I've tested this in a Spring Boot project and the image is saved to a file as expected.
If you simply need to get an image from a URL, Java comes with the javax.imageio.ImageIO class, which contains this method signature:
public static BufferedImage read(URL var0) throws IOException;
example use:
try {
BufferedImage image = ImageIO.read(new URL("http://www.foo.com/icon.png"));
int height = image.getHeight();
int width = image.getWidth();
} catch (IOException e) {}
The RestTemplate is expecting a class (e.g. some in-memory representation) to convert the response from the server into. For example, it could convert a response like:
{id: 1, name: "someone"}
into a class like:
class NamedThing {
private int id;
private String name;
// getters/setters go here
}
By calling:
NamedThing thing = restTemplate.getForObject("/some/url", NamedThing.class);
But, what you seem to really want to do is to take the response from the server and stream it directly to a file. Various methods exist to get the response body of your HTTP request as something like an InputStream that you can read incrementally, and then write out to an OutputStream (e.g. your file).
This answer shows how to use IOUtils.copy() from commons-io to do some the dirty work. But you need to get an InputStream of your file... A simple way is to use an HttpURLConnection. There's a tutorial with more information.

Parse: How can I get Relation from a local data store (...fromLocalDatastore())?

I am developing an app to serve as a learning and I'm using Parse (parse.com) as a data source.
I am conducting download all objects of my classes in the parse and saving to a local store that has Parse. The following code snippet that performs one of downloads:
public void noticia_getOrUpdate(boolean isUpdate) throws ParseException {
ParseQuery<Noticia> query = new ParseQuery(Noticia.class);
query.orderByDescending("createdAt");
List<Noticia> lNoticias = null;
try {
if (isUpdate) {
lNoticias = query.whereGreaterThan("updatedAt", this.sPref.ultimaAtualizacao_noticia()).find();
if (!lNoticias.isEmpty())
ParseObject.pinAllInBackground(lNoticias);
} else {
query.whereEqualTo("ativo", true);
lNoticias = query.find();
for (Noticia noticia : lNoticias) {
if (noticia.getUpdatedAt().getTime() > this.sPref.ultimaAtualizacao_noticia().getTime())
this.sPref.atualiza_noticia(noticia.getUpdatedAt());
}
ParseObject.pinAllInBackground(lNoticias);
this.sPref.atualiza_isUpdate(true);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
The problem is I'm downloading all my classes, one is the File type, is a file that works as an image for my news ("Noticia"). I can download and store all on-site data storage, but can not recover using the following code:
public static byte[] NoticiaMidiaRelation(Noticia noticia) {
try {
ParseRelation<Midia> relation = noticia.getImagem();
Midia midia = relation.getQuery().fromLocalDatastore.whereEqualTo("ativo", true).getFirst();
if (midia != null && midia.getFileData() != null)
return midia.getFileData();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
If retreat the "fromLocalDatastore" the query, he seeks the server and brings the file correctly, but do not want to pursue it again, because as said, already have the same image stored in the local data store.
Another way to do would be to get the relationship the media Id, after that perform a search for comparing ObjectId within the local store, but I think there's no way the property "parent". But if any, can be used as a solution.
You can't according to the documentation:
By default, when fetching an obj
ect, related ParseObjects are not fetched
There are work arounds but they might not be practical because by what I understand, you only have one image in your relation per ParseObject in your "Notica" class as you call getFirst(). In this case, using a Pointer would be a better decision but those aren't fetched by default either BUT they are cached to the LocalDatastore. You'll need to add the following code to your query to fetch the Pointer object.
query.include("your_column_key");

Accessing uploaded file in Apache Tapestry page

I'm using Apache Tapestry v5.3.7 and I already use the normal Tapestry upload component in a form. For a better user experience I try now to integrate Dropzone.js in a normal Tapestry page without any form. The JavaScript integration works fine. The uploaded file data are transferred to my server with a post request and I can access the request with all of its parameters.
My question is now how can I access the binary data of the uploaded file (maybe as InputStream) to save them in my system? I already injected the http request but getInputStream returns a empty stream.
Thanks for any suggestions
/** Code snippet of page java part */
...
#Inject
protected HttpServletRequest _request;
public void onActivate (String rowId) {
String fileName=_request.getParameter("file");
try {
InputStream is=_request.getInputStream();
// if I do read from is it returns -1
// :-(
doSomeSaveStuff(is); // dummy code
}
catch(Exception e) {
e.printStackTrace();
}
}
...
Here's one way to do it:
In template:
<t:form t:id="testForm" class="dropzone">
</t:form>
In page.java
#Inject
MultipartDecoder multipartDecoder;
#Component(id = "testForm")
private Form testForm;
#Inject
RequestGlobals requestGlobals;
void onSubmitFromTestForm() throws ManagerException {
System.out.println("test form invoked");
HttpServletRequest r = requestGlobals.getHTTPServletRequest();
UploadedFile u = multipartDecoder.getFileUpload("file");
The uploaded file contains what you uploaded and you can work with it the way you want.
Note: the HttpServletRequest::getParameterMap() , told me that the handle to to the file is called file which is how I know that passing file to getFileUpload makes the decoder correctly parse the multipart/post

Give image from database a link with jersey

I am self teaching myself how to write rest services. I insert the input stream into my database and now I want to use the image a user might upload. I would like to give the image to its own link... How do I go about doing that with jersey? I cant not find a tutorial online.. I'm stumped on how to go about this.
Here is how i'm getting the image.. it post to my database with a few functions I did not include.
#Path("/submitinfo" )
public class SubmitName {
#POST
#Produces(MediaType.APPLICATION_XML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String post(#FormDataParam("file") InputStream uploadedInputStream, #FormParam("first") String name) {
Connection con = connection();
postName(con, name);
postPhoto(con, uploadedInputStream);
return name;
}
}

Categories