Amazon Advertising API: Cannot locate SignedRequestHelper class - java

I have got code from amazon scratchpad and got the package required. The SignedRequestHelper class is not in the package and i am unable to run the program. I am attempting to get the price of the item using the amazon asin number.
package com.amazon.advertising.api.sample;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/*
* This class shows how to make a simple authenticated call to the
* Amazon Product Advertising API.
*
* See the README.html that came with this sample for instructions on
* configuring and running the sample.
*/
public class lookup {
/*
* Your AWS Access Key ID, as taken from the AWS Your Account page.
*/
private static final String AWS_ACCESS_KEY_ID = "XXXXXX";
/*
* Your AWS Secret Key corresponding to the above ID, as taken from the AWS
* Your Account page.
*/
private static final String AWS_SECRET_KEY = "XXXXXXX";
/*
* Use the end-point according to the region you are interested in.
*/
private static final String ENDPOINT = "webservices.amazon.com";
public static void main(String[] args) {
/*
* Set up the signed requests helper.
*/
SignedRequestsHelper helper;
try {
} catch (Exception e) {
e.printStackTrace();
return;
}
String requestUrl = null;
Map<String, String> params = new HashMap<String, String>();
params.put("Service", "AWSECommerceService");
params.put("Operation", "ItemLookup");
params.put("AWSAccessKeyId", "XXXXXX");
params.put("AssociateTag", "XXXXX");
params.put("ItemId", "B01H57GXUQ");
params.put("IdType", "ASIN");
params.put("ResponseGroup", "Images,ItemAttributes,Offers");
requestUrl = helper.sign(params);
System.out.println("Signed URL: \"" + requestUrl + "\"");
}
}
How would i be able to get the signedrequestshelper method or how would i be able to change the code?

SignedRequestHelper is a class available in one of the code samples from AWS here:
http://docs.aws.amazon.com/AWSECommerceService/latest/DG/AuthJavaSampleSig2.html
You can copy/paste the code in your project to make it run and work.

Related

How to upload videos on Youtube to a particular youtube account on Android programatically

Here is my use case:
I want users to be able to upload video content from their devices directly to my youtube or a dedicated youtube account without leaving my app. First of all, is this possible? Please I will appreciate code samples. Thanks
This shows how to upload a video using an HTTP request.
There are code snippets that are also available in java (and kotlin is pretty similar).
In order to see how to upload a video, go to https://developers.google.com/youtube/v3/code_samples/code_snippets, select Videos under Resource and insert under method.
If you then click on Show code and select JAVA at the top, you will get this example code:
/**
* Sample Java code for youtube.videos.insert
* See instructions for running these code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#java
*/
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Video;
import com.google.api.services.youtube.model.VideoSnippet;
import com.google.api.services.youtube.model.VideoStatus;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
public class ApiExample {
// You need to set this value for your code to compile.
// For example: ... DEVELOPER_KEY = "YOUR ACTUAL KEY";
private static final String DEVELOPER_KEY = "YOUR_API_KEY";
private static final String APPLICATION_NAME = "API code samples";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/**
* Build and return an authorized API client service.
*
* #return an authorized API client service
* #throws GeneralSecurityException, IOException
*/
public static YouTube getService() throws GeneralSecurityException, IOException {
final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
return new YouTube.Builder(httpTransport, JSON_FACTORY, null)
.setApplicationName(APPLICATION_NAME)
.build();
}
/**
* Call function to create API service object. Define and
* execute API request. Print API response.
*
* #throws GeneralSecurityException, IOException, GoogleJsonResponseException
*/
public static void main(String[] args)
throws GeneralSecurityException, IOException, GoogleJsonResponseException {
YouTube youtubeService = getService();
// Define the Video object, which will be uploaded as the request body.
Video video = new Video();
// Add the snippet object property to the Video object.
VideoSnippet snippet = new VideoSnippet();
snippet.setCategoryId("22");
snippet.setDescription("Description of uploaded video.");
snippet.setTitle("Test video upload.");
video.setSnippet(snippet);
// Add the status object property to the Video object.
VideoStatus status = new VideoStatus();
status.setPrivacyStatus("private");
video.setStatus(status);
// TODO: For this request to work, you must replace "YOUR_FILE"
// with a pointer to the actual file you are uploading.
// The maximum file size for this operation is 137438953472.
File mediaFile = new File("YOUR_FILE");
InputStreamContent mediaContent =
new InputStreamContent("application/octet-stream",
new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());
// Define and execute the API request
YouTube.Videos.Insert request = youtubeService.videos()
.insert("snippet,status", video, mediaContent);
Video response = request.setKey(DEVELOPER_KEY).execute();
System.out.println(response);
}
}
You can also look at another example java code for uploading a video to YouTube on GitHub.
Note that you will need to make a few changes to this:
Under android, you don't have a main. You will need to (1) put that code whereever you need to and you might want ro (2) do it asynchronously.
When using kotlin, you will also (3) need to modify the syntax accordingly.

Locally Hosted SparkJava Proxy Server Stalls when Querying Google Maps API

I am trying to write a proxy server with SparkJava that queries the Google Maps Directions API given parameters (i.e. location data, traffic model preference, departure time, etc...) from a client and returns various routing details such as distance, duration, and duration.
The server stalls when it tries to send a request to the API on behalf of the client. I placed print statements throughout the code to confirm that the hang was due to the API query. I have tried using different ports namely: 4567, 443, 80, and 8080 by using port() method but the problem persists. I am sure the server-side code conducting the API query is not the issue; everything works fine (proper route information is generated i.e. DirectionsApiRequest.await() returns properly) when I cut the client out, disable the endpoints, and run everything manually from the main method on the (deactivated) server's side.
Does anyone know why this could be happening?
(I use maven for dependency management)
The following shows the client trying to get the distance of the default route and the aforementioned error:
Server-side code:
Main class
package com.mycompany.app;
//import
// data structures
import java.util.ArrayList;
// google maps
import com.google.maps.model.DirectionsRoute;
import com.google.maps.model.LatLng;
// gson
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
// static API methods
import com.mycompany.app.DirectionsUtility;
import static spark.Spark.*;
// exceptions
import com.google.maps.errors.ApiException;
import java.io.IOException;
public class App
{
private static ArrayList<LatLng> locationsDatabase = new ArrayList<LatLng>();
private static DirectionsRoute defaultRoute = null;
public static void main( String[] args ) throws ApiException, InterruptedException, IOException
{
// client posts location data
post("routingEngine/sendLocations", (request,response) -> {
response.type("application/json");
ArrayList<LatLng> locations = new Gson().fromJson(request.body(),new TypeToken<ArrayList<LatLng>>(){}.getType());
locationsDatabase = locations;
return "OK";
});
// before any default route queries, the default route must be generated
before("routingEngine/getDefaultRoute/*",(request,response) ->{
RequestParameters requestParameters = new Gson().fromJson(request.body(),(java.lang.reflect.Type)RequestParameters.class);
defaultRoute = DirectionsUtility.getDefaultRoute(locationsDatabase,requestParameters);
});
// client gets default route distance
get("routingEngine/getDefaultRoute/distance", (request,response) ->{
response.type("application/json");
return new Gson().toJson(new Gson().toJson(DirectionsUtility.getDefaultRouteDistance(defaultRoute)));
});
DirectionsUtility.context.shutdown();
}
}
DirectionsUtility is the class responsible for consulting with Google Maps' API:
package com.mycompany.app;
// import
// data structures
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
// Google Directions API
import com.google.maps.GeoApiContext;
// request parameters
import com.google.maps.DirectionsApiRequest;
import com.google.maps.model.Unit;
import com.google.maps.model.TravelMode;
import com.google.maps.model.TrafficModel;
import com.google.maps.DirectionsApi.RouteRestriction;
import com.google.maps.model.Distance;
// result parameters
import com.google.maps.model.DirectionsResult;
import com.google.maps.model.LatLng;
import com.google.maps.model.DirectionsRoute;
import com.google.maps.model.DirectionsLeg;
// exceptions
import com.google.maps.errors.ApiException;
import java.io.IOException;
// time constructs
import java.time.Instant;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Call;
import okhttp3.Response;
import okhttp3.MediaType;
import okhttp3.HttpUrl;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public final class DirectionsUtility{
/**
* Private constructor to prevent instantiation.
*/
private DirectionsUtility(){}
/**
* API key.
*/
private static final String API_KEY = "YOUR PERSONAL API KEY";
/**
* Queries per second limit (50 is max).
*/
private static int QPS = 50;
/**
* Singleton that facilitates Google Geo API queries; must be shutdown() for program termination.
*/
protected static GeoApiContext context = new GeoApiContext.Builder()
.apiKey(API_KEY)
.queryRateLimit(QPS)
.build();
// TESTING
// singleton client
private static final OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(700,TimeUnit.SECONDS)
.writeTimeout(700, TimeUnit.SECONDS)
.readTimeout(700, TimeUnit.SECONDS)
.build();
/**
* Generates the route judged by the Google API as being the most optimal. The main purpose of this method is to provide a fallback
* for the optimization engine should it ever find the traditional processes of this server (i.e. generation of all possible routes)
* too slow for its taste. In other words, if this server delays to an excessive degree in providing the optimization engine with the
* set of all possible routes, the optimization engine can terminate those processes and instead entrust the decision to the Google
* Maps API. This method suffers from a minor caveat; the Google Maps API refuses to compute the duration in traffic for any journey
* involving multiple locations if the intermediate points separating the origin and destination are assumed to be stopover points (i.e.
* if it is assumed that the driver will stop at each point) therefore this method assumes that the driver will not stop at the intermediate
* points. This may introduce some inaccuracies into the predictions.
* (it should be noted that this server has not yet been equipped with the ability to generate all possible routes so this method is, at the
* at the moment, the only option)
*
* #param requestParameters the parameters required for a Google Maps API query; see the RequestParameters class for more information
*
* #return the default route
*/
public static DirectionsRoute getDefaultRoute(ArrayList<LatLng> locations,RequestParameters requestParameters) throws ApiException, InterruptedException, IOException
{
LatLng origin = locations.get(0);
LatLng destination = locations.get(locations.size() - 1);
// separate waypoints
int numWaypoints = locations.size() - 2;
DirectionsApiRequest.Waypoint[] waypoints = new DirectionsApiRequest.Waypoint[numWaypoints];
for(int i = 0; i < waypoints.length; i++)
{
// ensure that each waypoint is not designated as a stopover point
waypoints[i] = new DirectionsApiRequest.Waypoint(locations.get(i + 1),false);
}
// send API query
// store API query response
DirectionsResult directionsResult = null;
try
{
// create DirectionsApiRequest object
DirectionsApiRequest directionsRequest = new DirectionsApiRequest(context);
// set request parameters
directionsRequest.units(requestParameters.getUnit());
directionsRequest.mode(TravelMode.DRIVING);
directionsRequest.trafficModel(requestParameters.getTrafficModel());
if(requestParameters.getRestrictions() != null)
{
directionsRequest.avoid(requestParameters.getRestrictions());
}
directionsRequest.region(requestParameters.getRegion());
directionsRequest.language(requestParameters.getLanguage());
directionsRequest.departureTime(requestParameters.getDepartureTime());
// always generate alternative routes
directionsRequest.alternatives(false);
directionsRequest.origin(origin);
directionsRequest.destination(destination);
directionsRequest.waypoints(waypoints);
directionsRequest.optimizeWaypoints(requestParameters.optimizeWaypoints());
// send request and store result
// testing - notification that a new api query is being sent
System.out.println("firing off API query...");
directionsResult = directionsRequest.await();
// testing - notification that api query was successful
System.out.println("API query successful");
}
catch(Exception e)
{
System.out.println(e);
}
// directionsResult.routes contains only a single, optimized route
// return the default route
return directionsResult.routes[0];
} // end method
/**
* Returns the distance of the default route.
*
* #param defaultRoute the default route
*
* #return the distance of the default route
*/
public static Distance getDefaultRouteDistance(DirectionsRoute defaultRoute)
{
// testing - simple notification
System.out.println("Computing distance...");
// each route has only 1 leg since all the waypoints are non-stopover points
return defaultRoute.legs[0].distance;
}
}
Here is the client-side code:
package com.mycompany.app;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.maps.model.LatLng;
import com.google.maps.model.TrafficModel;
import com.google.maps.DirectionsApi.RouteRestriction;
import com.google.maps.model.TransitRoutingPreference;
import com.google.maps.model.TravelMode;
import com.google.maps.model.Unit;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Call;
import okhttp3.Response;
import okhttp3.MediaType;
import okhttp3.HttpUrl;
// time constructs
import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.concurrent.TimeUnit;
import com.google.maps.model.Distance;
import com.google.maps.model.Duration;
import java.io.IOException;
public class App
{
// model database
private static LatLng hartford_ct = new LatLng(41.7658,-72.6734);
private static LatLng loretto_pn = new LatLng(40.5031,-78.6303);
private static LatLng chicago_il = new LatLng(41.8781,-87.6298);
private static LatLng newyork_ny = new LatLng(40.7128,-74.0060);
private static LatLng newport_ri = new LatLng(41.4901,-71.3128);
private static LatLng concord_ma = new LatLng(42.4604,-71.3489);
private static LatLng washington_dc = new LatLng(38.8951,-77.0369);
private static LatLng greensboro_nc = new LatLng(36.0726,-79.7920);
private static LatLng atlanta_ga = new LatLng(33.7490,-84.3880);
private static LatLng tampa_fl = new LatLng(27.9506,-82.4572);
// singleton client
private static final OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(700,TimeUnit.SECONDS)
.writeTimeout(700, TimeUnit.SECONDS)
.readTimeout(700, TimeUnit.SECONDS)
.build();
private static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
public static void main( String[] args ) throws IOException
{
// post location data
// get locations from database
ArrayList<LatLng> locations = new ArrayList<LatLng>();
// origin
LatLng origin = hartford_ct;
locations.add(origin);
// waypoints
locations.add(loretto_pn);
locations.add(chicago_il);
locations.add(newyork_ny);
locations.add(newport_ri);
locations.add(concord_ma);
locations.add(washington_dc);
locations.add(greensboro_nc);
locations.add(atlanta_ga);
// destination
LatLng destination = tampa_fl;
locations.add(destination);
// serialize locations list to json
Gson gson = new GsonBuilder().create();
String locationsJson = gson.toJson(locations);
// post to routing engine
RequestBody postLocationsRequestBody = RequestBody.create(JSON,locationsJson);
Request postLocationsRequest = new Request.Builder()
.url("http://localhost:4567/routingEngine/sendLocations")
.post(postLocationsRequestBody)
.build();
Call postLocationsCall = httpClient.newCall(postLocationsRequest);
Response postLocationsResponse = postLocationsCall.execute();
// get distance of default route
// generate parameters
Unit unit = Unit.METRIC;
LocalDateTime temp = LocalDateTime.now();
Instant departureTime= temp.atZone(ZoneOffset.UTC)
.withYear(2025)
.withMonth(8)
.withDayOfMonth(18)
.withHour(10)
.withMinute(12)
.withSecond(10)
.withNano(900)
.toInstant();
boolean optimizeWaypoints = true;
String optimizeWaypointsString = (optimizeWaypoints == true) ? "true" : "false";
TrafficModel trafficModel = TrafficModel.BEST_GUESS;
// restrictions
RouteRestriction[] restrictions = {RouteRestriction.TOLLS,RouteRestriction.FERRIES};
String region = "us"; // USA
String language = "en-EN";
RequestParameters requestParameters = new RequestParameters(unit,departureTime,true,trafficModel,restrictions,region,language);
// build url
HttpUrl url = new HttpUrl.Builder()
.scheme("http")
.host("127.0.0.1")
.port(4567)
.addPathSegment("routingEngine")
.addPathSegment("getDefaultRoute")
.addPathSegment("distance")
.build();
// build request
Request getDefaultRouteDistanceRequest = new Request.Builder()
.url(url)
.post(RequestBody.create(JSON,gson.toJson(requestParameters)))
.build();
// send request
Call getDefaultRouteDistanceCall = httpClient.newCall(getDefaultRouteDistanceRequest);
Response getDefaultRouteDistanceResponse = getDefaultRouteDistanceCall.execute();
// store and print response
Distance defaultRouteDistance = gson.fromJson(getDefaultRouteDistanceResponse.body().string(),Distance.class);
System.out.println("Default Route Distance: " + defaultRouteDistance);
}
}
Both classes use the following class RequestParameters to package all the request parameters together (i.e. unit, departure time, region, language etc...) just for convenience
package com.mycompany.app;
import com.google.maps.model.Unit;
import java.time.Instant;
import com.google.maps.model.TrafficModel;
import com.google.maps.DirectionsApi.RouteRestriction;
public class RequestParameters
{
private Unit unit;
private Instant departureTime;
private boolean optimizeWaypoints;
private TrafficModel trafficModel;
private RouteRestriction[] restrictions;
private String region;
private String language;
public RequestParameters(Unit unit, Instant departureTime, boolean optimizeWaypoints, TrafficModel trafficModel, RouteRestriction[] restrictions, String region, String language)
{
this.unit = unit;
this.departureTime = departureTime;
this.optimizeWaypoints = optimizeWaypoints;
this.trafficModel = trafficModel;
this.restrictions = restrictions;
this.region = region;
this.language = language;
}
// getters
public Unit getUnit()
{
return this.unit;
}
public Instant getDepartureTime()
{
return this.departureTime;
}
public boolean optimizeWaypoints()
{
return this.optimizeWaypoints;
}
public TrafficModel getTrafficModel()
{
return this.trafficModel;
}
public RouteRestriction[] getRestrictions()
{
return this.restrictions;
}
public String getRegion()
{
return this.region;
}
public String getLanguage()
{
return this.language;
}
// setters
public void setTrafficModel(TrafficModel trafficModel)
{
this.trafficModel = trafficModel;
}
public void setRegion(String region)
{
this.region = region;
}
public void setLanguage(String language)
{
this.language = language;
}
}
Hopefully this provides the information necessary to investigate the problem.
In the server-side App class, the last line of the main method reads
DirectionsUtility.context.shutdown();
This effectively shuts down the ExecutorService that the Maps Services API uses (inside its RateLimitExecutorService) and that is responsible for actually executing requests to Google. So your request is enqueued, but never actually executed.
Also, instead of doing System.out.println(e) (inside the DirectionsUtility class) it may be better do something like e.printStacktrace() so you'll have access to the whole error + it's stack.

Cannot redirect with the Vaadin navigator

I've a very strange behavior, I think I have two issues, I put them together on the same post because they can be linked :
my code is :
VaadinSession.getCurrent().setAttribute("user", user);
System.out.println("User :"+ user);
getUI().getNavigator().navigateTo(HomePageView.HOMEPAGE);
1. First issue
I'm on the login page, I can see my user information, but I cannot navigate to the homepage.
I don't have any error !
If I delete the line with the vaadinSession, the navigator is working...
2. Second Issue
I tried to debug my code but I received a "source not found", to fix that, I follow Eclipse java debugging: source not found. But, seems to working for me.
What I did :
I recreated a new workspace without success.
I edited the source lookup path and I have my java project in it
In the preferences -> java -> installed JREs -> I've the 1.8.0 JDK
right click on the project -> maven -> download sources
right click on the project -> maven -> disable maven nature and after Configure -> project to maven
EDIT : SOLUTION for the issue 2 :
I was so blocked... I know it's an eclipse issue (configuration or something like that). I changed for IntelliJ. This IDE show me sources without problem.
INFO
I'm using Vaadin and REST web services (with the javax.ws.rs.client.ClientBuilder).
When I use SYSOUT, I have the good information. I received the information from the homepage (instead of the view seems to keep the login view).
Any hint will be very useful !
EDIT : Full LoginView class
package com.test.project.View;
import com.test.project.model.User;
import com.test.project.restclient.RestClient;
import com.vaadin.annotations.Title;
import com.vaadin.data.Binder;
import com.vaadin.data.validator.EmailValidator;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
/**
* Login View. The user should enter his email address. Extends {#link CustomComponent} and implements {#link View}
*
* #author Bob
*/
#Title("Sign Up")
public class LoginView extends CustomComponent implements
View {
private static final long serialVersionUID = 1L;
public static final String LOGIN = "";
private VerticalLayout vLayout = new VerticalLayout();
private static final String SIGNUP_LABEL = "Sign Up";
private static final String EMAIL_CAPTION = "Type your email here :";
private static final String SIGNIN_LABEL = "Sign In";
private TextField email;
private static final String TOKEN_ATTRIBUTE_LABEL = "token";
private final Binder<User> binder = new Binder<>();
private User user;
private Button loginButton;
/**
* Login view Constructor
*/
public LoginView() {
createLoginPanel();
addListener();
}
/**
* Add Listener concern by the Login View Fields
*/
private void addListener() {
loginButton.addClickListener(e -> {
RestClient rc = new RestClient();
user = rc.getUserInfo(email.getValue());
VaadinSession.getCurrent().setAttribute(TOKEN_ATTRIBUTE_LABEL, user.getToken());
System.out.println();
getUI().getNavigator().navigateTo(HomePageView.HOMEPAGE);
});
}
/**
* Create the login panel with the email field and the login button
*/
private void createLoginPanel() {
final VerticalLayout layout = new VerticalLayout();
layout.setSizeFull();
Panel panel = new Panel(SIGNUP_LABEL);
panel.setHeight(200, Unit.PIXELS);
panel.setWidth(300, Unit.PIXELS);
email = new TextField();
email.setCaption(EMAIL_CAPTION);
email.setHeight(30, Unit.PIXELS);
email.setWidth(275, Unit.PIXELS);
binder.forField(email).withValidator(new EmailValidator("This doesn't look like a valid email address")).bind(User::getEmail, User::setEmail);
loginButton = new Button(SIGNIN_LABEL);
loginButton.setIcon(VaadinIcons.SIGN_IN);
layout.addComponents(email, loginButton);
layout.setComponentAlignment(loginButton, Alignment.BOTTOM_RIGHT);
panel.setContent(layout);
vLayout.addComponent(panel);
vLayout.setSizeFull();
vLayout.setComponentAlignment(panel, Alignment.MIDDLE_CENTER);
setCompositionRoot(vLayout);
}
/* (non-Javadoc)
* #see com.vaadin.navigator.View#enter(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent)
*/
#Override
public void enter(ViewChangeEvent event) {
email.focus();
}
}
Rest client class :
package com.test.project.restclient;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.test.project.model.User;
/**
* Class contain the Rest Client which allow to use and call the rest web services.
*
* #author Bob
*/
public class RestClient {
private static final String EMAIL_LABEL = "email";
private static final Logger LOG = LoggerFactory.getLogger(RestClient.class);
private Client client;
public RestClient() {
client = ClientBuilder.newClient(new ClientConfig());
}
/**
* Get the user information from the user email
*
* #param email
* #return user
*/
#SuppressWarnings("unchecked")
#POST
#Path("http://IpAddress:8080/api/authentication/")
public User getUserInfo(String email) {
JSONObject obj = new JSONObject();
obj.put(EMAIL_LABEL, email);
WebTarget webtarget = client.target("http://IpAddress:8080/api/authentication/");
Response response = webtarget.request().accept(MediaType.APPLICATION_JSON).post(Entity.entity(obj, MediaType.APPLICATION_JSON));
String answer = response.readEntity(String.class);
LOG.info("User information are :" + answer);
Gson g = new Gson();
User user = g.fromJson(answer, User.class);
return user;
}
}
Home Page View :
package com.test.project.View;
import com.test.project.model.Action;
import com.test.project.restclient.RestClient;
import com.vaadin.data.Binder;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.Button;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
/**
* Home page view.
*
* #author Bob
*/
public class HomePageView extends CustomComponent implements
View {
private static final long serialVersionUID = 1L;
public static final String HOMEPAGE = "home";
private final VerticalLayout layout;
private static final String TOKEN_ATTRIBUTE_LABEL = "token";
/**
* Home page View constructor
*/
public HomePageView() {
layout = new VerticalLayout();
layout.setSizeFull();
String CURRENT_USER_TOKEN = (String) VaadinSession.getCurrent().getAttribute(TOKEN_ATTRIBUTE_LABEL);
System.out.println("Current user token : " + CURRENT_USER_TOKEN);
createMenu();
setCompositionRoot(layout);
}
/**
* Create a Vertical Menu with the Home page and Actions page
*/
private void createMenu() {
MenuBar barmenu = new MenuBar();
barmenu.addItem("Homepage", VaadinIcons.HOME, null);
barmenu.addItem("Actions", VaadinIcons.TABLE, null);
layout.addComponent(barmenu);
}
/* (non-Javadoc)
* #see com.vaadin.navigator.View#enter(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent)
*/
#Override
public void enter(ViewChangeEvent event) {
}
}
Ok, I found the solution/workarround for the issues :
For the first issue : "token" seems to be a reserved word, "tokenEmployee" seems to be better and it's working perfectly...
For the second issue : I still don't know why it's not working in Eclipse, I've the source but in debug mode, I'm not able to see them. I changed for IntelliJ. I was not able to find any thing about reserved words for the Vaadin Session. If someone find a link or something, I'm very interested !
Too much time trying to fix it..
A bit thanks to #jay who tried to help me!

Can we use YouTube Analytics Api using Java and Eclipse?

I tried reading google tutorials and doing the YouTube Analytics Api example. But, I am unable to make the code. Can someone help me to make it (using Java and Eclipse) ?
it shows an error in Import file
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtubeAnalytics.YoutubeAnalytics;
import com.google.api.services.youtubeAnalytics.model.ResultTable;
import com.google.api.services.youtubeAnalytics.model.ResultTable.ColumnHeaders;
import com.google.common.collect.Lists;
Example :
package com.google.api.services.samples.youtube.cmdline.youtube_analytics_cmdline_report_sample;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtubeAnalytics.YoutubeAnalytics;
import com.google.api.services.youtubeAnalytics.model.ResultTable;
import com.google.api.services.youtubeAnalytics.model.ResultTable.ColumnHeaders;
import com.google.common.collect.Lists;
public class Samp {
/**
* Demo displaying YouTube metrics from a user's channel using the YouTube Data and YouTube
* Analytics APIs. It also uses OAuth2 for authorization.
*
* #author Christoph Schwab-Ganser and Jeremy Walker
*/
public class YouTubeAnalyticsReports {
/** Global instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
/** Global instance of Youtube object to make general YouTube API requests. */
private static YouTube youtube;
/** Global instance of YoutubeAnalytics object to make analytic API requests. */
private static YoutubeAnalytics analytics;
/**
* Authorizes the installed application to access user's protected YouTube data.
*
* #param scopes list of scopes needed to access general and analytic YouTube info.
*/
private static Credential authorize(List<String> scopes) throws Exception {
// Load client secrets.
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(
JSON_FACTORY,
YouTubeAnalyticsReports.class.getResourceAsStream("/client_secrets.json"));
// Checks that the defaults have been replaced (Default = "Enter X here").
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
System.err.println(
"Enter Client ID and Secret from https://code.google.com/apis/console/?api=youtube"
+ "into youtube-analytics-cmdline-report-sample/src/main/resources/client_secrets.json");
System.exit(1);
}
// Set up file credential store.
FileCredentialStore credentialStore =
new FileCredentialStore(
new File(System.getProperty("user.home"),
".credentials/youtube-analytics-api-report.json"),
JSON_FACTORY);
// Set up authorization code flow.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
JSON_FACTORY,
clientSecrets,
scopes)
.setCredentialStore(credentialStore).build();
// Authorize.
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
/**
* Authorizes user, gets user's default channel via YouTube Data API, and gets/prints stats on
* user's channel using the YouTube Analytics API.
*
* #param args command line args (not used).
*/
public static void main(String[] args) {
// Scopes required to access YouTube general and analytics information.
List<String> scopes = Lists.newArrayList(
"https://www.googleapis.com/auth/yt-analytics.readonly",
"https://www.googleapis.com/auth/youtube.readonly"
);
try {
Credential credential = authorize(scopes);
// YouTube object used to make all non-analytic API requests.
youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("youtube-analytics-api-report-example")
.build();
// YouTube object used to make all analytic API requests.
analytics = new YoutubeAnalytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("youtube-analytics-api-report-example")
.build();
// Constructs request to get channel id for current user.
YouTube.Channels.List channelRequest = youtube.channels().list("id,snippet");
channelRequest.setMine(true);
channelRequest.setFields("items(id,snippet/title)");
ChannelListResponse channels = channelRequest.execute();
// List of channels associated with user.
List<Channel> listOfChannels = channels.getItems();
// Grab default channel which is always the first item in the list.
Channel defaultChannel = listOfChannels.get(0);
String channelId = defaultChannel.getId();
PrintStream writer = System.out;
if (channelId == null) {
writer.println("No channel found.");
} else {
writer.println("Default Channel: " + defaultChannel.getSnippet().getTitle() +
" ( " + channelId + " )\n");
printData(writer, "Views Over Time.", executeViewsOverTimeQuery(analytics, channelId));
printData(writer, "Top Videos", executeTopVideosQuery(analytics, channelId));
printData(writer, "Demographics", executeDemographicsQuery(analytics, channelId));
}
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
e.printStackTrace();
} catch (Throwable t) {
System.err.println("Throwable: " + t.getMessage());
t.printStackTrace();
}
}
/**
* Returns the views and unique viewers per day.
*
* #param analytics the analytics service object used to access the API.
* #param id the string id from which to retrieve data.
* #return the response from the API.
* #throws IOException if an API error occurred.
*/
private static ResultTable executeViewsOverTimeQuery(YoutubeAnalytics analytics,
String id) throws IOException {
return analytics.reports()
.query("channel==" + id, // channel id
"2012-01-01", // Start date.
"2012-01-14", // End date.
"views,uniques") // Metrics.
.setDimensions("day")
.setSort("day")
.execute();
}
/**
* Returns the top video by views.
*
* #param analytics the analytics service object used to access the API.
* #param id the string id from which to retrieve data.
* #return the response from the API.
* #throws IOException if an API error occurred.
*/
private static ResultTable executeTopVideosQuery(YoutubeAnalytics analytics,
String id) throws IOException {
return analytics.reports()
.query("channel==" + id, // channel id
"2012-01-01", // Start date.
"2012-08-14", // End date.
"views,subscribersGained,subscribersLost") // Metrics.
.setDimensions("video")
.setSort("-views")
.setMaxResults(10)
.execute();
}
/**
* Returns the demographics report
*
* #param analytics the analytics service object used to access the API.
* #param id the string id from which to retrieve data.
* #return the response from the API.
* #throws IOException if an API error occurred.
*/
private static ResultTable executeDemographicsQuery(YoutubeAnalytics analytics,
String id) throws IOException {
return analytics.reports()
.query("channel==" + id, // channel id
"2007-01-01", // Start date.
"2012-08-14", // End date.
"viewerPercentage") // Metrics.
.setDimensions("ageGroup,gender")
.setSort("-viewerPercentage")
.execute();
}
/**
* Prints the output from the API. The channel name is printed along with
* each column name and all the data in the rows.
* #param writer stream to output to
* #param title title of the report
* #param results data returned from the API.
*/
private static void printData(PrintStream writer, String title, ResultTable results) {
writer.println("Report: " + title);
if (results.getRows() == null || results.getRows().isEmpty()) {
writer.println("No results Found.");
} else {
// Print column headers.
for (ColumnHeaders header : results.getColumnHeaders()) {
writer.printf("%30s", header.getName());
}
writer.println();
// Print actual data.
for (List<Object> row : results.getRows()) {
for (int colNum = 0; colNum < results.getColumnHeaders().size(); colNum++) {
ColumnHeaders header = results.getColumnHeaders().get(colNum);
Object column = row.get(colNum);
if ("INTEGER".equals(header.getUnknownKeys().get("dataType"))) {
long l = ((BigDecimal) column).longValue();
writer.printf("%30d", l);
} else if ("FLOAT".equals(header.getUnknownKeys().get("dataType"))) {
writer.printf("%30f", column);
} else if ("STRING".equals(header.getUnknownKeys().get("dataType"))) {
writer.printf("%30s", column);
} else {
// default output.
writer.printf("%30s", column);
}
}
writer.println();
}
writer.println();
}
}
}
}
It would be helpful if you could state what error do you see in Imports?
But assuming you are finding errors in Imports it means you are missing project dependencies in your project path. Find the dependencies in Maven POM.xml. If you are not using Maven to build your project, then please download all the dependent JAR files as mentioned in POM.xml

Programmatically downloading a file using Selenium in Java

I was looking for a Chrome Extension which can intercept the download whenever we click on a PDF link or on a link that spawns a PDF at server end programmatically. One way of doing it was Selenium Browser Profiling, I found this particular code. I want Selenium to download the PDF file and rename it according to the strings i pass from the JAVA program.
How can i use this code to download code and hook it up it with my program. It should trigger this whenever i execute a command like this:-
**driver.findElement(By.xpath("//a[contains(#href,\"/bbtobs/bbtolbext/statements/savepdf?type=current&AccountIndex=0\")]")).click();**
CODE-
package com.lazerycode.selenium.filedownloader;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.log4j.Logger;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Set;
public class FileDownloader {
private static final Logger LOG = Logger.getLogger(FileDownloader.class);
private WebDriver driver;
private String localDownloadPath = System.getProperty("java.io.tmpdir");
private boolean followRedirects = true;
private boolean mimicWebDriverCookieState = true;
private int httpStatusOfLastDownloadAttempt = 0;
public FileDownloader(WebDriver driverObject) {
this.driver = driverObject;
}
/**
* Specify if the FileDownloader class should follow redirects when trying to download a file
*
* #param value
*/
public void followRedirectsWhenDownloading(boolean value) {
this.followRedirects = value;
}
/**
* Get the current location that files will be downloaded to.
*
* #return The filepath that the file will be downloaded to.
*/
public String localDownloadPath() {
return this.localDownloadPath;
}
/**
* Set the path that files will be downloaded to.
*
* #param filePath The filepath that the file will be downloaded to.
*/
public void localDownloadPath(String filePath) {
this.localDownloadPath = filePath;
}
/**
* Download the file specified in the href attribute of a WebElement
*
* #param element
* #return
* #throws Exception
*/
public String downloadFile(WebElement element) throws Exception {
return downloader(element, "href");
}
/**
* Download the image specified in the src attribute of a WebElement
*
* #param element
* #return
* #throws Exception
*/
public String downloadImage(WebElement element) throws Exception {
return downloader(element, "src");
}
/**
* Gets the HTTP status code of the last download file attempt
*
* #return
*/
public int getHTTPStatusOfLastDownloadAttempt() {
return this.httpStatusOfLastDownloadAttempt;
}
/**
* Mimic the cookie state of WebDriver (Defaults to true)
* This will enable you to access files that are only available when logged in.
* If set to false the connection will be made as an anonymouse user
*
* #param value
*/
public void mimicWebDriverCookieState(boolean value) {
this.mimicWebDriverCookieState = value;
}
/**
* Load in all the cookies WebDriver currently knows about so that we can mimic the browser cookie state
*
* #param seleniumCookieSet
* #return
*/
private BasicCookieStore mimicCookieState(Set seleniumCookieSet) {
BasicCookieStore mimicWebDriverCookieStore = new BasicCookieStore();
for (Cookie seleniumCookie : seleniumCookieSet) {
BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());
duplicateCookie.setDomain(seleniumCookie.getDomain());
duplicateCookie.setSecure(seleniumCookie.isSecure());
duplicateCookie.setExpiryDate(seleniumCookie.getExpiry());
duplicateCookie.setPath(seleniumCookie.getPath());
mimicWebDriverCookieStore.addCookie(duplicateCookie);
}
return mimicWebDriverCookieStore;
}
/**
* Perform the file/image download.
*
* #param element
* #param attribute
* #return
* #throws IOException
* #throws NullPointerException
*/
private String downloader(WebElement element, String attribute) throws IOException, NullPointerException, URISyntaxException {
String fileToDownloadLocation = element.getAttribute(attribute);
if (fileToDownloadLocation.trim().equals("")) throw new NullPointerException("The element you have specified does not link to anything!");
URL fileToDownload = new URL(fileToDownloadLocation);
File downloadedFile = new File(this.localDownloadPath + fileToDownload.getFile().replaceFirst("/|\\\\", ""));
if (downloadedFile.canWrite() == false) downloadedFile.setWritable(true);
HttpClient client = new DefaultHttpClient();
BasicHttpContext localContext = new BasicHttpContext();
LOG.info("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState);
if (this.mimicWebDriverCookieState) {
localContext.setAttribute(ClientContext.COOKIE_STORE, mimicCookieState(this.driver.manage().getCookies()));
}
HttpGet httpget = new HttpGet(fileToDownload.toURI());
HttpParams httpRequestParameters = httpget.getParams();
httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);
httpget.setParams(httpRequestParameters);
LOG.info("Sending GET request for: " + httpget.getURI());
HttpResponse response = client.execute(httpget, localContext);
this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
LOG.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt);
LOG.info("Downloading file: " + downloadedFile.getName());
FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
response.getEntity().getContent().close();
String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
LOG.info("File downloaded to '" + downloadedFileAbsolutePath + "'");
return downloadedFileAbsolutePath;
}
}
String s = driver.findElement(By.cssSelector("#navbtm img")).getAttribute("src");
URL url = new URL(s);
System.out.println(url);
BufferedImage bufImgOne = ImageIO.read(url);
ImageIO.write(bufImgOne, "png", new File("test.png"));
I have found an excellent article about it. Tried, and works perfectly:
http://ardesco.lazerycode.com/index.php/2012/07/how-to-download-files-with-selenium-and-why-you-shouldnt/
UPDATE:
Better solution is to get the image from the browser itself:
https://groups.google.com/forum/#!msg/selenium-users/8atiPIh39OY/Gp9_KEXnpRUJ

Categories