I'm using the following approach to return a Facebook user's music preferences:
//FIXME: Fetch results in a single operation
val likes = facebook.likeOperations().music
val artists = ArrayList<Artist>()
for (musicLiked in likes)
{
val musicProfile = facebook.fetchObject(musicLiked.id, Page::class.java, "id", "name", "genre");
artists.add(Artist(name = musicProfile.name, genre = musicProfile.genre))
}
The above approach won't scale, since we have an additional network operation for each artist the user likes.
I tried:
I tried using facebook.likeOperations.music however this doesn't fetch genre.
Question:
I would like to use facebook.fetchObject with a query that returns a PagedList. How to do this?
(No need to post example code in Kotlin if you prefer or are more familiar with Java - I'll be happy with information in any language).
Facebook api uses "fields" parameter in requests to return custom fields for objects. This parameter can be also used for liked music rest request.
me/music?fields=id,genre,name
above link will return all liked music with id, genre and name of the artist/group. Unfortunately FacebookTemplate does not have method which will apply for your needs. The method Facebook.likeOperations() returns instance of the LikeTemplate class which has constant PAGE_FIELDS with value
private static final String PAGE_FIELDS = "id,name,category,description,location,website,picture,phone,affiliation,company_overview,likes,checkins";
In above constant you do not have genre field. So you have two ways:
You can simply use facebook rest api with some rest library
You can override FacebookTemplate and return your own implementation of LikeTemplate as result of the likeOperations() method. You implementation of the LikeTemplate class should have different value in mentioned constant (added genre field at the end of the string)
Maybe some one will be more helpful but in my knowledge you do not have other options.
Thanks to advice given in #burovmarley's answer, I inspected the source and came up with:
val music = facebook.fetchConnections(userPage.id, "music", Page::class.java,
PagingParameters(25, 0, null, null).toMap(), "id,name,,genre")
for (musicLiked in music)
{
println("likes: ${musicLiked.name}, genre: ${musicLiked.genre}")
}
This allows using Spring Social Facebook as an unmodified dependency, and without issuing a pull request, which seem to be fairly slow in processing through the queue at the present time.
Related
I've created my first Play Framework Website with Java using the official documentation. It has a single page where I display a list of items that can be filtered or modified.
I have a Controller class with a method:
public CompletionStage<Result> feedpostslist(String domain, String date, String state, int page, int resnum, String search) {
return feedRepository.getArticleList(domain, date, state, page, resnum, search).thenApplyAsync(articles -> {
FeedArticle[] list = new FeedArticle[articles.size()];
articles.toArray(list);
return ok(views.html.feedpostslist.render(list));
}, ec.current());
}
This method does a query to the DB (through feedRepository) and then display the result using the view feedpostslist.
Everything is fine but now I need to get other data from the DB to be used in the same web page (so multiple queries). How do I do this in Play Framework? I don't understand what is the best way to do that.
Should I do multiple DB request inside the method showed before (through feedRepository) and then pass all these informations to my view? I don't want to do a mess or even something too heavy to handle.
If the second query doesn't depend on the first one you can run them in parallel using combineAsync. This is a good example on how to do that:
https://github.com/playframework/play-samples/blob/2.8.x/play-java-ebean-example/app/controllers/HomeController.java#L85
If the second query depends on results on the first then there's nothing you can do but to wait for the first one to complete and run the second one.
I have a Java-written Web API wherein I have web controllers handling HTTP requests. I'm trying to implement a RESTful architecture with HATEOAS, using Spring Boot. When adding HATEOAS links in methods I can easily add links for GET/DELETE requests, but I'm having trouble with POST/PUT/PATCH requests, mostly because those require me to supply a body of the thing I want to post, usually in JSON format. I've been googling for a while and I can't find out how to do it.
Here's how I'm adding links to GET / DELETE operations.
/**
* Shows all the Rooms present in the database.
*
* #return OK status and a list of Room Minimal DTO.
*/
#GetMapping(path = "/", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getRooms() {
List<RoomDTOMinimal> roomDTOList = roomRepository.getAllDTOWebInformation();
for (RoomDTOMinimal r : roomDTOList) {
if (userService.getUsernameFromToken().equals("ADMIN")) {
Link roomSensors = linkTo(methodOn(RoomsWebController.class).getSensors(r.getName())).withRel("Get Room" +
"Sensors");
Link deleteRoom = linkTo(methodOn(RoomsWebController.class).deleteRoom(r)).withRel("Delete this Room");
r.add(roomSensors);
r.add(deleteRoom);
} else if (userService.getUsernameFromToken().equals("REGULAR_USER")) {
Link roomTemp = linkTo(methodOn(RoomsWebController.class).getCurrentRoomTemperature(r.getName())).
withRel("Get Room Temperature");
r.add(roomTemp);
}
}
return new ResponseEntity<>(roomDTOList, HttpStatus.OK);
}
I want to add a Link to an "editRoom" request, something like:
Link editRoom = linkTo(methodOn(RoomsWebController.class).configureRoom(r.getName(), WHAT GOES HERE???).withSelfRel();
But configureRoom takes in the roomName and a roomDTO in its signature. RoomDTO is a #RequestBody, so I can't give it to the Link. How should I add the link to the objects in a way that then allows me to call on that method?
I'd like to have something like:
ROOM | Delete | Edit
On the client side, where if I click DELETE the room is deleted, and if I click Edit the client side expands, with text boxes, allowing me to insert the required parameters to edit the room. I have the client-side code implemented for the Edit function, with appropriate front-end; but I can't link to it on the server-side without already providing data that should come later, from the user input. What's the best way to do this?
I've since solved it after talking with a team lead. Apparently it's acceptable to either pass null or an empty DTO object as a parameter in the scenario above; the HATEOAS implementation cares specifically about those parameters that are of the path, and roughly speaking ignores the others. Those can then be replaced as needed on the client-side upon a user performing an action / inserting input.
I'm creating a java application that pulls data from facebook videos using RestFB. How can I retrieve the custom labels from each video?
Although I'm able to pull the normal data from each video, there doesn't seem to be any RestFB function that gets custom labels.
I've tried creating my own function by copying the RestFB source code for getting the title and then changing it according to the data I need, but that doesn't seem to work.
The custom labels field is missing atm in RestFB, so you can wait until a new version is released or write a custom video type like this:
public class CustomLabelsVideo extends Video {
#Facebook("custom_labels")
private List<String> customLabels = new ArrayList<>();
public List<String> getCustomLabels() {
return customLabels;
}
public void setCustomLabels(List<String> customLabels) {
this.customLabels = customLabels;
}
}
You need to use this type in the fetchObject method, and don't forget to add the custom_labels string to the fields you fetch.
i'm somewhat new to jinput and java in general and was wondering, what's the easiest way to set up multiple xbox 360 controllers (particularly 4) with jinput? currently, i'm currently going off of theuzo007's tutorial on jinput with controllers, and have a basic working controller setup going on. it would be fantastic if i could set what controller moves certain entities around. (i'm using my friend's homemade library, just so you know.)
screenshot -
http://imgur.com/a/1Ocu5
top one is the main block of code, last one is the header (sorry for putting them in the wrong order, imgur does that sometimes!)
if anyone could help me out, that would be great, thanks!
edit: if there's no possible way to do it, if anyone could try to reccomend a new library to me, that would be cool.
There is a possible way
That tutorial is pretty good. Furthermore, I think you can do the 4 controllers stuff by copy-pasting some code inside the zip theuzo007 provides you and a bit more. By the way, that page that you liked says that there is a better version of that tutorial where you can download an also better version of his code -> theuzo007's JInput tutorial V2
Once you download the code you can see that in JoystickTest.java there is a method called searchForControllers() that you can put (With the corresponding private ArrayList<Controller> foundControllers; as field) in a class called ControllerChecker or some cooler name. Make them all static and you will get something like this:
public class ControllerChecker {
private static ArrayList<Controller> foundControllers = null;
/**
* Just used for checking all available controllers.
*/
private static void searchForControllers() {
Controller[] controllers = ControllerEnvironment.getDefaultEnvironment().getControllers();
for(int i = 0; i < controllers.length; i++){
Controller controller = controllers[i];
if (
controller.getType() == Controller.Type.STICK ||
controller.getType() == Controller.Type.GAMEPAD ||
controller.getType() == Controller.Type.WHEEL ||
controller.getType() == Controller.Type.FINGERSTICK
)
{
// Add new controller to the list of all controllers.
foundControllers.add(controller);
// Add new controller to the list on the window.
window.addControllerName(controller.getName() + " - " + controller.getType().toString() + " type");
}
}
}
/**
* Returns null if there is no controller available. Otherwise, it retrieves the last controller in the list by removing it.
*/
public static Controller getController() {
if(foundControllers == null) {
foundControllers = new ArrayList<Controller>();
searchForControllers();
}
return foundControllers.size() == 0 ? null : foundControllers.remove(foundControllers.size() - 1);
}
}
You would use the static method getController() to make the players have a different controller, checking if the returned controller is null, meaning that there is no available controller. Also you can change my code and check for controllers everytime you ask for one, but you have to check if the controller is already in use.
I hope this helps you in your purpose. This solution just checks for all available controllers and returns then in the last order it found them (maybe using a Stack is more efficient). But probably you will want more functionality like being able to tell the program to select a specific controller by pressing a button, maybe in a screen that says "Please, connect your controller and press any key/button". This can be achieve easily if you understand theuzo007's code (the JoystickTest.java has a lot of useful lines!).
Also you can make some mechanism to detect unpluged controllers and just by plugging in them again the system recognize it. Maybe there is some controller id, I haven't found it yet.
Finally, there is more code here.
In my Android app I use Picasso to load images. This normally works perfectly well.
Today I tried loading a static image from the google maps api, but this doesn't seem to work. When I open the example link as provided on their info page, I get to see the static map image perfectly well. When I load it in my Android app using the line below, I get nothing at all.
Picasso.with(getContext()).load("http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=370x250&maptype=roadmap%20&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318%20&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false").into(mapView);
I also tried to download the image and uploading it to my personal webspace, from which it loads perfectly well, but somehow, it doesn't seem to load directly from the direct google API url.
Does anybody know why this is so, and how I can solve it?
The only programmatic point-of-failure that comes to mind is in parsing the URI. Looking at the current Picasso code (https://github.com/square/picasso/blob/master/picasso/src/main/java/com/squareup/picasso/Picasso.java) I see the following:
public RequestCreator load(String path) {
if (path == null) {
return new RequestCreator(this, null, 0);
}
if (path.trim().length() == 0) {
throw new IllegalArgumentException("Path must not be empty.");
}
return load(Uri.parse(path));
}
So I'd first debug
Uri.parse("http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=370x250&maptype=roadmap%20&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318%20&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false")
and see what that Object looks like. Does it drop or confuse any of your parameters?
If that doesn't lead you anwhere, try downloading the file manually using a HttpClient [or similar]. Then at least you can fully debug the request/response.
Also, I know Google maps has some limits -- are you sure you haven't reached them?
replace http with https
replace | with %7C
add api key
The .loadMap() function has many declared variables. This is the heart of the whole process.
So what is required for the static maps API to give us an image is that we make an http request with a given url, for which an image response (URL) is received. Let us run through the meaning and utility of these variables. Yes, all of them have a completely different meaning!
The mapUrlInitial variable is always the same while making an API call. It has a query of center ( ?center ) which specifies that we want the location to be centered in the map.
The mapUrlProperties variable contains a string where you control the actual zooming of the image response you will get, the size ofthe image and the color of the marker which will point out our place.
The mapUrlMapType variable is a string where you can actually determine the marker size you want and the type of the map. We are using a roadtype map in the app.
Finally latLong is a string which concatenates the latitude and the longitude of the place we want to pinpoint!
We then concatenate all of these strings to form a feasible Url. The Url is then loaded as we have seen above, in the Picasso code. One thing we can notice is that an event object is always required for all of this to happen, because we are able to fetch the position details using the event object! Final Code:-
fun loadMap(event: Event): String{
//location handling
val mapUrlInitial = “https://maps.googleapis.com/maps/api/staticmap?center=”
val mapUrlProperties = “&zoom=12&size=1200×390&markers=color:red%7C”
val mapUrlMapType = “&markers=size:mid&maptype=roadmap”
val latLong: String = “” +event.latitude + “,” + event.longitude
return mapUrlInitial + latLong + mapUrlProperties + latLong + mapUrlMapType
}
//load image
Picasso.get()
.load(loadMap(event))
.placeholder(R.drawable.ic_map_black_24dp)
.into(rootView.image_map)