as I m new for the Calendar API so i came up with the authorization part but not able to insert events into the calendar.
While inserting events it is showing the the error
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Insufficient Permission",
"reason" : "insufficientPermissions"
} ],
"message" : "Insufficient Permission"
}
Here is my entire code, if it will help:
package com.drive;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
//import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeServlet;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.util.ArrayMap;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.GenericData;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.google.api.services.calendar.*;
import com.google.api.services.calendar.Calendar.CalendarList;
import com.google.api.services.calendar.Calendar.Events;
import com.google.api.services.calendar.model.Acl;
import com.google.api.services.calendar.model.AclRule;
import com.google.api.services.calendar.model.CalendarListEntry;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.EventAttendee;
import com.google.api.services.calendar.model.EventDateTime;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
/**
* Entry sevlet for the Plus App Engine Sample. Demonstrates how to make an authenticated API call
* using OAuth2 helper classes.
*
* #author Nick Miceli
*/
public class DriveSampleServlet extends AbstractAppEngineAuthorizationCodeServlet {
// List the scopes your app requires. These must match the scopes
// registered in the Admin console for your Google Apps domain.
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
User user =UserServiceFactory.getUserService().getCurrentUser();
if(user!=null){
AuthorizationCodeFlow authFlow = initializeFlow();
Credential credential = authFlow.loadCredential(getUserId(req));
Calendar calendar =new Calendar.Builder(Utils.HTTP_TRANSPORT,Utils.JSON_FACTORY, credential).setApplicationName("ashishwaiting96").build();
// Drive drive = new Drive.Builder(Utils.HTTP_TRANSPORT, Utils.JSON_FACTORY, credential).setApplicationName("ashishwaiting96").build();
/* resp.getWriter().print("success"+calendar.acl().list(" sial.com_li54bsfij3i31a9a8uqdvurr3c#group.calendar.google.com").execute());
*/
com.google.api.services.calendar.model.Calendar calendar1 = calendar.calendars().get("primary").execute();
resp.getWriter().print("success"+calendar1.getSummary()+" "+calendar1.getKind()+" "+calendar1.getDescription());
Event event = new Event();
event.setSummary("appointment");
Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + 3600000);
DateTime start = new DateTime(startDate, TimeZone.getTimeZone("UTC"));
event.setStart(new EventDateTime().setDateTime(start));
DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
event.setEnd(new EventDateTime().setDateTime(end));
Event createdEvent = calendar.events().insert("primary", event).execute();
System.out.println(createdEvent.getId());
}
}
#Override
protected AuthorizationCodeFlow initializeFlow() throws ServletException, IOException {
return Utils.initializeFlow();
}
#Override
protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
return Utils.getRedirectUri(req);
}
}
snippet 2:
package com.drive;
import com.google.api.client.extensions.appengine.datastore.AppEngineDataStoreFactory;
import com.google.api.client.extensions.appengine.http.UrlFetchTransport;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Preconditions;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.drive.DriveScopes;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
class Utils {
private static final AppEngineDataStoreFactory DATA_STORE_FACTORY =
AppEngineDataStoreFactory.getDefaultInstance();
private static GoogleClientSecrets clientSecrets = null;
// private static Set<String> SCOPES = Collections.singleton(PlusScopes.PLUS_ME);
private static List<String> SCOPES = new ArrayList<String>();
static final String MAIN_SERVLET_PATH = "/DriveSampleServlet";
static final String AUTH_CALLBACK_SERVLET_PATH = "/oauth2callback";
static final UrlFetchTransport HTTP_TRANSPORT = new UrlFetchTransport();
static final JacksonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static GoogleClientSecrets getClientSecrets() throws IOException {
if (clientSecrets == null) {
clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
new InputStreamReader(Utils.class.getResourceAsStream("/client_secret.json")));
Preconditions.checkArgument(!clientSecrets.getDetails().getClientId().startsWith("Enter")
&& !clientSecrets.getDetails().getClientSecret().startsWith("Enter "),
"Download client_secrets.json file from https://code.google.com/apis/console/?api=plus "
+ "into plus-appengine-sample/src/main/resources/client_secrets.json");
}
return clientSecrets;
}
static GoogleAuthorizationCodeFlow initializeFlow() throws IOException {
//SCOPES.add(DriveScopes.DRIVE);
SCOPES.add(CalendarScopes.CALENDAR);
// SCOPES.add(PlusDomainsScopes.PLUS_ME);
// SCOPES.add(PlusDomainsScopes.PLUS_PROFILES_READ);
GoogleAuthorizationCodeFlow gf=
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, getClientSecrets(), SCOPES).setDataStoreFactory(
DATA_STORE_FACTORY).setAccessType("offline").setApprovalPrompt("force").build();
return gf;
}
static String getRedirectUri(HttpServletRequest req) {
GenericUrl requestUrl = new GenericUrl(req.getRequestURL().toString());
requestUrl.setRawPath(AUTH_CALLBACK_SERVLET_PATH);
return requestUrl.build();
}
}
I added the secret.json file which is working,
any help..
Insufficient Permission error is thrown when the authenticated user does not have sufficient permissions to execute this request. When I looked at the code, I see the line
// private static Set SCOPES = Collections.singleton(PlusScopes.PLUS_ME);
is commented out. When you are trying to add the calendar events, there should be scopes with WRITE authorization to the users profile in the code. You can try uncommenting the above line or uncomment the below lines:
// SCOPES.add(PlusDomainsScopes.PLUS_ME);
// SCOPES.add(PlusDomainsScopes.PLUS_PROFILES_READ);
Here are the links that will help you:
link1
link2
Also, if you are trying to add event into some one's calendar then you should have permission to do that. Please check this scenario too.
Related
I'm trying to test the onException(JsonProcessingException.class) route in the following class (please don't mind its name, I've cut some code out for clarity):
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.rest.RestBindingMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonProcessingException;
import pl.muni.camel.sample.customer.domain.CustomerData;
import pl.muni.camel.sample.customer.route.processor.CreateCustomerErrorResponseProcessor;
import pl.muni.camel.sample.customer.route.processor.CreateCustomerOkResponseProcessor;
#Component
public class SendCustomerDataToQueueRoute extends RouteBuilder {
#Value("${http.rest.listener.host}")
private String restListenerHost;
#Value("${http.rest.listener.port}")
private int restListenerPort;
#Override
public void configure() {
restConfiguration()
.component("restlet")
.dataFormatProperty("prettyPrint", "true")
.host(restListenerHost)
.port(restListenerPort);
rest("/rest/v1/customer")
.post("/create")
.bindingMode(RestBindingMode.json)
.skipBindingOnErrorCode(false)
.consumes("application/json")
.type(CustomerData.class)
.produces("application/json")
.route().id("acceptCreateCustomerRequest")
.from("direct:acceptRequest")
.to("direct:processRequest");
onException(JsonProcessingException.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
.to("direct:processException");
onException(Exception.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(500))
.to("direct:processException");
from("direct:processRequest").routeId("processCreateCustomerRequest")
.log("Received customer data: ${body}")
.process(new CreateCustomerOkResponseProcessor()).id("createOkResponse");
from("direct:processException").routeId("processCreateCustomerException")
.log(LoggingLevel.ERROR, "${exception.stacktrace}").id("logExceptionStackTrace")
.process(new CreateCustomerErrorResponseProcessor()).id("createErrorResponse");
}
}
I want to intercept the exchange after createErrorResponse processor and run some assertions on it. So far I've come up with this code, in which I weave in a mock endpoint after direct:processException endpoint:
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringBootRunner;
import org.apache.camel.test.spring.EnableRouteCoverage;
import org.apache.camel.test.spring.MockEndpointsAndSkip;
import org.apache.camel.test.spring.UseAdviceWith;
import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.annotation.DirtiesContext;
import pl.muni.camel.sample.customer.infrastructure.rest.CreateCustomerResponse;
#UseAdviceWith
#MockEndpointsAndSkip("restlet*")
#EnableRouteCoverage
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
#SpringBootTest
#ComponentScan("pl.muni.camel.sample.customer")
#RunWith(CamelSpringBootRunner.class)
public class SendCustomerDataToQueueIntegrationTest {
#Produce
private ProducerTemplate producerTemplate;
#Autowired
private CamelContext context;
#EndpointInject(uri = "mock:error")
private MockEndpoint errorEndpoint;
#Before
public void setUp() throws Exception {
context.getRouteDefinition("processCreateCustomerRequest").adviceWith(context, new AdviceWithRouteBuilder() {
#Override
public void configure() {
weaveByToUri("direct:processException")
.after()
.to("mock:error");
}
});
context.start();
}
#After
public void tearDown() throws Exception {
context.stop();
}
#Test
public void shouldReturnHttpStatus400ForInvalidJson() throws InterruptedException {
// given
final String customerDataString = "{\"firstName\": \"aaa\", \"lastname\": \"bbb\"}";
//when
producerTemplate.sendBody("direct:acceptRequest", customerDataString);
//then
errorEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 400);
errorEndpoint.assertIsSatisfied();
final List<Exchange> exchanges = errorEndpoint.getExchanges();
Assertions.assertThat(exchanges).hasSize(1);
final Exchange exchange = exchanges.get(0);
final CreateCustomerResponse response = exchange.getIn().getBody(CreateCustomerResponse.class);
Assertions.assertThat(response.isSuccess()).isFalse();
Assertions.assertThat(response.getErrorMessage()).startsWith("UnrecognizedPropertyException: Unrecognized field \"lastname\"");
}
}
Unfortunately, the Exchange.HTTP_RESPONSE_CODE header somehow disappears during the test and the assertion on errorEndpoint fails. I ran the test with debugger and breakpoint set within CreateCustomerErrorResponseProcessor class and there the header was still available.
Is there another way to set up the test and be able to retrieve the header or could this be a bug?
The URI you are weaving ("direct:processException") in your unit test is attached to a wrong route definition.
It should be:
context.getRouteDefinition("processCreateCustomerException").adviceWith(...)
(and not "processCreateCustomerRequest")
I am working on Rest Api, I want to implement facebook Login/Signup in my application.
My client is angularjs based application that sends request to facebook and get the authentication code, so far I have used custom filter that calls facebook and fetches user data after validating the Access Token.
I can now get the user details from Facebook and persist in my local database, but when i try to signup from my application for it moves to the custom filter that i made for facebook integration.Here is my SecurityConfiguration.java
package io.aurora.ams.config;
import io.aurora.ams.security.AuthoritiesConstants;
import io.aurora.ams.web.filter.MDCFilter;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import javax.inject.Inject;
import static io.aurora.ams.sharedkernel.support.RestPath.*;
#Configuration
#EnableWebSecurity(debug = true)
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
#ImportResource("classpath:acl-config.xml")
#SuppressWarnings("ALL")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
#Bean
public AuthFilter authFilter()
{
return new AuthFilter();
}
#Inject
private UserDetailsService userDetailsService;
#Bean
public PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
#Inject
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
{
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
public MDCFilter mdcFilter()
{
return new MDCFilter();
}
#Bean
public FilterRegistrationBean mySecurityFilter()
{
FilterRegistrationBean registration = new FilterRegistrationBean(authFilter());
registration.setOrder(10);
return registration;
}
#Override
public void configure(WebSecurity web) throws Exception
{
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers(API_VERSION_1_ACCOUNT_REGISTER_PATIENT)
.antMatchers(API_VERSION_1_ACCOUNT_ACTIVATE)
.antMatchers(API_VERSION_1_ACCOUNT_RECOVER_PASSWORD)
.antMatchers("/test/**")
.antMatchers("/h2-console/**");
}
#Override
#Order(Ordered.HIGHEST_PRECEDENCE)
public void configure(HttpSecurity http) throws Exception
{
http
.addFilterBefore(authFilter(), OAuth2ClientAuthenticationProcessingFilter.class)
.addFilterAfter(mdcFilter(), SecurityContextPersistenceFilter.class)
.httpBasic().realmName("pliro")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/oauth/authorize").permitAll()
.antMatchers("api/v1/auth/facebook").permitAll()
.antMatchers("api/v1/code").permitAll()
.and()
.authorizeRequests()
.antMatchers(API_VERSION_1_DOCTOR).permitAll()
.antMatchers(API + "/**").authenticated();
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception
{
return super.authenticationManagerBean();
}
#Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension()
{
return new SecurityEvaluationContextExtension();
}
}
This is my CustomFilter AuthFilter.java
package io.aurora.ams.config;
import io.aurora.ams.account.domain.model.user.User;
import io.aurora.ams.account.dto.UserDTO;
import io.aurora.ams.account.mapper.UserMapper;
import io.aurora.ams.account.repository.UserRepository;
import io.aurora.ams.sharedkernel.domain.model.Gender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.InvalidAuthorizationException;
import org.springframework.social.connect.Connection;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.connect.FacebookConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.inject.Inject;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by ozair on 16/6/16.
*/
#Component
public class AuthFilter extends OncePerRequestFilter
{
#Autowired
private UserRepository userRepository;
#Autowired
private FacebookConnectionFactory facebookConnectionFactory;
#Inject
private UserMapper userMapper;
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException
{
String xAuth = request.getHeader("fbToken");
try
{
User user = validateToken(xAuth);
// Create our Authentication and let Spring know about it
Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, AuthorityUtils.createAuthorityList("ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
catch (InvalidAuthorizationException ex)
{
logger.error(ex.getMessage());
}
filterChain.doFilter(request, response);
}
private User validateToken(String fbToken)
{
AccessGrant accessGrant = new AccessGrant(fbToken);
Connection<Facebook> connection = facebookConnectionFactory.createConnection(accessGrant);
org.springframework.social.facebook.api.User fbUser = connection.getApi().userOperations().getUserProfile();
String facebookId = fbUser.getId();
User user = userRepository.findBySocialId(facebookId);
if (user == null)
{
User userByEmail = userRepository.findByEmail(fbUser.getEmail());
if (userByEmail != null)
{
userByEmail.setSocialAccessGrant(accessGrant.getAccessToken());
userByEmail.setSocialId(facebookId);
userRepository.save(userByEmail);
return userByEmail;
}
else
{
String firstName = fbUser.getFirstName();
String lastName = fbUser.getLastName();
String email = fbUser.getEmail() == null ? "" : fbUser.getEmail();
UserDTO userDTO = new UserDTO();
userDTO.setFirstName(firstName);
userDTO.setLastName(lastName);
userDTO.setEmail(email);
userDTO.setPassword("123456");
userDTO.setPhoneNumber("03222211112");
userDTO.setGender(Gender.MALE);
userDTO.setSocialId(facebookId);
userDTO.setAccessGrant(accessGrant);
User userData = userMapper.userDTOtoUser(userDTO);
userRepository.save(userData);
return userData;
}
}
else
{
//update fbToken if not the same
if (user.getSocialAccessGrant() != null
&& !user.getSocialAccessGrant().equals(accessGrant.getAccessToken()))
{
user.setSocialAccessGrant(accessGrant.getAccessToken());
userRepository.save(user);
}
return user;
}
}
}
With below mentioned code,if the test case is pass-screenshot captured successfully and displayed in report.But when the test is failed--screenshot is not displayed.Even screenshot hyperlink is not displayed in report.Anybody can sort out the mistake in code?
package listeners;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import java.util.logging.Logger;
#Listeners
public class CountryChoserLayer extends TestListenerAdapter {
#Test(priority=1)
public void choseCountry() throws Exception{
driver.findElement(By.id("intselect")).sendKeys("India");
driver.findElement(By.xpath(".//*[#id='countryChooser']/a/img")).click();
//window.onbeforeunload = null;
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
FileUtils.copyFile(scrnsht, new File(NewFileNamePath));
System.out.println(NewFileNamePath);
Reporter.log("Passed Screenshot");
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case-Success");
System.out.println("---------------------------------------");
}
public String baseurl="http://www.sears.com/shc/s/CountryChooserView?storeId=10153&catalogId=12605";
public WebDriver driver;
public int Count = 0;
#Test(priority=0)
public void openBrowser() {
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.get(baseurl);
}
#Test(priority=2)
public void closeBrowser() {
driver.quit();
}
#Override
public void onTestFailure(ITestResult result){
Reporter.log("Fail");
System.out.println("BBB");
//Reporter.setCurrentTestResult(result);
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//File scrFile = ((TakesScreenshot) WebDriver.globalDriverInstance).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
//System.out.println("AAA" + NewFileNamePath);
try {
//System.out.println("CCC");
FileUtils.copyFile(scrnsht,new File(NewFileNamePath));
System.out.println(NewFileNamePath);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("DDD");
e.printStackTrace();
}
Reporter.log("Failed Screenshot");
Reporter.setCurrentTestResult(null);
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case Failed");
System.out.println("---------------------------------------");
}
#Override
public void onTestSkipped(ITestResult result) {
// will be called after test will be skipped
Reporter.log("Skip");
}
#Override
public void onTestSuccess(ITestResult result) {
// will be called after test will pass
Reporter.log("Pass");
}
}
Your onTestFailure method is not being called because you didn't specify listener for your test class. You are missing a value in #Listeners annotation. It should be something like
#Listeners({CountryChoserLayer.class})
You can find more ways of specifying a listener in official TestNg's documentation.
Another problem you are likely to encounter would be NullPointerException while trying to take screenshot in onTestFailure method. The easiest workaround for that would be changing the declaration of driver field to static. I run the code with those fixes and I got the report with screenshot.
I must add that in my opinion putting both test and listener methods into one class is not a good practice.
I am new to google cloud storage api, as well as using servers. I'm trying to write a web application in Java using Eclipse's IDE to read in a file that is stored in google's cloud storage. I have the code to read in the file on the server side, and am not sure how to modify the sample code on the client side so that it supports an httpServlet instead of a RemoteServiceServlet. Any help or suggestions would be greatly appreciated!
Below is my code on the server side.
package com.google.gwt.sample.interfacecloud.server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.Channels;
import java.util.ArrayList;
import javax.servlet.http.*;
import com.google.gwt.sample.interfacecloud.client.GreetingService;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;
#SuppressWarnings("serial")
public class CloudInteraction extends HttpServlet implements GreetingService{
public static final String BUCKETNAME = "obd_data";
public static final String FILENAME = "data.txt";
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
resp.setContentType("text/plain");
String filename = "/gs/" + BUCKETNAME + "/" + FILENAME;
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile readableFile = new AppEngineFile(filename);
FileReadChannel readChannel =
fileService.openReadChannel(readableFile, false);
BufferedReader reader =
new BufferedReader(Channels.newReader(readChannel, "UTF8"));
String line = reader.readLine();
resp.getWriter().println("READ:"+line);
System.out.println(line);
readChannel.close();
}
#Override
public String greetServer(String name) throws IllegalArgumentException {
// TODO Auto-generated method stub
return null;
}
}
You are mixing and matching RPC with plain Servlets. You should not be doing that. Do away with RPC interfaces for such interactions if you intend to you plain Servlets. You would be better served with RequestBuilder in this scenario. Note - it is not very clear what your are requirements are?
I deployed recently a Roo/Gwt project on Google App Engine.
I spent a couple of hours but couldn't find a tutorial that shows, step by step, how can we add n authentification system (withe the Federated Login Api).
I found this very good article that provides some helpful code :
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
#SuppressWarnings("serial")
public class OpenIdDemoServlet extends HttpServlet {
private static final Map<String, String> openIdProviders;
static {
openIdProviders = new HashMap<String, String>();
openIdProviders.put("Google", "google.com/accounts/o8/id");
openIdProviders.put("Yahoo", "yahoo.com");
openIdProviders.put("MySpace", "myspace.com");
openIdProviders.put("AOL", "aol.com");
openIdProviders.put("MyOpenId.com", "myopenid.com");
}
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser(); // or req.getUserPrincipal()
Set<String> attributes = new HashSet();
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
if (user != null) {
out.println("Hello <i>" + user.getNickname() + "</i>!");
out.println("[<a href=\""
+ userService.createLogoutURL(req.getRequestURI())
+ "\">sign out</a>]");
} else {
out.println("Hello world! Sign in at: ");
for (String providerName : openIdProviders.keySet()) {
String providerUrl = openIdProviders.get(providerName);
String loginUrl = userService.createLoginURL(req
.getRequestURI(), null, providerUrl, attributes);
out.println("[" + providerName + "] ");
}
}
}
}
How can I setup this authentification module? Where should I put this code because there is no "main.java" file?
Thank you very much,
Regards
This is in progress to be implemented for GWT 2.1/Roo 1.1.0. See this for more details https://jira.springsource.org/browse/ROO-1003
If you can't wait, check the Spring Security in Google App Engine article, at http://blog.springsource.com/2010/08/02/spring-security-in-google-app-engine/
That approach is not supported by Roo though (so once you change the generated code, it will be harder, but still possible, to continue using Roo)