I'm trying my first exercise on Cucumber with Java. Getting error NullPointer and com.sun.proxy.$Proxy16 while executing.
Tried upgrading, downgrading various dependencies.
package com.cucu.runner;
import org.junit.runner.RunWith;
//import cucumber.api.CucumberOptions;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
#RunWith(Cucumber.class)
#CucumberOptions
(
features= {".//src/main/java/com/cucu/feature/"},
glue="com.cucu.stepdef",
dryRun=false,
monochrome=true,
plugin= {"pretty","html:test-output"}
)
public class TestRunner_Cucumber {
}
Feature: LoginPage
Scenario: Successful Login with Valid Credentials
Given User launch the URL
When Page title should be "Welcome, please sign in!"
When User enters valid Username "admin#yourstore.com" and valid Password "admin"
When User clicks on LogIn button
Then User lands on the homepage and verifies the text
package com.cucu.stepdef;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import com.cucu.configprop.TestBase;
import com.cucu.pages.LoginPage;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDefinitions extends TestBase{
LoginPage loginPage = new LoginPage(driver);
#Before
public static void Start()
{
initialization();
}
#Given("User launch the URL")
public void user_launch_the_URL() {
launchURL();
}
#When("Page title should be \"([^\"]*)\"")
public void Page_title_should_be(String Title) {
String ActTitle = loginPage.titleValidation();
System.out.println(ActTitle);
Assert.assertSame(Title, ActTitle);
}
#When("User enters valid Username {string} and valid Password {string}")
public void user_enters_valid_Username_and_valid_Password(String username, String password) {
loginPage.enterEmail(username);
loginPage.enterPassword(password);
}
#When("User clicks on LogIn button")
public void user_clicks_on_LogIn_button() {
loginPage.clickLogIn();
}
#Then("User lands on the homepage and verifies the text")
public void user_lands_on_the_homepage_and_verifies_the_text() {
String DisplayText = loginPage.HeaderValidation();
Assert.assertSame("Incorrect Text", "Dashboard", DisplayText);
}
}
package com.cucu.configprop;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.cucu.pages.CreateOrdersPage;
import com.cucu.pages.CreateUsersPage;
import com.cucu.pages.HomePage;
import com.cucu.pages.LoginPage;
public class TestBase {
public static WebDriver driver;
public static LoginPage loginPage;
public static HomePage homePage;
public static CreateUsersPage createUsersPage;
public static CreateOrdersPage createOrdersPage;
public static WebDriverWait waitTime;
public static Properties prop;
public TestBase()
{
try {
prop = new Properties();
FileInputStream inp = new FileInputStream("F:\\Azar\\Cucumber_Practice\\"
+ "src\\main\\java\\com\\cucu\\configprop\\config.properties");
prop.load(inp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void initialization(){
String browserName = prop.getProperty("browser");
if(browserName.equals("chrome")){
System.setProperty("webdriver.chrome.driver","F:\\Installation\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
}
}
public static void launchURL()
{
driver.get(prop.getProperty("url"));
}
public static void waitDriver()
{
waitTime = new WebDriverWait(driver, 2000);
}
}
When Page title should be "Welcome, please sign in!" # StepDefinitions.Page_title_should_be(String)
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy16.getText(Unknown Source)
at com.cucu.pages.LoginPage.titleValidation(LoginPage.java:39)
at com.cucu.stepdef.StepDefinitions.Page_title_should_be(StepDefinitions.java:31)
Related
i tried integrating google signing in my app, I've done all I am supposes to do but when i run it on andoid device it telling me failed, please kindly help
this is my main Activity
package com.example.todo;
import static android.content.ContentValues.TAG;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.identity.BeginSignInRequest;
import com.google.android.gms.auth.api.identity.SignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.GoogleAuthProvider;
public class MainActivity extends AppCompatActivity {
private TextView todo;
private ImageView googleBtn;
GoogleSignInOptions gso;
GoogleSignInClient gsc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
todo = findViewById(R.id.todo);
googleBtn = findViewById(R.id.googleBtn);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
gsc = GoogleSignIn.getClient(this,gso);
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct != null){
navitgateToSecondActivity();
}
googleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
}
private void signIn() {
Intent signInIntent = gsc.getSignInIntent();
startActivityForResult(signInIntent,1000);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000){
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
task.getResult(ApiException.class);
navitgateToSecondActivity();
} catch (ApiException e) {
Toast.makeText(this, "Google Auth failed", Toast.LENGTH_SHORT).show();
}
}
}
}
void navitgateToSecondActivity(){
finish();
Intent intent = new Intent(this,secondActivity.class);
startActivity(intent);
}
}
this is the second activity
package com.example.todo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.navigation.NavigationView;
public class secondActivity extends AppCompatActivity {
private Button signOut;
private DrawerLayout drawer;
private NavigationView navigationView;
private MaterialToolbar toolbar;
GoogleSignInOptions gso;
GoogleSignInClient gsc;
private TextView profileName;
ImageView profilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
gsc = GoogleSignIn.getClient(this,gso);
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);
if (acct!=null){
String personName = acct.getDisplayName();
String personEmail = acct.getEmail();
Uri personPhoto = acct.getPhotoUrl();
profileName.setText(personName);
profilePic.setImageIcon(Icon.createWithContentUri(personPhoto));
}
initViews();
setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,R.string.drawer_open,R.string.drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logout();
}
});
}
void initViews(){
drawer = findViewById(R.id.drawer);
navigationView = findViewById(R.id.navigationView);
toolbar = findViewById(R.id.toolbar);
signOut = findViewById(R.id.signOut);
}
void logout(){
gsc.signOut().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
finish();
startActivity(new Intent(secondActivity.this,
MainActivity.class));
}
});
}
}
i tried integrating google signing in my app, I've done all I am supposes to do but when i run it on andoid device it telling me failed, please kindly help, i tried all that expecting to get a sign in but it keeps telling me failed
I'am Ropi, i have an issue with my spring boot project test.
The issue is :
UnknownClassName.initializationError : NoClassDefFound UnknownClassName;
when i run the project it with skiped test proccess, it run well . and then i run the test it also run well..
but after i edit the test ( for example : i only add space on my test code), it give me an error.
and then when i edited my working code ( for example : i only add space on my coding work ), it give me illegal error.
My testing Code :
import com.emerio.rnd.otp.service.OtpService;
import org.hamcrest.core.IsNot;
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.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import static org.hamcrest.Matchers.*;
#RunWith(SpringRunner.class)
// #SpringBootTest
#WebFluxTest
public class OtpApplicationTests {
private Integer OTP1;
private Integer OTP2;
#Autowired
private WebTestClient webTestClient;
private OtpService otpService = new OtpService();
#Before
public void setup() throws Exception {
OTP1 = otpService.generateOTP("admin");
OTP2 = otpService.generateOTP("admin1");
}
// #WebFluxTest(OtpController.class)
#Test
public void generateOTPSuccess() throws Exception
{
webTestClient.get().uri("/generateotp/admin")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.data.otp").isNotEmpty();
}
#Test
public void generateOTPUsernameNotExist() throws Exception
{
webTestClient.get().uri("/generateotp/null")
.exchange()
.expectStatus().isBadRequest();
}
// #Test
// public void generateNewOTP() throws Exception
// {
// webTestClient.get().uri("/generateotp/admin1")
// .exchange()
// .expectStatus().isOk()
// .expectBody()
// .jsonPath("$.[otp != "+OTP2+"]");
// }
#Test
public void validateOTPSuccess() throws Exception
{
webTestClient.get().uri("/validateotp/admin/"+OTP1.toString())
.exchange()
.expectStatus().isOk();
}
#Test
public void validateOTPfailed() throws Exception
{
webTestClient.get().uri("/validateotp/admin/981981")
.exchange()
.expectStatus().isBadRequest();
}
#Test
public void validateOTPWithChar() throws Exception
{
webTestClient.get().uri("/validateotp/admin/AS1213")
.exchange()
.expectStatus().isBadRequest();
}
#Test
public void validateOTPTimeOut() throws Exception
{
// Thread.sleep(300010);
webTestClient.get().uri("/validateotp/admin/981981")
.exchange()
.expectStatus().isBadRequest();
}
My Controller Working code
My Controller :
import com.emerio.rnd.otp.response.Response;
import com.emerio.rnd.otp.service.OtpService;
import com.google.gson.Gson;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
#RestController
public class OtpController
{
private OtpService otpService = new OtpService();
private Response response = new Response();
#RequestMapping(method=RequestMethod.GET , value="/generateotp/{username}", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
public Mono<Object> generateOTP (#PathVariable String username)
{
try
{
if (username.equals("null"))
{
return Mono.just(new Throwable("error"));
} else
{
int otp = otpService.generateOTP(username);
JSONObject jObj = new JSONObject();
jObj.put("otp", otp);
return Mono.just(response.loaded(new Gson().fromJson(jObj.toString(), Object.class)));
}
} catch (Exception e)
{
return null;
}
}
#RequestMapping(method=RequestMethod.GET , value="/validateotp/{username}/{otp}", produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
public Mono<Response> validateOTP (#PathVariable String username, #PathVariable String otp)
{
try
{
Integer otpCache = otpService.getOTP(username);
if (!otpCache.toString().equals(otp))
{
System.out.println("cache awal : " + otpCache);
System.out.println("cache : " + otp);
return Mono.just(response.loaded("otp not valid"));
} else
{
otpService.clearOTP(username);
return Mono.just(response.loaded("otp valid"));
}
} catch (Exception e)
{
return null;
}
}
My OTP Service :
package com.emerio.rnd.otp.service;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.stereotype.Service;
#Service
public class OtpService
{
private static final Integer EXPIRE_MINS = 5;
private LoadingCache<String, Integer> otpCache;
public OtpService()
{
super();
otpCache = CacheBuilder.newBuilder()
.expireAfterWrite(EXPIRE_MINS, TimeUnit.MINUTES).build(new CacheLoader<String,Integer>()
{
public Integer load (String key)
{
return 0;
}
});
}
public int generateOTP (String key)
{
Random random = new Random();
int otp = 100000 + random.nextInt(900000);
otpCache.put(key, otp);
return otp;
}
public int getOTP (String key)
{
try
{
return otpCache.get(key);
} catch (Exception e)
{
return 0;
}
}
public void clearOTP (String key)
{
otpCache.invalidate(key);
}
}
I am unable to establish an Atmosphere Broadcaster per user session for an Atmosphere resource. All I can gather from the documentation is how to build "chat" applications that broadcast the same message to every user.
Is it possible to have the Atmosphere framework establish a channel per user session or do I have to do something and handle these connections myself with an in-memory map?
This is the resource I want:
/websockets/notifications
I want user's A and B to connect to this channel from different browsers and then have the ability to stream them messages independently. I should be able to use their session ID's to have atmosphere understand which person to send the response to.
Does Atmosphere support this?
Relevant POM.xml
<spring-boot-starter-web.version>1.3.3.RELEASE</spring-boot-starter-web.version>
<atmosphere-runtime.version>2.4.4</atmosphere-runtime.version>
<atmosphere-javascript.version>2.3.0</atmosphere-javascript.version>
Atmosphere Configuration
package com.hello;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.atmosphere.cache.UUIDBroadcasterCache;
import org.atmosphere.cpr.ApplicationConfig;
import org.atmosphere.cpr.AtmosphereFramework;
import org.atmosphere.cpr.AtmosphereServlet;
import org.atmosphere.cpr.MetaBroadcaster;
import org.springframework.boot.context.embedded.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class AtmosphereConfiguration implements ServletContextInitializer {
#Bean
public AtmosphereServlet atmosphereServlet() {
return new AtmosphereServlet();
}
#Bean
public AtmosphereFramework atmosphereFramework() {
return atmosphereServlet().framework();
}
#Bean
public MetaBroadcaster metaBroadcaster() {
AtmosphereFramework framework = atmosphereFramework();
return framework.metaBroadcaster();
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
configureAthmosphere(atmosphereServlet(), servletContext);
}
private void configureAthmosphere(AtmosphereServlet servlet, ServletContext servletContext) {
ServletRegistration.Dynamic atmosphereServlet = servletContext.addServlet("atmosphereServlet", servlet);
atmosphereServlet.setInitParameter(ApplicationConfig.ANNOTATION_PACKAGE, "com.hello");
atmosphereServlet.setInitParameter(ApplicationConfig.BROADCASTER_CACHE, UUIDBroadcasterCache.class.getName());
atmosphereServlet.setInitParameter(ApplicationConfig.BROADCASTER_SHARABLE_THREAD_POOLS, "true");
atmosphereServlet.setInitParameter(ApplicationConfig.BROADCASTER_MESSAGE_PROCESSING_THREADPOOL_MAXSIZE, "10");
atmosphereServlet.setInitParameter(ApplicationConfig.BROADCASTER_ASYNC_WRITE_THREADPOOL_MAXSIZE, "10");
servletContext.addListener(new org.atmosphere.cpr.SessionSupport());
atmosphereServlet.addMapping("/websocket/*");
atmosphereServlet.setLoadOnStartup(0);
atmosphereServlet.setAsyncSupported(true);
}
}
Atmosphere Resource
package com.hello;
import java.nio.charset.StandardCharsets;
import org.atmosphere.config.service.Get;
import org.atmosphere.config.service.Disconnect;
import org.atmosphere.config.service.ManagedService;
import org.atmosphere.config.service.Ready;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#ManagedService(path = NotificationAtmosphereResource.PATH)
public class NotificationAtmosphereResource {
public static final String PATH = "/websocket/notifications";
private Logger logger = LoggerFactory.getLogger(NotificationAtmosphereResource.class);
#Get
public void init(AtmosphereResource resource){
resource.getResponse().setCharacterEncoding(StandardCharsets.UTF_8.name());
}
#Ready
public void onReady(final AtmosphereResource resource) {
logger.info("Connected {}", resource.uuid());
}
#Disconnect
public void onDisconnect(AtmosphereResourceEvent event) {
logger.info("Client {} disconnected [{}]", event.getResource().uuid(),
(event.isCancelled() ? "cancelled" : "closed"));
}
}
Service from which I emit Messages
package com.hello;
import org.atmosphere.cpr.MetaBroadcaster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class NotificationEmitterBean implements NotificationEmitter {
private Logger logger = LoggerFactory.getLogger(NotificationEmitterBean.class);
#Autowired
private MetaBroadcaster metaBroadcaster;
#Autowired
private NotificationService notificationService;
#Autowired
private JsonMapper jsonMapper;
#Override
public void emitNotification(String sessionId, String msg) {
// This will broadcast to all users on /websocket/notifications
// How can I use sessionId to broadcast to the respective browser?
metaBroadcaster.broadcastTo(NotificationAtmosphereResource.PATH,
jsonMapper.toJson(msg));
}
}
}
The only way I was able to get this working was to create my own session based broadcaster. I used ExcludeSessionBroadcaster written by Jeanfrancois Arcand as my baseline.
IncludeSessionBroadcaster.java
package com.hello;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Future;
import org.atmosphere.cpr.AtmosphereConfig;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.Broadcaster;
import org.atmosphere.cpr.BroadcasterFuture;
import org.atmosphere.cpr.DefaultBroadcaster;
import org.atmosphere.cpr.Deliver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An implementation of {#link DefaultBroadcaster} that include one or more {#link AtmosphereResource}
*
* Based on ExcludeSessionBroadcaster written by Jeanfrancois Arcand
*
* #author Steven Zgaljic
*/
public class IncludeSessionBroadcaster extends DefaultBroadcaster {
private static final Logger logger = LoggerFactory.getLogger(IncludeSessionBroadcaster.class);
public IncludeSessionBroadcaster(){}
public Broadcaster initialize(String id, AtmosphereConfig config) {
return super.initialize(id, config);
}
/**
* the AtmosphereResource r will be include for this broadcast
*
* #param msg
* #param r
* #return
*/
#Override
public Future<Object> broadcast(Object msg, AtmosphereResource r) {
if (destroyed.get()) {
throw new IllegalStateException("This Broadcaster has been destroyed and cannot be used");
}
Set<AtmosphereResource> sub = new HashSet<AtmosphereResource>();
sub.removeAll(resources);
sub.add(r);
start();
Object newMsg = filter(msg);
if (newMsg == null) {
return null;
}
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(newMsg, sub.size());
dispatchMessages(new Deliver(newMsg, sub, f, msg));
return f;
}
/**
* the AtmosphereResources subset will be include for this broadcast
*
* #param msg
* #param subset
* #return
*/
#Override
public Future<Object> broadcast(Object msg, Set<AtmosphereResource> subset) {
if (destroyed.get()) {
return futureDone(msg);
}
subset.retainAll(resources);
start();
Object newMsg = filter(msg);
if (newMsg == null) {
return futureDone(msg);
}
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(newMsg, subset.size());
dispatchMessages(new Deliver(newMsg, subset, f, msg));
return f;
}
/**
* session will be include for this broadcast
*
* #param msg
* #param s
* #return
*/
public Future<Object> broadcast(Object msg, String sessionId) {
if (destroyed.get()) {
return futureDone(msg);
}
Set<AtmosphereResource> subset = new HashSet<AtmosphereResource>();
for (AtmosphereResource r : resources) {
if (!r.getAtmosphereResourceEvent().isCancelled() &&
sessionId.equals(r.getRequest().getSession().getId())) {
subset.add(r);
break;
}
}
start();
Object newMsg = filter(msg);
if (newMsg == null) {
return futureDone(msg);
}
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(newMsg, subset.size());
dispatchMessages(new Deliver(newMsg, subset, f, msg));
return f;
}
}
Then I assigned this broadcaster to the Atmosphere resource.
NotificationAtmosphereResource.java
package com.hello;
import java.nio.charset.StandardCharsets;
import org.atmosphere.config.service.Get;
import org.atmosphere.config.service.Disconnect;
import org.atmosphere.config.service.ManagedService;
import org.atmosphere.config.service.Ready;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#ManagedService(path = NotificationAtmosphereResource.PATH,
broadcaster=IncludeSessionBroadcaster.class)
public class NotificationAtmosphereResource {
public static final String PATH = "/websocket/notifications";
private Logger logger = LoggerFactory.getLogger(NotificationAtmosphereResource.class);
#Get
public void init(AtmosphereResource resource){
resource.getResponse().setCharacterEncoding(StandardCharsets.UTF_8.name());
}
#Ready
public void onReady(final AtmosphereResource resource) {
logger.info("Connected {}", resource.uuid());
}
#Disconnect
public void onDisconnect(AtmosphereResourceEvent event) {
logger.info("Client {} disconnected [{}]", event.getResource().uuid(),
(event.isCancelled() ? "cancelled" : "closed"));
}
}
Then I could send message to only the browser (sessionId) that I want.
NotificationEmitterBean.java
package com.hello;
import org.atmosphere.cpr.MetaBroadcaster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class NotificationEmitterBean implements NotificationEmitter {
private Logger logger = LoggerFactory.getLogger(NotificationEmitterBean.class);
#Autowired
private BroadcasterFactory factory;
#Override
public void emitNotification(String sessionId, String msg) {
((IncludeSessionBroadcaster)factory.lookup(NotificationAtmosphereResource.PATH)).broadcast(msg, sessionId);
}
}
}
I am new to android and i am getting this error.Maths1 code:
package com.materialdesign.geniusmathsandphysics;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class Maths1 extends Activity{
MainActivity async;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maths1);
async=new MainActivity();
Button m15,d15;
m15 = (Button) findViewById(R.id.but_m1may15);
d15 = (Button) findViewById(R.id.but_m1dec15);
m15.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File pdf = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/" + "M1_May_15.pdf");
if (pdf.exists()) {
//file= new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/pdf/Area.pdf");
Intent i=new Intent(Maths1.this,PdfViewer.class);
i.putExtra("FileName",pdf);
startActivity(i);
} else {
if (isNetworkConnected() == true) {
Toast.makeText(Maths1.this, "Starting Download....please wait.", Toast.LENGTH_LONG).show();
async.new Connect().execute("166.62.10.29", "M1_May_15.pdf");
} else {
Toast.makeText(Maths1.this, "No internet connection \n Please try again", Toast.LENGTH_SHORT).show();
}
}
}
});
d15.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File pdf = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/" + "M1_Dec_15.pdf");
if (pdf.exists()) {
ViewPDF();
} else {
if (isNetworkConnected() == true) {
async.new Connect().execute("166.62.10.29", "M1_Dec_15.pdf");
Toast.makeText(Maths1.this, "Starting Download....please wait.", Toast.LENGTH_LONG).show();
ViewPDF();
} else {
Toast.makeText(Maths1.this, "No internet connection \n Please try again", Toast.LENGTH_SHORT).show();
}
}
}
});
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
public void ViewPDF()
{
Intent i=new Intent(Maths1.this,PdfViewer.class);
SavePreferences("name", "M1_Dec_15.pdf");
startActivity(i);
}
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
}
pdf viewer code:
package com.materialdesign.geniusmathsandphysics;
import android.content.SharedPreferences;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.File;
public class PdfViewer extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdfviewer);
com.joanzapata.pdfview.PDFView Pdf = (com.joanzapata.pdfview.PDFView) findViewById(R.id.pdfview1);
//String filepath=getIntent().getExtras().getString("name");
String file=showPreferences("name");
File fd = new File(file);
//Log.i("hhhhdsdada",filepath);
Pdf.fromFile(fd).defaultPage(1).swipeVertical(true).load();
}
private String showPreferences(String key){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String savedPref = sharedPreferences.getString(key, "");
File files= new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/GeniusPhysicsandMaths/"+savedPref);
String file=files.toString();
return file;
}
}
this is my logcat:
FATAL EXCEPTION: AsyncTask #3 Process: com.materialdesign.geniusmathsandphysics, PID: 18871
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: PDF file is corrupted
at org.vudroid.pdfdroid.codec.PdfDocument.open(Native Method)
at org.vudroid.pdfdroid.codec.PdfDocument.openDocument(PdfDocument.java:28)
at org.vudroid.pdfdroid.codec.PdfContext.openDocument(PdfContext.java:18)
at org.vudroid.core.DecodeServiceBase.open(DecodeServiceBase.java:59)
at com.joanzapata.pdfview.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:52)
at com.joanzapata.pdfview.DecodingAsyncTask.doInBackground(DecodingAsyncTask.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
i am using joanzapata library to view pdf files.for that i am trenter code hereying to pass that file name from maths 1 class on button click listner. The library takes file as input so i had to convert string to file previously using intent i was getting null pointer exception but now with shared preferences i am getting this error. Please help me to solve it. Thanks in advance.
I am trying to understand Stateful Session bean life cycle.I am particularly interested when activation and passivation life cycle callback invoked.I created a demo to understand this scenario. Here is My code :
My Remote interface is :
package com.orbit.stateful;
import javax.ejb.Remote;
import java.util.List;
#Remote
public interface ShoppingCart
{
public void addItem(String itemName);
public void removeItem(String item);
public List<String> getAllItems();
public void finishShopping();
}
My Stateful session bean class is as follow:
package com.orbit.stateful;
import javax.ejb.Stateful;
import javax.ejb.Remove;
import javax.ejb.PrePassivate;
import javax.ejb.PostActivate;
import javax.ejb.StatefulTimeout;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
//import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.ArrayList;
#Stateful
//#StatefulTimeout(value=5L,unit=TimeUnit.MINUTES)
public class ShoppingCartBean implements ShoppingCart
{
private List<String> itemList;
public ShoppingCartBean(){
System.out.println("Stateful SessionBean Constructor Called");
}
#PostConstruct
public void intialize(){
System.out.println("Initializing shopping Cart");
itemList=new ArrayList<String>();
}
public void addItem(String itemName){
itemList.add(itemName);
}
public void removeItem(String item){
itemList.remove(item);
}
public List<String> getAllItems(){
return itemList;
}
#Remove
public void finishShopping(){
System.out.println("I am finished with Shopping");
}
#PreDestroy
public void tidyUp(){
System.out.println("Remove Shopping Bean");
}
#PrePassivate
public void logPassivation(){
System.out.println("Passivating Now");
}
#PostActivate
public void logActivation(){
System.out.println("Activating Now");
}
}
And standalone client for this bean is :
package com.orbit.stateful;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Properties;
import java.util.List;
public class ShoppingCartClient
{
public static void main(String[] args) throws Exception
{
Properties props = new Properties();
props.setProperty("java.naming.factory.initial",
"com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs",
"com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state",
"com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
Context ctx=new InitialContext(props);
ShoppingCart sc=(ShoppingCart)ctx.lookup("com.orbit.stateful.ShoppingCart");
sc.addItem("J2SE");
//Thread.sleep(17000);
sc.addItem("J2EE");
sc.addItem("JDBC");
List<String> books=sc.getAllItems();
for (String str: books )
{
System.out.println("Books is : "+ str);
}
//sc.finishShopping();
}
}
Now I have set Cache Idle Timeout=20 in GlassFish 3.1.2
But still My stateful session bean is not passivating after 20 seconds. am I doing something wrong or something is not happening correctly in Glashfish ?Help me to understand this.
Thanks in Advance