Struts2 execAndWait and file upload no work - file

I have this problem and I'm really going crazy without having a result.
I have a form and all fields are required through validator.xml
My form contains a field for the upload image (required)
When I click the submit button present a paggina waiting through (execAndWait configured in struts.xml).
my big problem is this:
the waiting page always redirect to my form page with text (the file field and mandatory).
Here is the code:
/register.jsp
<!-- al submit chiama l'action register -->
<action name="register" class="action.Register" method="execute" >
<interceptor-ref name="defaultStack" />
<interceptor-ref name="fileUpload">
<param name="maximumSize">10000000</param>
<param name="allowedTypes">image/jpeg,image/gif,image/jpg</param>
</interceptor-ref>
<interceptor-ref name="params"></interceptor-ref>
<interceptor-ref name="execAndWait">
</interceptor-ref>
<result name="success">index.jsp</result>
<result name="input">/register.jsp</result>
<result name="wait">/test.jsp</result>
</action>
waiting page:
<meta http-equiv="refresh" content="5;url=<s:url includeParams="all" />"/>
</head>
<body>
<p>your request is processing...</p>
<img src="images/indicator.gif"/>
my form:
<s:form method="post" action="register" validate="false" enctype="multipart/form-data">
<s:textfield key="utenteBean.nome" name="utenteBean.nome" value="a" />
<s:textfield key="utenteBean.nickname" name="utenteBean.nickname" value="a" />
<sj:datepicker key="utenteBean.nato" name="utenteBean.nato"
showButtonPanel="true" displayFormat="dd/mm/yy" value="25/09/1983"/>
<s:textfield key="utenteBean.professione" name="utenteBean.professione" value="a"/>
<s:textfield key="utenteBean.eta" name="utenteBean.eta" value="3"/>
<s:textfield key="utenteBean.dj_preferito" name="utenteBean.dj_preferito" value="a" />
<s:textfield key="utenteBean.rave_fatti" name="utenteBean.rave_fatti" value="3" />
<s:textfield key="utenteBean.sito_preferito" name="utenteBean.sito_preferito" value="a" />
<s:textfield key="utenteBean.come_siveste" name="utenteBean.come_siveste" value="a" />
<s:textarea key="utenteBean.messaggio" name="utenteBean.messaggio" value="a"/>
<s:file label="file" name="file" requiredLabel="true"" ></s:file>
really thanks for your help

I suppose that you have put wrong field name for the file tag. Can you show us your action class? Regarding to that instead of:
<s:file label="file" name="file" requiredLabel="true"" ></s:file>
try to use:
<s:file label="file" name="utenteBean.file" requiredLabel="true"" ></s:file>
or just check in your action class the name of the file property.

yes sure ... below my Action class:
public class Register extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private UtenteBeanAction utenteBean;
private File file;
private String fileContentType;
private String fileFileName;
private String filesPath;
private ServletContext context;
Map<String, Object> session;
public String execute(){
if (file != null) {
File file = this.file;
// /System.out.println(file.getName());
try {
Util.saveFile(file, fileFileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ERROR;
}
} else {
return ERROR;
}
return SUCCESS;
}
public void validate(){
if(this.fileFileName==null){
this.addFieldError("file", "errore");
}
}
public UtenteBeanAction getUtenteBean() {
return utenteBean;
}
public void setUtenteBean(UtenteBeanAction utenteBean) {
this.utenteBean = utenteBean;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFilesPath() {
return filesPath;
}
public void setFilesPath(String filesPath) {
this.filesPath = filesPath;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
#Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session=session;
}
}
Thank you so much for your help ...

I solved it by putting my bean in session. I could not find a better solution after many hours of work.
If other people have the same problem I can see the changes I made in my. Action
package action;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import Bean.UtenteBeanAction;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import Utility.Util;
public class Register extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private UtenteBeanAction utenteBean;
private ServletContext context;
Map<String, Object> session;
public String execute(){
session.put("utente", utenteBean);
if (utenteBean.getFile() != null) {
File file = utenteBean.getFile();
// /System.out.println(file.getName());
try {
Util.saveFile(file, utenteBean.getFileFileName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ERROR;
}
} else {
return ERROR;
}
return SUCCESS;
}
public void validate() {
if (session.get("utente") != null) {
this.utenteBean = (UtenteBeanAction) session.get("utente");
}
if (this.utenteBean.getFileFileName() == null) {
this.addFieldError("utenteBean.file", "errore");
}
}
public UtenteBeanAction getUtenteBean() {
return utenteBean;
}
public void setUtenteBean(UtenteBeanAction utenteBean) {
this.utenteBean = utenteBean;
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
#Override
public void setSession(Map<String, Object> session) {
// TODO Auto-generated method stub
this.session=session;
}
}
I hope I can be of help.
Thanks for the support.

Related

I'm trying to perform a search on my recycler adapter when onQueryTextChange gives error to make filter as static in adapter

This is my activity_course_details.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CourseDetails">
<SearchView
android:id="#+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false">
<requestFocus />
</SearchView>
<!--Recycler view for displaying
our data from Firestore-->
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/idRVCourses"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp" />
<!--Progress bar for showing loading screen-->
<ProgressBar
android:id="#+id/idProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
CoursesDetails.java
public class CourseDetails extends AppCompatActivity implements
SearchView.OnQueryTextListener{
// creating variables for our recycler view,
// array list, adapter, firebase firestore
// and our progress bar.
private RecyclerView courseRV;
private ArrayList<Courses> coursesArrayList;
private CourseRVAdapter courseRVAdapter;
private FirebaseFirestore db;
ProgressBar loadingPB;
SearchView editsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_details);
editsearch = (SearchView) findViewById(R.id.search);
editsearch.setOnQueryTextListener((SearchView.OnQueryTextListener) this);
// initializing our variables.
courseRV = findViewById(R.id.idRVCourses);
loadingPB = findViewById(R.id.idProgressBar);
// initializing our variable for firebase
// firestore and getting its instance.
db = FirebaseFirestore.getInstance();
// creating our new array list
coursesArrayList = new ArrayList<>();
courseRV.setHasFixedSize(true);
courseRV.setLayoutManager(new LinearLayoutManager(this));
// adding our array list to our recycler view adapter class.
courseRVAdapter = new CourseRVAdapter(coursesArrayList, this);
// setting adapter to our recycler view.
courseRV.setAdapter(courseRVAdapter);
// below line is use to get the data from Firebase Firestore.
// previously we were saving data on a reference of Courses
// now we will be getting the data from the same reference.
db.collection("Courses").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
// after getting the data we are calling on success method
// and inside this method we are checking if the received
// query snapshot is empty or not.
if (!queryDocumentSnapshots.isEmpty()) {
// if the snapshot is not empty we are
// hiding our progress bar and adding
// our data in a list.
loadingPB.setVisibility(View.GONE);
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
// after getting this list we are passing
// that list to our object class.
Courses c = d.toObject(Courses.class);
// and we will pass this object class
// inside our arraylist which we have
// created for recycler view.
coursesArrayList.add(c);
}
// after adding the data to recycler view.
// we are calling recycler view notifuDataSetChanged
// method to notify that data has been changed in recycler view.
courseRVAdapter.notifyDataSetChanged();
} else {
// if the snapshot is empty we are displaying a toast message.
Toast.makeText(CourseDetails.this, "No data found in Database", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// if we do not get any data or any error we are displaying
// a toast message that we do not get any data
Toast.makeText(CourseDetails.this, "Fail to get the data.", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String text = newText;
CourseRVAdapter.filter(text);
return false;
}
}
CoursesRVAdapter.java
public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> {
// creating variables for our ArrayList and context
private ArrayList<Courses> coursesArrayList = null;
private Context context;
private ArrayList<Courses> arrayList;
// creating constructor for our adapter class
public CourseRVAdapter(ArrayList<Courses> coursesArrayList, Context context) {
this.coursesArrayList = coursesArrayList;
this.context = context;
this.arrayList = new ArrayList<Courses>();
this.arrayList.addAll(coursesArrayList);
}
#NonNull
#Override
public CourseRVAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// passing our layout file for displaying our card item
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull CourseRVAdapter.ViewHolder holder, int position) {
// setting data to our text views from our modal class.
Courses courses = coursesArrayList.get(position);
holder.courseNameTV.setText(courses.getCourseName());
holder.courseDurationTV.setText(courses.getCourseDuration());
holder.courseDescTV.setText(courses.getCourseDescription());
}
#Override
public int getItemCount() {
// returning the size of our array list.
return coursesArrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
// creating variables for our text views.
private final TextView courseNameTV;
private final TextView courseDurationTV;
private final TextView courseDescTV;
public ViewHolder(#NonNull View itemView) {
super(itemView);
// initializing our text views.
courseNameTV = itemView.findViewById(R.id.idTVCourseName);
courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);
courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
}
}
#Override
public long getItemId(int position) {
return position;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
coursesArrayList.clear();
if (charText.length() == 0) {
arrayList.addAll(coursesArrayList);
} else {
for (Courses wp : arrayList) {
if (wp.getCourseName().toLowerCase(Locale.getDefault()).contains(charText)) {
coursesArrayList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Courses.java
public class Courses {
// variables for storing our data.
private String courseName, courseDescription, courseDuration;
public Courses() {
// empty constructor
// required for Firebase.
}
// Constructor for all variables.
public Courses(String courseName, String courseDescription, String courseDuration) {
this.courseName = courseName;
this.courseDescription = courseDescription;
this.courseDuration = courseDuration;
}
// getter methods for all variables.
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
// setter method for all variables.
public void setCourseDescription(String courseDescription) {
this.courseDescription = courseDescription;
}
public String getCourseDuration() {
return courseDuration;
}
public void setCourseDuration(String courseDuration) {
this.courseDuration = courseDuration;
}
}
i dont want to make this classs as static it give me error to uch so icant to amke search option in my android application i cant resolve this issue please help to resolve this issue.
i getting error in CourseRVAdapter.filter(text);
this to make filter as static this filter is make in CoursesRVAdapter public void filter(String charText) {------}
is the classs so what can do for making search option in recyclerview adapter list in android.
and please if you getting any suggesion for me please give me
i appreciating all of the things that you will says to me
thank you so much

Unable to display data fetched from the database

I am new to stackoverflow and to Java. I am trying to fetch the data from the database then display it in a JSF page.
For the table I have a model : BusesInfo.java that contains getters and setters for the attributes of the table.
then I also have BusesDao that fetches the data from DB and stores it in an array list. BusesInfoBean that links these data to the JSF page. The connection to the database is success. the JSF page contains a table that calls BusesInfobean.busesInfo in the columns i call BusesInfo.attribute
Please I need your help! Below you can find sample codes:
package beans;
import daos.BusesDao;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import models.BusesInfo;
#ViewScoped
public class BusesInfoBean implements Serializable {
private final BusesDao busesDao = new BusesDao();
private ArrayList<BusesInfo> busesInfo;
public BusesInfoBean(){}
#PostConstruct
public void init(){
try {
busesInfo = busesDao.buildBusesInfo();
} catch (Exception ex) {
Logger.getLogger(ManageEventsBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
public ArrayList<BusesInfo> getBusesInfo() {
return busesInfo;
}
public void setBusesInfo(ArrayList<BusesInfo> busesInfo) {
this.busesInfo = busesInfo;
}
}
BusesDao.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import models.BusesInfo;
import java.util.logging.Logger;
import java.util.logging.Level;
public class BusesDao extends ConnectionDao {
public ArrayList<BusesInfo> buildBusesInfo() throws Exception {
ArrayList<BusesInfo> list = new ArrayList<>();
Connection conn = getConnection();
try {
String sql = "SELECT * FROM BUSES_INFO";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(populateBusesInfo(rs));
}
rs.close();
ps.close();
return list;
} catch (SQLException e) {
throw new SQLException(e.getMessage());
}
}
private BusesInfo populateBusesInfo(ResultSet rs) throws SQLException {
BusesInfo busesInfo = new BusesInfo();
busesInfo.setBusID(rs.getInt("BUS_ID"));
busesInfo.setDriverID(rs.getInt("DRIVER_ID"));
busesInfo.setDepartureTime(rs.getString("DEPARTURE_TIME"));
busesInfo.setArrivalTime(rs.getString("ARRIVAL_TIME"));
busesInfo.setRouteEn(rs.getString("ROUTE_EN"));
busesInfo.setRouteAr(rs.getString("ROUTE_AR"));
busesInfo.setLicensePlate(rs.getString("LICENSE_PLATE"));
busesInfo.setCapacity(rs.getInt("CAPACITY"));
return busesInfo;
}
public static void main(String [] args){
try {
BusesDao busesDao = new BusesDao();
ArrayList<BusesInfo> busesInfo = busesDao.buildBusesInfo();
} catch (Exception ex) {
Logger.getLogger(EventsDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
the model class BusesInfo only contains getters and setters:
public class BusesInfo implements Serializable {
private int busID;
private int driverID;
private String departureTime;
private String arrivalTime;
private String routeEn;
private String routeAr;
private String licensePlate;
private int capacity;
public BusesInfo(){}
/**
*
* #param busID
* #param driverID
* #param departureTime
* #param arrivalTime
* #param routeEn
* #param routeAr
* #param licensePlate
* #param capacity
*/
public BusesInfo(int busID, int driverID, String departureTime, String arrivalTime, String routeEn, String routeAr, String licensePlate, int capacity) {
this.busID = busID;
this.driverID = driverID;
this.departureTime = departureTime;
this.arrivalTime = arrivalTime;
this.routeEn = routeEn;
this.routeAr = routeAr;
this.licensePlate = licensePlate;
this.capacity = capacity;
}
public int getBusID() {
return busID;
}
public void setBusID(int busID) {
this.busID = busID;
}
public int getDriverID() {
return driverID;
}
public void setDriverID(int driverID) {
this.driverID = driverID;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getRouteEn() {
return routeEn;
}
public void setRouteEn(String routeEn) {
this.routeEn = routeEn;
}
public String getRouteAr() {
return routeAr;
}
public void setRouteAr(String routeAr) {
this.routeAr = routeAr;
}
public String getLicensePlate() {
return licensePlate;
}
public void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
}
JSF page:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>#{msgs.buses}</title>
</h:head>
<h:body>
<div>
<ui:decorate template="/app_templates/app_template.xhtml">
<h:form id="bus_info_form">
<p:dataTable
id="bus_info_tbl"
value = "#{busesInfoBean.busesInfo}"
class = "dataTable"
var="event"
rows="2"
dir="#{langBean.dir}"
emptyMessage="#{msgs.no_buses}"
paginator="true"
paginatorPosition="top"
paginatorTemplate="#{langBean.isEnglish? '{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}' : '{RowsPerPageDropdown} {LastPageLink} {NextPageLink} {PageLinks} {PreviousPageLink} {FirstPageLink}'}"
>
<p:ajax event="rowSelectRadio"
update=":bus_info_form:bus_info_tbl"/>
<f:facet name="header" id="header">
#{msgs.buses}
</f:facet>
<p:column selectionMode="single" style="width:5%"/>
<p:column headerText="#{msgs.bus_id}"
style="width:15%"
sortBy="#{busesInfo.busID}">
<h:outputText value="#{busesInfo.busID}"/>
</p:column>
<p:column headerText="#{msgs.driver_id}"
style="width:15%"
sortBy="#{busesInfo.driverID}">
<h:outputText value="#{busesInfo.driverID}"/>
</p:column>
<p:column headerText="#{msgs.departure_time}"
style="width:15%"
sortBy="#{busesInfo.departureTime}">
<h:outputText value="#{busesInfo.departureTime}"/>
</p:column>
<p:column headerText="#{msgs.arrival_time}"
style="width:15%"
sortBy="#{busesInfo.arrivalTime}">
<h:outputText value="#{busesInfo.arrivalTime}"/>
</p:column>
<p:column headerText="#{msgs.route}"
style="width:20%"
filterBy="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}"
filterMatchMode="contains"
sortBy="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}">
<h:outputText value="#{langBean.isEnglish?busesInfo.routeEn:busesInfo.routeAr}"/>
</p:column>
<p:column headerText="#{msgs.license_plate}"
style="width:15%"
sortBy="#{busesInfo.licensePlate}">
<h:outputText value="#{busesInfo.licensePlate}"/>
</p:column>
<p:column headerText="#{msgs.capacity}"
style="width:15%"
sortBy="#{busesInfo.capacity}">
<h:outputText value="#{busesInfo.capacity}"/>
</p:column>
</p:dataTable>
</h:form>
</ui:decorate>
</div>
</h:body>
</html>

camel jpa #Consumed is not being called

I'm trying to use #Consumed on jpa entity with camel.
this is my route :
<route id="incomingFileHandlerRoute">
<from
uri="jpa://com.menora.inbal.incomingFileHandler.Jpa.model.MessageToDB?consumer.nativeQuery=select
* from file_message where mstatus = 'TODO'&consumer.delay=5000&consumeDelete=false&consumeLockEntity=true&consumer.SkipLockedEntity=true" />
<to uri="bean:incomingFileHandler" />
</route>
and my entity:
#Entity
#Table(name = "file_message")
public class MessageToDB implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
private String uuid;
private String fileName;
private String body;
private String mstatus;
#Temporal(TemporalType.TIMESTAMP)
private Date mtimestamp;
#Consumed
public void updateMstatus() {
setMstatus(MessageStatus.DONE.name());
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getMstatus() {
return mstatus;
}
public void setMstatus(String mstatus) {
this.mstatus = mstatus;
}
public Date getMtimestamp() {
return mtimestamp;
}
public void setMtimestamp(Date mtimestamp) {
this.mtimestamp = mtimestamp;
}
}
I do get to incomingFileHandler bean with results from db but I do not get to the Consumed method updateMstatus . The incomingFileHandler bean is getting called continuously as always there are results from db
I have a similar implementation with camel-jpa and annotations #Consumed and #PreConsumed in the entity but none of these methods is called.
I look the camel-jpa source code and found this in JpaConsumer.java:
protected DeleteHandler<Object> createPreDeleteHandler() {
// Look for #PreConsumed to allow custom callback before the Entity has been consumed
final Class<?> entityType = getEndpoint().getEntityType();
if (entityType != null) {
// Inspect the method(s) annotated with #PreConsumed
if entityType is null the entity class inst inspect the method annotated with #Consumed and #PreConsumed.
Solution: add entityType=com.xx.yy.MessageToDB to your URI to set Endpoint Entity type.

Code is working in jdk7 not in jdk8

I took the sample code from How to create custom components in JavaFX 2.0 using FXML?. the code working fine in jdk7 but the checkbox and combo box values are not working in jdk8. I am not able to click the check box even and select the dropdown.
Please guide me for the same.
Please find the sample code below
Package structure
com.example.javafx.choice
ChoiceCell.java
ChoiceController.java
ChoiceModel.java
ChoiceView.fxml
com.example.javafx.mvc
FxmlMvcPatternDemo.java
MainController.java
MainView.fxml
MainView.properties
ChoiceCell.java
package com.example.javafx.choice;
import java.io.IOException;
import java.net.URL;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Node;
import javafx.scene.control.ListCell;
public class ChoiceCell extends ListCell<ChoiceModel>
{
#Override
protected void updateItem(ChoiceModel model, boolean bln)
{
super.updateItem(model, bln);
if(model != null)
{
URL location = ChoiceController.class.getResource("ChoiceView.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try
{
Node root = (Node)fxmlLoader.load(location.openStream());
ChoiceController controller = (ChoiceController)fxmlLoader.getController();
controller.setModel(model);
setGraphic(root);
}
catch(IOException ioe)
{
throw new IllegalStateException(ioe);
}
}
}
}
ChoiceController.java
package com.example.javafx.choice;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
public class ChoiceController
{
private final ChangeListener<String> LABEL_CHANGE_LISTENER = new ChangeListener<String>()
{
public void changed(ObservableValue<? extends String> property, String oldValue, String newValue)
{
updateLabelView(newValue);
}
};
private final ChangeListener<Boolean> IS_SELECTED_CHANGE_LISTENER = new ChangeListener<Boolean>()
{
public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue)
{
updateIsSelectedView(newValue);
}
};
private final ChangeListener<Boolean> IS_VISIBILITY1_CHANGE_LISTENER = new ChangeListener<Boolean>() {
public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue) {
updateIsVisibleView1(newValue);
}};
#FXML
private Label labelView;
#FXML
private CheckBox isSelectedView;
#FXML
ComboBox isVisible1;
private ChoiceModel model;
public ChoiceModel getModel()
{
return model;
}
public void setModel(ChoiceModel model)
{
if(this.model != null)
removeModelListeners();
this.model = model;
setupModelListeners();
updateView();
}
private void removeModelListeners()
{
model.labelProperty().removeListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().removeListener(IS_SELECTED_CHANGE_LISTENER);
model.isVisibleProperty1().removeListener(IS_VISIBILITY1_CHANGE_LISTENER);
isSelectedView.selectedProperty().unbindBidirectional(model.isSelectedProperty());
}
private void setupModelListeners()
{
model.labelProperty().addListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().addListener(IS_SELECTED_CHANGE_LISTENER);
model.isVisibleProperty1().addListener(IS_VISIBILITY1_CHANGE_LISTENER);
isSelectedView.selectedProperty().bindBidirectional(model.isSelectedProperty());
}
private void updateView()
{
updateLabelView();
updateIsSelectedView();
updateIsVisibleView1();
}
private void updateLabelView(){ updateLabelView(model.getLabel()); }
private void updateLabelView(String newValue)
{
labelView.setText(newValue);
}
private void updateIsSelectedView(){ updateIsSelectedView(model.isSelected()); }
private void updateIsSelectedView(boolean newValue)
{
isSelectedView.setSelected(newValue);
}
private void updateIsVisibleView1() {
updateIsVisibleView1(model.isVisible1());
}
private void updateIsVisibleView1(boolean newValue) {
isVisible1.setVisible(newValue);
}
}
ChoiceModel.java
package com.example.javafx.choice;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class ChoiceModel
{
private final StringProperty label;
private final BooleanProperty isSelected;
private final BooleanProperty isVisible1;
public ChoiceModel(String label, boolean isSelected, boolean isVisible1)
{
this.label = new SimpleStringProperty(label);
this.isSelected = new SimpleBooleanProperty(isSelected);
this.isVisible1 = new SimpleBooleanProperty(isVisible1);
}
public String getLabel(){ return label.get(); }
public void setLabel(String label){ this.label.set(label); }
public StringProperty labelProperty(){ return label; }
public boolean isSelected(){ return isSelected.get(); }
public void setSelected(boolean isSelected){ this.isSelected.set(isSelected); }
public BooleanProperty isSelectedProperty(){ return isSelected; }
public boolean isVisible1()
{
return isVisible1.get();
}
public void setVisible1(boolean isVisible1)
{
this.isVisible1.set(isVisible1);
}
public BooleanProperty isVisibleProperty1()
{
return isVisible1;
}
}
ChoiceView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.collections.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<HBox xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="com.example.javafx.choice.ChoiceController">
<children>
<CheckBox fx:id="isSelectedView" />
<Label fx:id="labelView" />
<ComboBox id="isVisible1" fx:id="isVisible1" value="last 7 digits" visible="false">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="last 10 digits" />
<String fx:value="last 9 digits" />
<String fx:value="last 8 digits" />
<String fx:value="last 7 digits" />
<String fx:value="last 6 digits" />
<String fx:value="last 5 digits" />
<String fx:value="last 4 digits" />
<String fx:value="last 3 digits" />
</FXCollections>
</items>
</ComboBox>
</children>
</HBox>
FxmlMvcPatternDemo.java
package com.example.javafx.mvc;
import com.example.javafx.choice.ChoiceController;
import java.util.ResourceBundle;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class FxmlMvcPatternDemo extends Application
{
public static void main(String[] args) throws ClassNotFoundException
{
Application.launch(FxmlMvcPatternDemo.class, args);
}
#Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load
(
FxmlMvcPatternDemo.class.getResource("MainView.fxml"),
ResourceBundle.getBundle(FxmlMvcPatternDemo.class.getPackage().getName()+".MainView")/*properties file*/
);
ChoiceController controller = new ChoiceController();
stage.setScene(new Scene(root));
stage.show();
}
}
MainController.java
package com.example.javafx.mvc;
import com.example.javafx.choice.ChoiceCell;
import com.example.javafx.choice.ChoiceModel;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
public class MainController implements Initializable
{
#FXML
private ListView<ChoiceModel> choicesView;
#Override
public void initialize(URL url, ResourceBundle rb)
{
choicesView.setCellFactory(new Callback<ListView<ChoiceModel>, ListCell<ChoiceModel>>()
{
public ListCell<ChoiceModel> call(ListView<ChoiceModel> p)
{
return new ChoiceCell();
}
});
choicesView.setItems(FXCollections.observableArrayList
(
new ChoiceModel("Tiger", true, false),
new ChoiceModel("Shark", false, true),
new ChoiceModel("Bear", false, true),
new ChoiceModel("Wolf", true, true)
));
}
#FXML
private void handleForceChange(ActionEvent event)
{
if(choicesView != null && choicesView.getItems().size() > 0)
{
boolean isSelected = choicesView.getItems().get(0).isSelected();
choicesView.getItems().get(0).setSelected(!isSelected);
}
}
}
MainView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox
xmlns:fx="http://javafx.com/fxml"
fx:controller="com.example.javafx.mvc.MainController"
prefWidth="300"
prefHeight="400"
fillWidth="false"
>
<children>
<Label text="%title" />
<ListView fx:id="choicesView" />
<Button text="Force Change" onAction="#handleForceChange" />
</children>
</VBox>
MainView.proprties
title=JavaFX 2.0 FXML MVC demo
I didn't dig deeper but refactoring like as following should suffice. Double check for correct executions of attached and removed listeners.
public class ChoiceCell extends ListCell<ChoiceModel> {
private Node root;
private ChoiceController controller;
public ChoiceCell() {
URL location = ChoiceController.class.getResource("ChoiceView.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try {
root = (Node) fxmlLoader.load(location.openStream());
controller = (ChoiceController) fxmlLoader.getController();
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
#Override
protected void updateItem(ChoiceModel model, boolean bln) {
super.updateItem(model, bln);
if (model != null) {
controller.setModel(model);
setGraphic(root);
} else {
setGraphic(null);
}
}
}

How to call another method in the pojo class setter method [session file uploading application] of Hibernate and struts 2

Hi Friends i am developing an web application which uses hibernate and struts2. i am creating photo album i successfully done that with out using hibernate but, with hibernate it is having problem while inserting to the database. the module works like this as soon as the file uploaded it will insert the FileName, Contenttype,id and it suppose to insert the Image File(byte[]) Content also but it is showing Null in table value.. my code goes like this...
#Entity
#Table(name="PHOTOALBUM")
public class User implements Serializable {
#Id
#GeneratedValue
#Column(name="PHOTO_ID")
private Long id;
#Column(name="IMAGE")
private byte[] Image;
#Column(name="CONTENT_TYPE")
private String userImageContentType;
#Column(name="PHOTO_NAME")
private String userImageFileName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserImageFileName() {
return userImageFileName;
}
public void setUserImageFileName(String userImageFileName) {
this.userImageFileName = userImageFileName;
}
public String getUserImageContentType() {
return userImageContentType;
}
public void setUserImageContentType(String userImageContentType) {
this.userImageContentType = userImageContentType;
}
public byte[] getImage() {
return Image;
}
public void setImage(byte[] Image) {
Image=Change(this.getUserImage());
this.Image = Image;
}
#Transient
private File userImage;
public File getUserImage() {
return userImage;
}
public void setUserImage(File userImage) {
this.userImage = userImage;
}
public byte[] Change(File userImage)
{
// userImage=this.getUserImage();
// String name=userImage.getName();
// long len=userImage.length();
byte[] bFile = new byte[(int) userImage.length()];
try {
FileInputStream fileInputStream = new FileInputStream(userImage);
fileInputStream.read(bFile);
fileInputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
// System.out.println("The Name Of File In Pojo Class Is:="+ name);
//System.out.println("The Length Of File In Pojo Class Is:="+ len);
//System.out.println("The Content Of File In Pojo Class Is:="+ bFile);
return bFile;
}
}
and i am saving the values like this
public class UserDAOImpl implements UserDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
/**
* Used to save or update a user.
*/
#Override
public void saveOrUpdateUser(User user) {
try {
session.saveOrUpdate(user);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to delete a user.
*/
#Override
public void deleteUser(Long userId) {
try {
User user = (User) session.get(User.class, userId);
session.delete(user);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to list all the users.
*/
#SuppressWarnings("unchecked")
#Override
public List<User> listUser() {
List<User> courses = null;
try {
courses = session.createQuery("from User").list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}
/**
* Used to list a single user by Id.
*/
#Override
public User listUserById(Long userId) {
User user = null;
try {
user = (User) session.get(User.class, userId);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
}
the struts action mapping goes like this...
\<package name="default" extends="hibernate-default">
<action name="saveOrUpdateUser"method="saveOrUpdate"class="com.srikanth.web.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
<action name="listUser" method="list" class="com.srikanth.web.UserAction">
<result name="success">/register.jsp</result>
</action>
<action name="editUser" method="edit" class="com.srikanth.web.UserAction">
<result name="success">/register.jsp</result>
</action>
<action name="deleteUser" method="delete" class="com.srikanth.web.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
</package>
and my jsp goes like this
\<s:form action="saveOrUpdateUser">
<s:push value="user">
<s:hidden name="id" />
<s:file name="userImage" label="User Image" />
<s:submit />
</s:push>
</s:form>
<s:iterator value="userList" status="userStatus">
<s:property value="id" />
<s:property value="userImageFileName" />
<s:property value="userImageContentType" />
<img src='<s:property value="userImage" />' alt"" />
<s:url id="deleteURL" action="deleteUser">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a>
</s:iterator>
I am trying to call the Change Method so that it convert the file to byte[] and stored it in byte[] Image variable using setter but it is not working....
So please help me with this one .....
thanks in advance
As per my understand of question the problem is only inserting file into table. Copy & paste the Change() method into com.srikanth.web.UserAction class as you are using this action for every DB transaction. use Change() method before going to insert/update in DB.
For example:
public class UserAction extends ActionSupport{
//variable to get file from jsp
private File uploadedImage;
.....
//setters & getters for uploadedImage
#Override
public String gsexecute() throws Exception {
User user = new User();
//set image value as byteArray
user.setImage(Change(uploadedImage));
//insert or update DB here
return SUCCESS;
}
public byte[] Change(File userImage)
{
// userImage=this.getUserImage();
// String name=userImage.getName();
// long len=userImage.length();
byte[] bFile = new byte[(int) userImage.length()];
try {
FileInputStream fileInputStream = new FileInputStream(userImage);
fileInputStream.read(bFile);
fileInputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
// System.out.println("The Name Of File In Pojo Class Is:="+ name);
//System.out.println("The Length Of File In Pojo Class Is:="+ len);
//System.out.println("The Content Of File In Pojo Class Is:="+ bFile);
return bFile;
}
}
And make sure that the table column should support the byte array insert. Ex: use BLOB column type for MYSQL.

Resources