public class SpringMVCWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { LoginApplicationConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
public class Initializer extends AbstractHttpSessionApplicationInitializer {
public Initializer() {
super(Config.class);
}
}
How can i use both SessionManager and AbstractAnnotationConfigDispatcherServletInitializer without making multiple ContextLoader* definitions?
I had the same issue while working with Spring MVC and initialising multiple initialisers.
Separated the two into different classes and annotated them with Spring #Order(value)
This will be initialised first. The AbstractAnnotationConfigDispatcherServletInitializer will initiate the servlet application context as well as root application context.
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#Order(1)
public class Init extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override protected Class<?>[] getRootConfigClasses() {
return new Class[]{Config.class};
}
#Override protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override protected String[] getServletMappings() {
return new String[]{"/*"};
}
}
This will be annotated with #Order(2) This is the second initialisation for the Session initialisation class AbstractHttpSessionApplicationInitializer will ensure that the servlet will use springSessionRepositoryFilter for every request that is responsible for replacing HttpSession implementation by custom implementation backed by Redis more details.
import org.springframework.core.annotation.Order;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
#Order(2)
#EnableRedisHttpSession(maxInactiveIntervalInSeconds = 600)
public class SessionInit extends AbstractHttpSessionApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException
{
super.onStartup(servletContext);
}
}
Related
I want to store my data in realm but it is not working, it show me error when I click on save button where I add toast. There is no error found, but data is not saving.
My MainActivity Class
package com.deitel.realmrecyclerviewspinnerpriority;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import io.realm.Realm;
public class MainActivity extends AppCompatActivity {
private static final String TAG="MainActivity";
Realm realm;
EditText text_name;
EditText text_details;
Button btn_save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
realm=Realm.getDefaultInstance();
Realm.init(getApplicationContext());
text_name = findViewById(R.id.text_name);
text_details = findViewById(R.id.text_details);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
savedata(text_name.getText().toString(),text_details.getText().toString());
}
});
}
private void savedata(final String name, final String datails){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgrealm) {
// Number maxid=bgrealm.where(ModelClass.class).max("id");
// int newkey=(maxid==null) ? 1 : maxid.intValue()+1;
ModelClass user = bgrealm.createObject(ModelClass.class);
user.setName(name);
user.setDetails(datails);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
Realm Class Where I initilize configutation etc.
package com.deitel.realmrecyclerviewspinnerpriority;
import android.app.Application;
import io.realm.Realm;
import io.realm.RealmConfiguration;
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration configuration=new RealmConfiguration.Builder().name("RealmData.realm").build();
Realm.setDefaultConfiguration(configuration);
}
}
Model Class.
package com.deitel.realmrecyclerviewspinnerpriority.Modelclass;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class ModelClass extends RealmObject {
#PrimaryKey
private String Name;
private String Details;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDetails() {
return Details;
}
public void setDetails(String details) {
Details = details;
}
}
I think you are not setting primary key,
Try below approach
private void savedata(final String name, final String datails){
try(Realm mRealm = Realm.getDefaultInstance()){
ModelClass user = new ModelClass();
int newkey=(maxid==null) ? 1 : maxid.intValue()+1;
user.setId(newkey);
user.setName(name);
user.setDetails(datails);
mRealm.executeTransaction(rlm-> {
rlm.insertOrUpdate(user);
});
}
}
insertOrUpdate inserts a new record if PK doesn't exists else update it.
I am performing some background task using this class
class Download extends Task{
protected Object call() throws Exception {
try {
updateMessage("Establishing Connection");
DownloadHelper downloadHelper = new DownloadHelper();
downloadHelper.performTask();
return null;
} catch (IOException | ParseException ex) {
logger.error(ExceptionUtils.getStackTrace(ex));
throw ex;
}
}
}
This Task in turn calls DownloadHelper to perform some task.
class DownloadHelper{
public DownloadHelper(){
}
public void performTask(){
----
----
}
}
Is there a way to update the status message of the Task API (updateMessage()) from the DownloadHelper class.?
The expedient approach is to pass a reference to the Download task as a parameter to the DownloadHelper constructor. To minimize coupling, you can instead pass a reference to your implementation of updateMessage() as a parameter of type Consumer, "an operation that accepts a single input argument and returns no result."
DownloadHelper helper = new DownloadHelper(this::updateMessage);
Your helper's implementation of performTask() can then ask the updater to accept() messages as needed.
Consumer<String> updater;
public DownloadHelper(Consumer<String> updater) {
this.updater = updater;
}
public void performTask() {
updater.accept("Helper message");
}
A related example is seen here.
import java.util.function.Consumer;
import javafx.application.Application;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
* #see https://stackoverflow.com/q/45708923/230513
*/
public class MessageTest extends Application {
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("MessageTest");
StackPane root = new StackPane();
Label label = new Label();
root.getChildren().add(label);
Scene scene = new Scene(root, 320, 120);
primaryStage.setScene(scene);
primaryStage.show();
Download task = new Download();
task.messageProperty().addListener((Observable o) -> {
label.setText(task.getMessage());
});
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
private static class Download extends Task<String> {
#Override
protected String call() throws Exception {
updateMessage("Establishing connection");
DownloadHelper helper = new DownloadHelper(this::updateMessage);
helper.performTask();
return "MessageTest";
}
#Override
protected void updateMessage(String message) {
super.updateMessage(message);
}
}
private static class DownloadHelper {
Consumer<String> updater;
public DownloadHelper(Consumer<String> updater) {
this.updater = updater;
}
public void performTask() {
updater.accept("Helper message");
}
}
public static void main(String[] args) {
launch(args);
}
}
I have following classes
AppConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.pdma.dmapp")
public class AppConfig extends WebMvcConfigurerAdapter{
#Bean(name="multipartResolver")
public StandardServletMultipartResolver resolver(){
return new StandardServletMultipartResolver();
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
registry.viewResolver(viewResolver);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/webResources/**").addResourceLocations("/webResources/");
registry.addResourceHandler("/angularApps/**").addResourceLocations("/angularApps/");
}
}
SecurityConfiguration.java
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication()
.withUser("GISManager")
.password("gis#manager#pdma")
.roles("GISManager");
}
#Override
public void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/**").access("hasRole('GISManager')")
.and().formLogin()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
AppInitializer.java
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
private static final String LOCATION = "D:/uploads/";
private static final long MAX_FILE_SIZE = 1024*1024*25;
private static final long MAX_REQUEST_SIZE = 1024*1024*30;
private static final int FILE_SIZE_THRESHOLD = 0;
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class [] {AppConfig.class,SecurityConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/",
"*.html",
"*.htm",
"*.ajax"};
}
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration){
registration.setMultipartConfig(getMultipartConfigElement());
}
private MultipartConfigElement getMultipartConfigElement(){
MultipartConfigElement element = new MultipartConfigElement(LOCATION,
MAX_FILE_SIZE,
MAX_REQUEST_SIZE,
FILE_SIZE_THRESHOLD);
return element;
}
}
WelcomeController.java
#Controller
#RequestMapping(value="/")
public class WelcomeController {
#GetMapping(value="")
public String getWelcomePage(){
return "welcome";
}
}
welcome.jsp is placed in /WEB-INF/views/
I am getting login page and all other pages like main.html etc but I am unable to get welcome page. When I try to hit localhost:8080/dmapp/ I get following message in console:
WARNING: No mapping found for HTTP request with URI [/dmapp/] in DispatcherServlet with name 'dispatcher'
This problem was present before I used spring-security
What can be the problem
changing
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/",
"*.html",
"*.htm",
"*.ajax"};
}
to
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/"};
}
solved problem in my case
I created an EJB project and another project to test the first.
This screenshot gives an overview about my two projects.
The class main on the test project is:
public class TestEjb
{
public static void main(String[] args)
{
GestionEmployeeRemote gestion = null;
try {
Properties jndiProperties = new Properties();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
Context context = new InitialContext(jndiProperties);
Object o = context.lookup("ejb:/FirstEJBProject/GestionEmployee!services.GestionEmployeeRemote");
gestion = (GestionEmployeeRemote) o;
} catch (NamingException e) {
e.printStackTrace();
}
createEmployee(gestion);
}
public static void createEmployee(GestionEmployeeRemote gestion)
{
Employee employee = new Employee("Foulen", "Ben Foulen", new Date(), "Directeur");
gestion.createEmployee(employee);
}
The file jndi.properties is:
java.naming.factory.url.pkgs=org.jboss.ejb.client.naming
java.naming.factory.initial=org.jboss.naming.remote.client.InitialContextFactory
java.naming.provider.url=remote://localhost:4447
jboss.naming.client.ejb.context=true
jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT=false
The class GestionEmployee.java is:
package services;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import persistance.Employee;
/**
* Session Bean implementation class GestionEmployee
*/
#Stateless
public class GestionEmployee implements GestionEmployeeRemote, GestionEmployeeLocal {
#PersistenceContext
EntityManager em;
public GestionEmployee() {
// TODO Auto-generated constructor stub
}
#Override
public void createEmployee(Employee employee) {
em.persist(employee);
}
#Override
public void updateEmployee(Employee employee) {
em.merge(employee);
}
#Override
public void deleteEmployee(Employee employee) {
em.remove(employee);
}
#Override
public Employee getEmployeeById(int idEmployee) {
Employee elmployee = em.find(Employee.class, idEmployee);
return null;
}
#Override
public List<Employee> getAllEmployee() {
Query query = em.createQuery("select e from Employee e");
return query.getResultList();
}
}
The class GestionEmployeeRemote.java is:
package services;
import java.util.List;
import javax.ejb.Remote;
import persistance.Employee;
#Remote
public interface GestionEmployeeRemote
{
public void createEmployee (Employee employee);
public void updateEmployee (Employee employee);
public void deleteEmployee (Employee employee);
public Employee getEmployeeById (int idEmployee);
public List<Employee> getAllEmployee();
}
After running the class main, I got this error:
Exception in thread "main" java.lang.IllegalStateException: EJBCLIENT000025: No EJB receiver available for handling [appName:, moduleName:FirstEJBProject, distinctName:] combination for invocation context org.jboss.ejb.client.EJBClientInvocationContext#a47962
at org.jboss.ejb.client.EJBClientContext.requireEJBReceiver(EJBClientContext.java:749)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocation(ReceiverInterceptor.java:116)
at org.jboss.ejb.client.EJBClientInvocationContext.sendRequest(EJBClientInvocationContext.java:183)
at org.jboss.ejb.client.EJBInvocationHandler.sendRequestWithPossibleRetries(EJBInvocationHandler.java:253)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:198)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:144)
at com.sun.proxy.$Proxy0.createEmployee(Unknown Source)
at test.TestEjb.createEmployee(TestEjb.java:37)
at test.TestEjb.main(TestEjb.java:31)
I'm looking for finding a solution for this issue, any help is appreciated.Thanks a lot.
Hi I have a strange problem,
I'am following this Tutorial (http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/) and at step 5, configurting initializer class there are two ways of doing that:
1 with WebAppInitializer (my code below)
public class SpindleSpringWebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(AppConfig.class);
appContext.setServletContext(servletContext);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
With AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer (my code here)
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
This is my AppConfig.java
#Configuration
#EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(31556926);
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
The Thing is that when I use the first method everything works, but when I use the second one i get 404 (description The requested resource is not available). I have no other errors and I have no idea how to debug this. I wouldn't bother but I'm trying to implement Spring Security to the code and as I understand the secon type of initializer is the preffered type nowdays.
I'm using Maven, STS, Pivotal tc Servert Developer Edition. Thanks for any feedback.
The problem is solved. Target folder still held web.xml and context.xml files. Deleting target folder and reinstalling the app was the right thing to do