As per the Dagger 2 documentation
I am trying to set up a test environment according to Dagger2's documentation
(Just for context, I have successfully done this in Dagger 1.)
The problem, specifically, is that while Dagger2 correctly generates DaggerRoboDaggerComponent (as used in App.java), it does not generate DaggerTestRoboDaggerComponent (as used in MainActivityTest.java). I have checked the directory structure to make sure it's not hiding in some obscure place, and done the requisite clean, rebuild, Invalidate Caches / Restart, etc.
If someone could please let me know the error of my ways, I'd appreciate it. Thanks in advance.
You can clone the project here
Or, browse thru the project files below:
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "xx.robodagger"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.dagger:dagger:2.10'
annotationProcessor "com.google.dagger:dagger-compiler:2.10"
testCompile 'junit:junit:4.12'
testCompile "org.robolectric:robolectric:3.3.1"
}
App.java
package xx.robodagger;
import android.app.Application;
public class App extends Application {
static RoboDaggerComponent roboDaggerComponent;
static RoboDaggerComponent getComponent() {
return roboDaggerComponent;
}
#Override public void onCreate() {
super.onCreate();
roboDaggerComponent = DaggerRoboDaggerComponent.builder()
.roboDaggerModule(new RoboDaggerModule())
.build();
}
}
Foo.java
package xx.robodagger;
class Foo {
#Override public String toString() {
return "foo";
}
}
MainActivity.java
package xx.robodagger;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import javax.inject.Inject;
public class MainActivity extends AppCompatActivity {
#Inject Foo foo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App.getComponent().inject(this);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.textview);
tv.setText(foo.toString());
}
}
RoboDaggerComponent.java
package xx.robodagger;
import javax.inject.Singleton;
import dagger.Component;
#Singleton
#Component(modules={RoboDaggerModule.class})
interface RoboDaggerComponent {
void inject(MainActivity mainActivity);
}
RoboDaggerModule.java
package xx.robodagger;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
#SuppressWarnings("unused")
#Module
class RoboDaggerModule {
#Provides
#Singleton
Foo providesFoo() { return new Foo(); }
}
And now in the test directory,
FakeFoo.java
package xx.robodagger;
class FakeFoo extends Foo {
#Override public String toString() {
return "bar";
}
}
MainActivityTest.java
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import javax.inject.Inject;
#RunWith(RobolectricTestRunner.class)
#Config(constants = BuildConfig.class)
public class MainActivityTest {
TestRoboDaggerComponent testRoboDaggerComponent;
#Inject Foo foo;
#Before
public void setup() {
testRoboDaggerComponent = DaggerTestRoboDaggerComponent.builder()
.testRoboDaggerModule(new TestRoboDaggerModule())
.build();
testRoboDaggerComponent.inject(this);
}
#Test
public void fooBarTest() {
assert(foo.toString().equals("bar"));
}
}
TestRoboDaggerComponent.java
package xx.robodagger;
import javax.inject.Singleton;
import dagger.Component;
#Singleton
#Component(modules={TestRoboDaggerModule.class})
interface TestRoboDaggerComponent {
void inject(MainActivityTest mainActivityTest);
}
TestRoboDaggerModule.java
package xx.robodagger;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
#SuppressWarnings("unused")
#Module
class TestRoboDaggerModule {
#Provides
#Singleton
Foo providesFoo() { return new FakeFoo(); }
}
Delete TestRoboDaggerComponent.java, it's not needed
Modify App.java to setup the component via a protected method
#Override public void onCreate() {
super.onCreate();
setupComponent();
}
protected void setupComponent() {
roboDaggerComponent = DaggerRoboDaggerComponent.builder()
.roboDaggerModule(new RoboDaggerModule())
.build();
}
Modify TestApp.java to extend App, and override the previously mentioned method with the TestModule
public class TestApp extends App {
#Override
protected void setupComponent() {
roboDaggerComponent = DaggerRoboDaggerComponent.builder()
.roboDaggerModule(new TestRoboDaggerModule())
.build();
}
}
And finally, in the actual test, leverage Robolectric's power to specify the Application module
#RunWith(RobolectricTestRunner.class)
#Config(constants = BuildConfig.class,
application = TestApp.class)
public class MainActivityTest {
private MainActivity mainActivity;
#Before
public void setup() {
mainActivity = Robolectric.setupActivity(MainActivity.class);
}
#Test
public void fooBarTest() {
TextView tv = (TextView)mainActivity.findViewById(R.id.textview);
assert(tv.getText().equals("bar"));
}
}
Notice that there isn't any DI in the actual test proper. The injection of MainActivity takes place as expected, and with the overridden module. If you have a dependency that uses #Injects in the constructor, the solution per Dagger's documentation is not to use injection in the test, but to just call the normal constructor with mocked objects. This all makes sense. I still think the originally reported issue is a bug, but whatever.
Related
I've upgraded all my firebase packages today, and I had to upgrade to version 8.0.0-dev.13 for firebase messaging even though it is still in dev due to dependency issues. In Application.Java, I have:
package com.halloglobal.flutterapp.hallo;
import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
import io.flutter.view.FlutterMain;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
#override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
#override
public void registerWith(PluginRegistry registry) {
FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
}
Which has worked fine in the past, but now with this new version, I get this error:
Note: Recompile with -Xlint:deprecation for details.
/Users/hallo/Documents/HalloMonoRepo/hallo/android/app/src/main/java/com/halloglobal/flutterapp/hallo/Application.java:7: error: package io.flutter.plugins.firebasemessaging does not exist
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
^
/Users/hallo/Documents/HalloMonoRepo/hallo/android/app/src/main/java/com/halloglobal/flutterapp/hallo/Application.java:8: error: package io.flutter.plugins.firebasemessaging does not exist
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
How do I need to change my Application.java to work with the new version?
I fixed it by removing the plugin registration completely, the new version handles it internally now.
this worked for me. Maybe will help you.if there is something you don't use, remove it like flutter local notification.
Also you can check this article
https://medium.com/#demmydwirhamadan/working-well-firebase-cloud-messaging-push-notification-in-flutter-tested-on-android-4eb91f45d45
import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
#Override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
#Override
public void registerWith(PluginRegistry registry) {
if (alreadyRegisteredWith(registry)) {
return;
}
FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
FlutterLocalNotificationsPlugin.registerWith(registry.registrarFor("com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin"));
}
private static boolean alreadyRegisteredWith(PluginRegistry registry) {
final String key = Application.class.getCanonicalName();
if (registry.hasPlugin(key)) {
return true;
}
registry.registrarFor(key);
return false;
}
}
Add this in your dependency - pubspec.yaml
firebase_messaging:
im working on my first project
i used FirebaseAuth and firebase realtime database
i followed every step carefully at first everything is alright and my project has connect to the db successfully(two weeks ago) i had even test my db , but after i update my android studio version something went wrong :(
my app keep crash every time i click on the buttons.
i really don't know what is the problem? before everything was alright
"i read articles about the api-key and i checked it there is nothing wrong with it"
here is my register code :
package com.example.lastone;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.santalu.maskedittext.MaskEditText;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.basgeekball.awesomevalidation.ValidationStyle;
import com.basgeekball.awesomevalidation.utility.RegexTemplate;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Register2 extends AppCompatActivity {
MaskEditText license,phone;
private EditText email,pass1,pass2;
private Button but;
AwesomeValidation awesomeValidation;
private FirebaseDatabase rootNode;
//realtime
DatabaseReference reference;
//authinicate
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register2);
//validation
awesomeValidation=new AwesomeValidation(ValidationStyle.BASIC);
updateUI();
//authinication
firebaseAuth= FirebaseAuth.getInstance();
}
private void updateUI() {
license=findViewById(R.id.license);
email=(EditText)findViewById(R.id.email);
phone=findViewById(R.id.phone);
pass1=(EditText)findViewById(R.id.pass1);
pass2=(EditText)findViewById(R.id.pass2);
but=(Button)findViewById(R.id.but);
String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d])(?=.*[~`!##\\$%\\^&\\*\\(\\)\\-_\\+=\\{\\}\\[\\]\\|\\;:\"<>,./\\?]).{8,}";
String Regex = ("[0-9]{10}");
awesomeValidation.addValidation(Register2.this,R.id.license, Regex, R.string.licensee);
awesomeValidation.addValidation(Register2.this,R.id.email,android.util.Patterns.EMAIL_ADDRESS, R.string.emailrr);
awesomeValidation.addValidation(Register2.this,R.id.phone, RegexTemplate.TELEPHONE, R.string.phonen);
awesomeValidation.addValidation(Register2.this,R.id.pass1,regexPassword,R.string.pass11);
awesomeValidation.addValidation(Register2.this,R.id.pass2,R.id.pass1,R.string.pass22);
but.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
signUp();
// send to the database
rootNode= FirebaseDatabase.getInstance();
reference=rootNode.getReference("users");
//get all the values from the textfield
String License =license.getText().toString();
String Phone_number =phone.getText().toString();
String Email =email.getText().toString();
String password =pass1.getText().toString();
UserHelperClass helper=new UserHelperClass(License , Phone_number, Email, password);
reference.child(License).setValue(helper);
//validate
if(awesomeValidation.validate())
{
Toast.makeText(Register2.this, "Data Received Successfully", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(Register2.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
private void signUp() {
firebaseAuth.createUserWithEmailAndPassword(email.getText().toString(), pass1.getText().toString())
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = firebaseAuth.getCurrentUser();
String email=user.getEmail();
String name=user.getDisplayName();
Toast.makeText(Register2.this, "Name : "+name+"\n"+"Email : "+email,
Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Register2.this,Login.class);
startActivity(intent);
} else {
// If sign in fails, display a message to the user.
Toast.makeText(Register2.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
// updateUI(null);
}
// ...
}
});
}
}
login code:
package com.example.lastone;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class Login extends AppCompatActivity
{
private EditText email,pass;
private Button lo;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email=(EditText)findViewById(R.id.email);
pass=(EditText)findViewById(R.id.pass);
lo=(Button)findViewById(R.id.lo);
firebaseAuth= FirebaseAuth.getInstance();
lo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Signin();
}
});
}
private void Signin()
{
firebaseAuth.signInWithEmailAndPassword(email.getText().toString(), pass.getText().toString())
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = firebaseAuth.getCurrentUser();
String email=user.getEmail();
String name=user.getDisplayName();
Toast.makeText(Login.this,"Logged in successuly",
Toast.LENGTH_SHORT).show();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(Login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
// Intent intent=new Intent(Login.this,profile.class);
}
}
});
}
}
error:
2020-04-04 02:25:41.923 7642-7642/com.example.lastone E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.lastone, PID: 7642
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.Preconditions.checkNotEmpty(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(com.google.firebase:firebase-auth##19.3.0:205)
at com.example.lastone.Login.Signin(Login.java:53)
at com.example.lastone.Login.access$000(Login.java:27)
at com.example.lastone.Login$1.onClick(Login.java:46)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
also build gradle :
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.lastone"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.basgeekball:awesome-validation:4.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.firebase:firebase-database:19.2.1'
implementation 'com.google.firebase:firebase-auth:19.3.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.github.santalu:mask-edittext:1.0.2'
}
the deadline is on this week please help :((
Add these dependencies and run your your projet again
implementation 'com.google.firebase:firebase-analytics:17.2.3'
implementation 'com.google.firebase:firebase-core:17.2.3'
I'm trying to test my Spring 5 web controllers with JUnit 5.
The two way to test controller (as mentionned in spring documentation) always give me null pointer.
This is my test class
import com.lacunasaurus.gamesexplorer.test.configuration.TestBackEndConfiguration;
import com.lacunasaurus.gamesexplorer.test.configuration.TestWebConfig;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
#RunWith(JUnitPlatform.class)
#ExtendWith(SpringExtension.class)
#WebAppConfiguration()
#ContextConfiguration(classes = {TestWebConfig.class, TestBackEndConfiguration.class})
public class TestAuthenticationCreateAccountController {
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setup() {
// this.mockMvc = MockMvcBuilders.standaloneSetup(new AuthenticationCreateAccountController()).build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
#Test
public void getAccount() throws Exception {
// Here i've got an null pointer
mockMvc.perform(get("/"));
}
}
Here my web configuration for tests
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
#ComponentScan(basePackages = {"com.lacunasaurus.gamesexplorer.web"})
public class TestWebConfig implements WebMvcConfigurer, ApplicationContextAware {
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
And now my controller
#Controller
#RequestMapping("/create-account")
public class AuthenticationCreateAccountController {
#Autowired
UserAccountValidator accountValidator;
#Autowired
AuthenticationService authenticationService;
#GetMapping
public String navigate() {
return "authentication/create-account";
}
#ModelAttribute("userAccount")
public UserAccount setDefaultAccount() {
return new UserAccount();
}
#InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(accountValidator);
}
#PostMapping
public String createAccount(#Validated UserAccount userAccount, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "authentication/create-account";
}
authenticationService.createUserAccount(userAccount);
return "authentication/create-account";
}
}
EDIT : The stacktrace given by the IDE
java.lang.NullPointerException at com.lacunasaurus.gamesexplorer.test.controller.TestAuthenticationCreateAccountController.getAccount(TestAuthenticationCreateAccountController.java:41)
Results :
Tests in error:
TestAuthenticationCreateAccountController.getAccount:41 NullPointer
I've got already test my backend with junit 5 and spring and everything work well.
Thanks to thoses who will help me to understand how to test controller :)
The new test for controllers :
#ExtendWith(SpringExtension.class)
#WebAppConfiguration()
#ContextConfiguration(classes = {TestWebConfig.class, TestBackEndConfiguration.class})
#TestInstance(Lifecycle.PER_CLASS)
public class TestAuthenticationCreateAccountController {
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#BeforeEach
void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
#Test
void getAccount() throws Exception {
mockMvc.perform(get("/toto")).andExpect(status().isOk());
}
}
If you're using Junit5, See this reference
#ExtendWith(MockitoExtension.class) // For Junit5
public class TestAuthenticationCreateAccountController {
#Mock
private WebApplicationContext wac;
#InjectMocks
private AuthenticationCreateAccountController ac;
private MockMvc mockMvc;
#BeforeEach // For Junit5
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(ac).build();
}
#Test
public void getAccount() throws Exception {
mockMvc.perform(get("/"));
}
}
In order to use JUnit Jupiter, you must use autoconfigure MockMvc. This is a help to resolve all related configuration.
#ExtendWith(SpringExtension.class)
#WebAppConfiguration()
#AutoConfigureMockMvc
#Autowired
private MockMvc mockMvc;
This should fix your issue.
I am trying to do an example to change the xml config to Java config for Spring MVC. But my simple example is not working. On running this project on server, I can't see any beans initializing or the dispatcher servlet name on console.
and I get 404 error on running the http://localhost:8080/Servlet3Example/
I have created a maven project and following is my code:
package com.project.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MyDispatcherServlet extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
System.out.println("get root config");
//return new Class[]{RootConfig.class};
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
System.out.println("get web config");
return new Class[]{WebConfig.class};
}
#Override
protected String[] getServletMappings() {
System.out.println("in dispatcher servlet");
return new String[] {"/"};
}
}
And the WebConfig is:
package com.project.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages={"com.project.controllers"})
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setSuffix(".jsp");
viewResolver.setPrefix("/WEB-INF/views/");
return viewResolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
And controller:
package com.project.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController {
#RequestMapping(value="/",method=RequestMethod.GET)
public String home()
{
return "home";
}
}
Can you please change #ComponentScan to #ComponentScan(basePackages={"com.project.*"})
I am a student and learning JavaFX since a month.
I am developing a application where I want a service to repeatedly start again after its execution of the task. For this I have come to know that 'ScheduledService' is used.
So can anybody please explain the use of scheduledservice with simple example and also how it differs from the 'Service' in JavaFX. Thanks ;)
EDIT : How can I define that this ScheduledService named DataThread should be restarted every 5 seconds ?
public class DataThread extends ScheduledService<Void>
{
#Override
public Task<Void> createTask() {
return new Task<Void>() {
#Override
public Void call() throws Exception {
for(i=0;i<10;i++)
{
System.out.println(""+i);
}
return null;
}
};
}
}
Considering you have a sound knowledge of Service class. ScheduledService is just a Service with a Scheduling functionality.
From the docs
The ScheduledService is a Service which will automatically restart itself after a successful execution, and under some conditions will restart even in case of failure
So we can say it as,
Service -> Execute One Task
ScheduledService -> Execute Same Task at regular intervals
A very simple example of Scheduled Service is the TimerService, which counts the number of times the Service Task has been called. It is scheduled to call it every 1 second
import java.util.concurrent.atomic.AtomicInteger;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.util.Duration;
public class TimerServiceApp extends Application {
#Override
public void start(Stage stage) throws Exception {
TimerService service = new TimerService();
AtomicInteger count = new AtomicInteger(0);
service.setCount(count.get());
service.setPeriod(Duration.seconds(1));
service.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
System.out.println("Called : " + t.getSource().getValue()
+ " time(s)");
count.set((int) t.getSource().getValue());
}
});
service.start();
}
public static void main(String[] args) {
launch();
}
private static class TimerService extends ScheduledService<Integer> {
private IntegerProperty count = new SimpleIntegerProperty();
public final void setCount(Integer value) {
count.set(value);
}
public final Integer getCount() {
return count.get();
}
public final IntegerProperty countProperty() {
return count;
}
protected Task<Integer> createTask() {
return new Task<Integer>() {
protected Integer call() {
//Adds 1 to the count
count.set(getCount() + 1);
return getCount();
}
};
}
}
}