UI engine accessed without holding the event lock - blackberry

I've created a simple app that calls a url inside a browserfield whenever a phonecall is initiated or received, but I keep on getting the exception:
UI engine accessed without holding the event lock.
I read somewhere that I have to make use of Global Events, but I don't know how to do that. I have been struggling a long time on this and would appreciate any help on getting the urls to load when a call is iniated or dialled without getting an error.
My code:
public class BackgroundApp extends MainScreen implements PhoneListener {
BrowserField bf = new BrowserField();
public BackgroundApp(){
super();
Phone.addPhoneListener(this); //Phonelistener added to code
add(bf);
}
public void callIncoming(int callId) { //Method to listen for an incoming call and get the number
try {
bf.requestContent("http://www.yahoo.com/");
} catch (Exception me) {
me.printStackTrace();
}
}
public void callAdded(int arg0) {}
public void callAnswered(int callId) {}
public void callConferenceCallEstablished(int callId) {}
public void callConnected(int callId) {}
public void callDirectConnectConnected(int callId) {}
public void callDirectConnectDisconnected(int callId) {}
public void callDisconnected(int callId) {}
public void callEndedByUser(int callId) {}
public void callFailed(int callId, int reason) {}
public void callHeld(int callId) {}
public void callInitiated(int callid) {
try {
bf.requestContent("http://www.google.com/");
} catch (Exception me) {
me.printStackTrace();
}
}
public void callRemoved(int callId) {}
public void callResumed(int callId) {} /
public void callWaiting(int callid) {}
public void conferenceCallDisconnected(int callId) {}
public boolean onClose() {
System.exit(0);
return true;
}
}

Replace this
bf.requestContent("something");
with
synchronized (UiApplication.getEventLock())
{
bf.requestContent("http://www.yahoo.com/");
}
or use like this:
synchronized (UiApplication.getEventLock())
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
bf.requestContent("http://www.yahoo.com/");
}
});
}

Related

mvc 6 ef7 Customer table object is null in AppDbContext - there is data in the database

When I enter URL localhost:xxx/api/Customers, it showed "is null". I looked at the variable in debugger mode, it show the table customers object is null;
Remember there is data in the table. Any idea?
Customer class
public class Customer
{
public string Id { get; set; }
public string lName { get; set; }
}
appsettings.json
{
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=.\\sqlexpress;Database=EF7;Trusted_Connection=True;"
}
}
AppDbContext
public class AppDbContext : DbContext
{
public DbSet<Customer> Customers;
protected override void OnModelCreating(ModelBuilder Builder)
{
Builder.Entity<Customer>().HasKey(c => c.Id);
base.OnModelCreating(Builder);
}
}
CustomersController
[Route("api/[controller]")]
public class CustomersController : Controller
{
AppDbContext _ctx { get; set; }
public CustomersController([FromServices] AppDbContext ctx)
{
_ctx = ctx;
}
// GET: api/values
[HttpGet]
public JsonResult Get()
{
if(_ctx.Customers!=null)
return Json(_ctx.Customers.ToList());
else {
return Json("is null");
}
}
}
Startup.cs
public class Startup
{
IConfigurationRoot Configuration;
public Startup(IHostingEnvironment env)
{
var Builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = Builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddEntityFramework().AddSqlServer().AddDbContext<AppDbContext>(o=>o.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.UseMvc();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
Never mind, my Dbset is a field instead of property. So I just changed to DbSet Customer {get;set}

Not able to populate the User object when using Spring OAuth2 Jdbc token store

I updated Roy Clarkson's Spring REST service (https://github.com/royclarkson/spring-rest-service-oauth) with a Jdbc-based token store. The original implementation uses an in-memory token store. I was able to see the user details in the User object. On the other hand, after switching to Jdbc-based token store, all the fields in the User object were empty. It appears somehow Spring security was not able to associate the access token with the user under which I obtained the token when I was using Jdbc-based token store.
The in-memory token store implementation:
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends
AuthorizationServerConfigurerAdapter {
#Autowired
private DataSource dataSource;
private TokenStore tokenStore = new InMemoryTokenStore();
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Autowired
private CustomUserDetailsService userDetailsService;
#Autowired
private ClientDetailsService clientDetailsService;
#Bean
public ClientDetailsService clientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
// #formatter:off
endpoints
.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
// #formatter:on
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.withClientDetails(clientDetailsService);
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(this.tokenStore);
return tokenServices;
}
}
The REST endpoint:
#RequestMapping("/greeting")
public Greeting greeting(#AuthenticationPrincipal User user) {
return new Greeting(counter.incrementAndGet(), String.format(template, user.getName()));
}
user.getName() returns the name of the user under which I obtained the access token.
The jdbc token store implementation:
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends
AuthorizationServerConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Autowired
private TokenStore tokenStore;
#Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Autowired
private CustomUserDetailsService userDetailsService;
#Autowired
private ClientDetailsService clientDetailsService;
#Bean
public ClientDetailsService clientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
// #formatter:off
endpoints
.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
// #formatter:on
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.withClientDetails(clientDetailsService);
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(this.tokenStore);
return tokenServices;
}
}
The REST endpoint:
#RequestMapping("/greeting")
public Greeting greeting(#AuthenticationPrincipal User user) {
return new Greeting(counter.incrementAndGet(), String.format(template, user.getName()));
}
user.getName() returns null.
CustomUserDetailsService
#Service
public class CustomUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
#Autowired
public CustomUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByLogin(username);
if (user == null) {
throw new UsernameNotFoundException(String.format("User %s does not exist!", username));
}
return new UserRepositoryUserDetails(user);
}
private final static class UserRepositoryUserDetails extends User implements UserDetails {
private static final long serialVersionUID = 1L;
private UserRepositoryUserDetails(User user) {
super(user);
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles();
}
#Override
public String getUsername() {
return getLogin();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
}
User
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#NotEmpty
private String name;
#NotEmpty
#Column(unique = true, nullable = false)
private String login;
#NotEmpty
private String password;
#NotEmpty
private String privilege;
#JsonIgnore
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "user_role", joinColumns = { #JoinColumn(name = "user_id") }, inverseJoinColumns = { #JoinColumn(name = "role_id") })
private Set<Role> roles = new HashSet<Role>();
public User() {
}
public User(User user) {
super();
this.id = user.getId();
this.name = user.getName();
this.login = user.getLogin();
this.password = user.getPassword();
this.roles = user.getRoles();
this.privilege = user.getPrivilege();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPrivilege() {return privilege; }
public void setPrivilege(String privilege) {this.privilege = privilege; }
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
The issue is that the "UserRepositoryUserDetails" you are creating is not serializable.
UserRepositoryUserDetails is implementing "UserDetails" which is Serializable but the class it is extending "User" is not Serializable.
You must be getting a warning also from comiler to add a serialId.
Solution
Make your UserRepositoryUserDetails as serializable.
After making User class serializable everything worked as expected.

Concurrent requests when using Ninject and DbContext

Here is my project responsible for data:
public interface IRepository<T> where T : class
{
IQueryable<T> All();
T GetById(int id);
void Add(T entity);
void Update(T entity);
....
}
EF implement IRepository
public class GenericRepository<T> : IRepository<T> where T : class
{
public GenericRepository() : this(new ApplicationDbContext())
{
}
public GenericRepository(DbContext context)
{
if (context == null)
{
throw new ArgumentException("An instance of DbContext is required to use this repository.", "context");
}
this.Context = context;
this.DbSet = this.Context.Set<T>();
}
protected IDbSet<T> DbSet { get; set; }
protected DbContext Context { get; set; }
public virtual IQueryable<T> All()
{
return this.DbSet.AsQueryable();
}
public virtual T GetById(int id)
{
return this.DbSet.Find(id);
}........
I use unit of work pattern
public interface IUowData : IDisposable
{
IRepository<House> Houses { get; }
IRepository<Floor> Floors { get; }
...
int SaveChanges();
}
And this is his implementation
public class UowData:IUowData
{
private readonly DbContext context;
private readonly Dictionary<Type, object> repositories = new Dictionary<Type, object>();
public UowData(){}
public UowData(DbContext context)
{
this.context = context;
}
private IRepository<T> GetRepository<T>() where T : class
{
if (!this.repositories.ContainsKey(typeof(T)))
{
var type = typeof(GenericRepository<T>);
this.repositories.Add(typeof(T), Activator.CreateInstance(type, this.context));
}
return (IRepository<T>)this.repositories[typeof(T)];
}
public int SaveChanges()
{
return this.context.SaveChanges();
}
public void Dispose()
{
this.context.Dispose();
}
The second project is of type Web API through which I try to access data from database:
public class ArduinoController : ApiController
{
private IEmailSender sender;
private IUowData data;
public ArduinoController(IEmailSender sender, IUowData data)
{
this.sender = sender;
this.data = data;
}
[HttpPost]
[ActionName("PostAlarm")]
public void PostAlarm(dynamic sensorJson)
{
var alartModel = this.data.Sensors.All()
.....
When I try to use Ninject dependancy resolve i get exception:
"The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.".
Everything works fine if I fetch one page at a time. I am using a simple tool 'XENU' to fetch multiple pages simultaneously. This is when I get errors with DBContext by fetching multiple pages at a time.
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
EmailSettings emailSettings = new EmailSettings
{
ServerName = Settings.Default.EmailServerName,
...
};
kernel.Bind<IEmailSender>().To<EmailSender>().WithConstructorArgument("settings", emailSettings);
kernel.Bind<IUowData>().To<UowData>().InRequestScope().WithConstructorArgument("context",new ApplicationDbContext());
}
}
.WithConstructorArgument("context",new ApplicationDbContext());
results in one DB Context for the whole application. Remove that and add a binding instead.
.Bind<DbContext>().To<ApplicationDbContext>().InRequestScope();

Ninject Property Injection not working on ActionFilters

I have an interface and a class that implements that interface
public interface ISessionVariables
{
bool IsSessionTokenValidated { get; set; }
}
public class HttpContextSessionVariablesAdapter : ISessionVariables
{
private T Get<T>(string key)
{
return (T)HttpContext.Current.Session[key];
}
private void Set(string key, object value)
{
HttpContext.Current.Session[key] = value;
}
public bool IsSessionTokenValidated
{
get { return Get<bool>("IsSessionTokenValidated"); }
set { Set("IsSessionTokenValidated", value); }
}
}
I bind the interface to implementation using Ninject:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ISessionVariables>().To<HttpContextSessionVariablesAdapter>();
}
I have an ActionFilter
public class ValidateSessionTokenAttribute : ActionFilterAttribute
{
[Inject]
public ISessionVariables SessionVariables { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (SessionVariables.IsSessionTokenValidated == false)
{
throw new HttpException((int)HttpStatusCode.Unauthorized, "User session has expired");
}
base.OnActionExecuting(filterContext);
}
}
Strange bug:
If i add the ValidateSessionTokenAttribute to an ActionResult, SessionVariables property gets populated.
[ValidateSessionToken]
public ActionResult Index()
{
}
If i bind the same filter to all ActionResults, (in FilterConfig), the SessionVariables property is always null.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ValidateSessionTokenAttribute());
}
}
What i am doing wrong?

Blackberry - manage conference call from application?

How to create conference call from application?
We will have to:
start call
hold call
start new call
join conference
...
To start call see api from Blackberry - make a call from native address book
There is no api to hold and join but we can use Blackberry - run menu item from dialer Phone App technique
To bring app screen back foreground we can use code from Blackberry - Create an application which will lock another application event
Full code:
class Scr extends MainScreen implements PhoneListener {
private static final String STR_MODULE_NAME = "SOConferenceCall";
EditField mPhoneNumber = new EditField("phone number: ", "12345");
boolean mConnected = false;
Vector mPhoneCalls = new Vector();
public Scr() {
Phone.addPhoneListener(this);
add(mPhoneNumber);
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
if (isCalling()) {
menu.add(new MenuItem("add to conference", 0, 0) {
public void run() {
holdActiveCall();
makeCall(mPhoneNumber.getText());
}
});
} else {
menu.add(new MenuItem("call", 0, 0) {
public void run() {
makeCall(mPhoneNumber.getText());
}
});
}
}
private void holdActiveCall() {
runMenuItem("Hold");
}
private void joinCalls() {
runMenuItem("Join Conference");
}
private void makeCall(String number) {
PhoneArguments call = new PhoneArguments(PhoneArguments.ARG_CALL,
number);
Invoke.invokeApplication(Invoke.APP_TYPE_PHONE, call);
}
private void runMenuItem(String menuItemText) {
Screen screen = Ui.getUiEngine().getActiveScreen();
Menu menu = screen.getMenu(0);
for (int i = 0, cnt = menu.getSize(); i < cnt; i++)
if (menu.getItem(i).toString().equalsIgnoreCase(menuItemText))
menu.getItem(i).run();
}
protected int switchToForeground() {
int id = -1;
ApplicationManager appMan
= ApplicationManager.getApplicationManager();
ApplicationDescriptor appDes[]
= appMan.getVisibleApplications();
for (int i = 0; i < appDes.length; i++) {
Sreing name = appDes[i].getModuleName();
if (name.equalsIgnoreCase(STR_MODULE_NAME)) {
id = appMan.getProcessId(appDes[i]);
appMan.requestForeground(id);
// give a time to foreground application
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
}
return id;
}
private boolean isCalling() {
return mConnected;
}
public void callAdded(int callId) {
switchToForeground();
}
public void callAnswered(int callId) {
switchToForeground();
}
public void callConferenceCallEstablished(int callId) {
switchToForeground();
}
public void callConnected(int callId) {
if (mPhoneCalls.size() == 0)
mConnected = true;
else
joinCalls();
mPhoneCalls.addElement(Phone.getCall(callId));
switchToForeground();
}
public void callDirectConnectConnected(int callId) {
switchToForeground();
}
public void callDirectConnectDisconnected(int callId) {
switchToForeground();
}
public void callDisconnected(int callId) {
mPhoneCalls.removeElement(Phone.getCall(callId));
if (mPhoneCalls.size() == 0)
mConnected = false;
switchToForeground();
}
public void callEndedByUser(int callId) {
switchToForeground();
}
public void callFailed(int callId, int reason) {
switchToForeground();
}
public void callHeld(int callId) {
switchToForeground();
}
public void callIncoming(int callId) {
switchToForeground();
}
public void callInitiated(int callid) {
switchToForeground();
}
public void callRemoved(int callId) {
switchToForeground();
}
public void callResumed(int callId) {
switchToForeground();
}
public void callWaiting(int callid) {
switchToForeground();
}
public void conferenceCallDisconnected(int callId) {
switchToForeground();
}
}

Resources