MySQL YEAR field - how to input from jsf - mysql

The tools created this field in the entity:
#Entity
#Table(name = "movies")
public class Movie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idmovie;
// etc
#Temporal(TemporalType.DATE)
#Column(name = "year_of_release")
#Past(message = "Back from the future ?") // added by me
#NotNull(message = "Please enter the year of the movie") // added by me
private Date yearOfRelease;
}
I want to enter the year from a form - I can't find anything that produces a year drop down and that converts it to an YEAR field (getting Data truncation exceptions).
The closest I got :
<h:outputLabel for="yearOfRelease">Year of release</h:outputLabel>
<h:inputText id="yearOfRelease"
value="#{movieController.movie.yearOfRelease}" redisplay="true"
converterMessage="Please enter date in yyyy-MM-dd format">
<f:convertDateTime pattern="yyyy-MM-dd" />
</h:inputText>
<h:message id="yearOfReleaseMessage" for="yearOfRelease" />
Do not seem to find a converter to tell jsf to convert to year.
Is integer my only option ?
Also ideally I would like a dropdown. I found things like
<h:selectOneListbox value="#{form.year}" size="5">
<f:selectItem itemValue="1900" itemLabel="1900"/>
<f:selectItem itemValue="1901" itemLabel="1901"/> ... </h:selectOneListbox>
but surely there is a way to have this automated ?
I am new to JSF and I'd rather stay vanilla JavaEE (no faces libraries). I am on glassfish 4.
Partial answer
// YEAR
private static final short MIN_YEAR = 1901;
private static final short MAX_YEAR = 2014; // (short) new
// java.util.Date().getYear(); // does not play with message
private static final List<Short> YEARS = new ArrayList<>(MAX_YEAR
- MIN_YEAR + 1);
static {
for (short i = MIN_YEAR; i <= MAX_YEAR; ++i) {
YEARS.add(i);
}
}
private static final String MIN_MSG = "Min release year: " + MIN_YEAR;
private static final String MAX_MSG = "Max release year: " + MAX_YEAR;
#Column(name = "year_of_release")
#NotNull(message = "Please enter the year of release of the movie")
#Min(value = 1901, message = MIN_MSG)
#Max(value = 2014, message = MAX_MSG)
private short yearOfRelease = 2014;
public List<Short> getYears() {
return YEARS;
}
And in the form:
<h:selectOneListbox id="yearOfRelease" redisplay="true"
value="#{movieController.movie.yearOfRelease}" size="8">
<f:selectItems value="#{movieController.movie.years}" var="entry"
itemValue="#{entry}" itemLabel="#{entry}" />
<f:ajax event="blur" render="yearOfReleaseMessage" />
</h:selectOneListbox>
If someone can come up with something more elegant (like some ready made Year dropdown that validates #Past and converts to something nice for a MySQL Year datatype) I would gladly accept it.

You can declare <f:selectItems /> and fill it with values from the bean, so something like
#RequestScoped
#ManagedBean
public class Form {
private List<String> items = new ArrayList<>();
#PostConstruct
public void init() {
for(int i=1900;i<2000;i++) {
items.add(i);
}
}
public List<String> getItems() {
return items;
}
}
and then in your page
<h:selectOneListbox value="#{form.year}" size="5">
<f:selectItems value="#{form.items}" var="entry"
itemValue="#{entry}" itemLabel="#{entry}" />
</h:selectOneListbox>

Related

How to use LazyDataModel List in a selectOneMenu

I want to use a LazyDataModel List inside a SelectOneMenu, but the selectoneMenu doesn't show anything . this is my code
public void show() {
beneficiaries = new LazyDataModel<Fournisseur>() {
private static final long serialVersionUID = 1L;
private List<Fournisseur> list;
#Override
public List<Fournisseur> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,Object> filters){
list = service.getAll((String)filters.get("benef.intitule"),first, pageSize);
this.setRowCount(service.count((String)filters.get("benef.intitule")));
return list;
}
#Override
public Object getRowKey(Fournisseur obj) {
return obj.getCpt();
}
#Override
public Fournisseur getRowData(String rowKey) {
Fournisseur o=null;
if(rowKey != null) {
for (Fournisseur obj : list) {
if(rowKey == obj.getCpt()) {
o = obj;
}
}
return o;
}else {
return null;
}
}
};
}
this is my html code
<p:selectOneMenu id="beneficiary" value="#
{documentController.doc.beneficiary}" converter="#
{beneficiaryConverter}" panelStyle="width:160px" required="true" >
<f:selectItem itemLabel="Selectionner" itemValue="" />
<f:selectItems value="#{beneficiaryController.beneficiaries}"
var="beneficiary" itemLabel="#{beneficiary.intitule}" itemValue="#
{beneficiary}" />
</p:selectOneMenu>
i've tested the list out side the selectOneMenu and it's work fine.
You are using PrimeFaces and want to allow the user to select one out of very many options. As Melloware mentioned, LazyDataModel is ment for use with DataTable or other components that support pagination this way ( e.g. DataGrid)
For your use case p:autoComplete seemes to be the best way to go.
dropdown="true" makes it look like a selectOneMenu, and you can limit the number of items show using maxResults="5".
<p:autoComplete dropdown="true" maxResults="5" value="#{autoCompleteView.txt6}"
completeMethod="#{autoCompleteView.completeText}" />
You'll need to write a custom autoComplete method that finds matches for given user search input:
public List<String> completeText(String query) {
List<String> results = new ArrayList<String>();
// fill the result matching the query from user input
return results;
}

Multiple Dateformat

i am task to change the dateformat according to the user's language. Currently the website runs in Chinese and English, However i am unable to change the format of the mask according to the user's language.
<h:outputText styleClass="outputText"
id="index_output_todate" value="#{msg.index_output_todate}">
</h:outputText>
<p:calendar value="#{pc_Index.w_message.am_todate_filter}"
id="index_input_todate" styleClass="calendar" maxlength="10"
pattern="#{pc_Index.dateDisplayFormat}" onfocus="$(this).mask('9999年99月99日');">
<p:watermark for="index_input_todate" value="#{pc_Index.watermarkDateDisplayFormat}" />
<f:convertDateTime pattern="#{pc_Index.dateDisplayFormat}" />
</p:calendar>
I need the date format of the mask to be 9999年99月99日 when the user login as a zh_CN user or a date format of DD/MM/YYYY for en_UK user.
Is there a way to do this?
I had already set the locale
public String getDateDisplayFormat() {
String locale = getUserLocale();
String DATEFORMAT_UK = "dd/MM/yyyy";
String DATEFORMAT_US = "mm/dd/yyyy";
String DATEFORMAT_CN = "yyyy年MM月dd日";
String _s = DATEFORMAT_UK;
if(!isEmptyNull(locale) && locale.equals("en_US")) {
_s = DATEFORMAT_US;
}
else if(!isEmptyNull(locale) && locale.equals("zh_CN")) {
_s = DATEFORMAT_CN;
}
return _s;
}
EDIT:
HTML
<h:form> <p:outputLabel for="index_output_frdate" value="#{msg.index_output_frdate}" />
<p:calendar id="index_output_frdate" value="#{pc_Index.w_message.am_todate_filter}"
styleClass="calendar" maxlength="10"
pattern="#{pc_Index.dateDisplayFormat}" mask="true" />
<p:watermark for="index_output_frdate" value="#{pc_Index.watermarkDateDisplayFormat}" /> </h:form>
Manage Bean:
if (isPageFirstLoad(JSP)) {
_w.setIndex_viewtype("11961003");
if (isEmptyNull(_w.getAm_todate_filter())) {
_w.setAm_todate_filter(getTodayDate());
}
Date _todate = _w.getAm_todate_filter();
Date d = _w.addDaysToDate(_todate, -7);
_w.setAm_frdate_filter(d);
_w.setViewNew(true);
_w.populateAlertsMessages();
}
if (this.trigger_viewtype_change) {
this.trigger_viewtype_change = false;
}
}
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getDateDisplayFormat() {
String locale = getUserLocale(); //WARNING!! Hard-coded!!
final String DATEFORMAT_UK = "dd/MM/yyyy";
final String DATEFORMAT_US = "mm/dd/yyyy";
final String DATEFORMAT_CN = "yyyy年MM月dd日";
if(!locale.isEmpty() && locale.equals("en_US")) {
return DATEFORMAT_US;
}
if(!locale.isEmpty() && locale.equals("zh_CN")) {
return DATEFORMAT_CN;
}
return DATEFORMAT_UK;
}
Doesn't seems to have anything wrong. but the mask just doesnt seem to come out
I don´t know what snippet of your code fails exactly. I've tried an easier example and works very well, so I recommend you debug all your involved code in this functionality.
<h:form>
<p:outputLabel for="mask" value="Mask:" />
<p:calendar id="mask" value="#{dumpController.date}" pattern="#{dumpController.dateDisplayFormat}" mask="true" />
<p:watermark for="mask" value="Input a date" />
</h:form>
Method in charge to set the date's mask:
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getDateDisplayFormat() {
final String locale = "zh_CN"; //WARNING!! Hard-coded!!
final String DATEFORMAT_UK = "dd/MM/yyyy";
final String DATEFORMAT_US = "mm/dd/yyyy";
final String DATEFORMAT_CN = "yyyy年MM月dd日";
if(!locale.isEmpty() && locale.equals("en_US")) {
return DATEFORMAT_US;
}
if(!locale.isEmpty() && locale.equals("zh_CN")) {
return DATEFORMAT_CN;
}
return DATEFORMAT_UK;
}

PrimeFaces add row to DataTable

I want to make a Log-File-Reader. I have a Upload field, and a dataTable. First I choose the Log-File an Upload it. Then the program Split each line of the Log-File in the separate variables. Now the Log-File should be printet line for line into the table. But I dont know, how i should put the Lines in the Table. It works, when I define the Lines Static bevore. But now when the lines are not defined static it don't update the Table.
Here is my index.xhtml:
<h:form xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>LogReader</title>
</h:head>
<h:body>
<p:accordionPanel dynamic="true" cache="true" activeIndex="1" multiple="false">
<p:tab title="Upload File">
<h:panelGrid>
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}" mode="advanced" dragDropSupport="false"
update="messages" fileLimit="1" allowTypes="/(\.|\/)(log|txt|)$/" />
<p:growl id="messages" showDetail="true"/>
</h:panelGrid>
</p:tab>
</p:accordionPanel>
<p:dataTable id="dataTable" var="log" value="#{fileUpload.logsSmall}" widgetVar="dataTable"
emptyMessage="No Log found with given criteria" filteredValue="#{tableBean.filteredLogs}"
rowKey="#{log.datetime}" paginator="true" rows="20" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" rowsPerPageTemplate="5,10,15,20,50,100" selection="#{tableBean.selectedLog}" selectionMode="single">
<f:facet name="header">
<p:outputPanel>
<h:outputText value="Search all fields:" />
<p:inputText id="globalFilter" onkeyup="dataTable.filter();" style="width:150px" />
</p:outputPanel>
</f:facet>
<p:column id="datetimeColumn" filterBy="datetime" sortBy="datetime"
headerText="DateTime" footerText=""
filterMatchMode="contains">
<h:outputText value="#{log.datetime}" />
</p:column>
<p:column id="levelColumn" filterBy="level"
headerText="LogLevel" footerText=""
filterOptions="#{tableBean.levelOptions}"
filterMatchMode="exact" sortBy="level">
<h:outputText value="#{log.level}" />
</p:column>
<p:column id="categoryColumn" filterBy="category" sortBy="category"
headerText="Category" footerText=""
filterMatchMode="contains">
<h:outputText value="#{log.category}" />
</p:column>
<p:column id="messageColumn" filterBy="message" sortBy="message"
headerText="Message" footerText="" filterMatchMode="contains">
<h:outputText value="#{log.message}" />
</p:column>
</p:dataTable>
</h:body>
Here my TableBean:
package com.rausch.logreader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import com.rausch.logreader.Log;
#ViewScoped
#ManagedBean(name = "tableBean")
#SessionScoped
public class TableBean implements Serializable {
private final static String[] level;
private SelectItem[] levelOptions;
private List<Log> filteredLogs;
private int i = 0;
private Log selectedLog;
private Log[] selectedLogs;
static {
level = new String[5];
level[0] = "DEBUG";
level[1] = "INFO";
level[2] = "WARN";
level[3] = "ERROR";
level[4] = "FATAL";
}
public TableBean() {
levelOptions = createLevelOptions(level);
}
public Log getSelectedLog() {
return selectedLog;
}
public void setSelectedLog(Log selectedLog) {
this.selectedLog = selectedLog;
}
public void listAdd(List<Log> list, String datetime, String level, String category, String message){
list.add(new Log(datetime, level, category, message));
}
public List<Log> getFilteredLogs() {
return filteredLogs;
}
public void setFilteredLogs(List<Log> filteredCars) {
this.filteredLogs = filteredCars;
}
private SelectItem[] createLevelOptions(String[] data) {
SelectItem[] options = new SelectItem[data.length + 1];
options[0] = new SelectItem("", "Select");
for(int i = 0; i < data.length; i++) {
options[i + 1] = new SelectItem(data[i], data[i]);
}
return options;
}
public SelectItem[] getLevelOptions() {
return levelOptions;
}
}
And here my FileUploadController:
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
#ViewScoped
#ManagedBean(name = "fileUploadController")
#SessionScoped
public class FileUploadController {
public List<Log> logsSmall;
public void handleFileUpload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
} catch (IOException e) {
e.printStackTrace();
}
}
private String destination="C:\\Java\\";
public void copyFile(String fileName, InputStream in) {
try {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(destination + fileName));
int read;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
readFile(destination + fileName);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void readFile(String filePath){
try
{
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader(filePath));
String output;
String datetime = "";
String level = "";
String category = "";
String message;
TableBean table = new TableBean();
while ((sCurrentLine = br.readLine()) != null) {
//System.out.println(sCurrentLine.charAt(4) + "" + sCurrentLine.charAt(7) + sCurrentLine.charAt(13) + "" +sCurrentLine.charAt(16));
if(sCurrentLine.length()<1){
}
else{
if (sCurrentLine.length() >= 16 && sCurrentLine.charAt(4)=='-' && sCurrentLine.charAt(7)=='-' && sCurrentLine.charAt(13)==':' && sCurrentLine.charAt(16)==':'){
output = "";
message = "";
String[] leerzeichen = sCurrentLine.split(" ");
datetime = leerzeichen[0] + " " + leerzeichen[1];
level = leerzeichen[2];
category = leerzeichen[4];
int arraylength = leerzeichen.length;
for (int l=5; l<arraylength; l++){
message = message.concat(leerzeichen[l] + " ");
}
output = datetime + level + category + message;
} else {
message = sCurrentLine;
output = message;
}
logsSmall = new ArrayList<Log>();
table.listAdd(logsSmall, datetime, level, category, message);
System.out.println(output);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sorry for my bad English. I try to Ask an other way:
I want to have a program, where I can upload a *.log File and read it in a table. I open the xhtml, and there is a empty table. Than I Upload the File with the <:pFileUpload. The File Upload Controller takes the Log-File and split each line in the values (datetime, Level, Category and message). Then the Script should add a new row to the table width the datas of the Log-File-Line. Then it goes to the next Line and parses the Text. At the End the Table should show the content of the Log-File.
The Problem is, that the Table don't Reload. Or i don't know how i should reload it. When I upload the File, the script correctly read each Line of the Log-File. But the table keeps empty.
I quite don't understand what is yourt question what i see some lack of understanding on how to use the beans to manage the view.
First, you have #ViewScoped and #SessionScoped declared at the same time. There must be only one.
Second, the thing about defining managed beans it's that you don't have to manage the creation or destruction on them, the system does. Thats why they are called managed. So doing this:
TableBean table = new TableBean();
is useless. You are creating and instance of an object inside a funcion. Outside that function the object is unreacheable, as the annotations aren't considered if you create the object in your code.
I would have one managed bean that handles the events on the view, like this:
#ViewScoped
#ManagedBean(name = "logViewController")
public class LogViewController{
private List<Log> filteredLogs;
private List<Log> logsSmall;
public void handleFileUpload(FileUploadEvent event) {....}
// other private functions
//public getters and setters
}
Also, if you are working with java 7, maybe you want to look at the new file
I/O.

primefaces selectOneMenu not outputting correctly

I am creating a SelectOneMenu. The menu outputs correctly. However, along with the menu being outputted is an InputBox and then all the items of the menu being printed as text. I don't know what is causing it. I have included a image of the output below.
Here is my JSF code:
<p:panelGrid columns="2">
<h:outputLabel for="trader" value="Trader:" />
<p:selectOneMenu id="trader" value="#{fixBean.trader}">
<f:selectItem itemLabel="Select" itemValue="0" />
<f:selectItems value="#{fixBean.traderOption}" />
</p:selectOneMenu>
</p:panelGrid>
Below is the code to my Bean:
private SelectItem[] traderOption = createFilterOptions(traders);
private final static String[] traders;
private static String trader = "";
static {
traders = new String[9];
traders[0] = "Dowd";
traders[1] = "Dwyer";
traders[2] = "Edelman";
traders[3] = "Hughes";
traders[4] = "Kelley";
traders[5] = "Nauyokas";
traders[6] = "Options";
traders[7] = "Rafferty";
traders[8] = "Russillo";
}
public String getTrader() {
return trader;
}
public void setTrader(String trader) {
this.traderOption = trader;
}
public void setTraderOption() {
traderOption = createFilterOptions(traders);
}
private SelectItem[] createFilterOptions(String[] data) {
SelectItem[] options = new SelectItem[data.length + 1];
options[0] = new SelectItem("", "Select");
for(int i = 0; i < data.length; i++) {
options[i + 1] = new SelectItem(data[i], data[i]);
}
return options;
}
public SelectItem[] getTraderOption() {
return traderOption;
}
The SelectMenu has the correct options in it however, I don't know why the rest of the output is being create (i.e. InputBox and text list).
****update****
I rebuilt the page using the primfaces SelectOneMenu example and built out from there. That resolved the issue. Though still not sure what was causing the issue

How to handle unidirectional many-to-many relations with Ebean

I have a problem with Ebean. I have the usual Objects PsecUser, PsecRoles and PsecPermission.
A user can have many Permissions or Roles and a Role can have many Permission.
Here the code (extract):
#Entity
public class PsecPermission {
#Id
#GeneratedValue
private Long id;
#Column(unique=true, nullable=false)
private String name;
#Column(nullable=false)
private String type = PsecBasicPermission.class.getName();
#Column(nullable=false)
private String target;
#Column(nullable=false)
private String actions;
}
#Entity
public class PsecRole {
#Id
#GeneratedValue
private Long id;
#Column(unique=true, nullable=false)
private String name;
#Temporal(TemporalType.TIMESTAMP)
private Date lastUpdate;
#ManyToMany(fetch=FetchType.EAGER)
private List<PsecPermission> psecPermissions;
private boolean defaultRole = false;
}
I wrote the following helper-method:
public PsecRole createOrUpdateRole(String name, boolean defaultRole, String... permissions) {
PsecRole result = server.find(PsecRole.class).
where().eq("name", name).findUnique();
if (result == null) {
result = new PsecRole();
result.setName(name);
}
final List<PsecPermission> permissionObjects = server.find(PsecPermission.class).
where().in("name", (Object[])permissions).findList();
result.setPsecPermissions(permissionObjects);
result.setDefaultRole(defaultRole);
final Set <ConstraintViolation <PsecRole>> errors =
Validation.getValidator().validate(result);
if (errors.isEmpty()) {
server.save(result);
server.saveManyToManyAssociations(result, "psecPermissions");
} else {
log.error("Can't save role: " + name +"!");
for (ConstraintViolation <PsecRole> constraintViolation : errors) {
log.error(" " + constraintViolation);
}
}
return result;
}
and try the following test:
#Test
public void testCreateOrUpdateRole() {
String[] permNames = {"Test1", "Test2", "Test3"};
List <PsecPermission> permissions = new ArrayList <PsecPermission>();
for (int i = 0; i < permNames.length; i++) {
helper.createOrUpdatePermission(permNames[i], "target"+ i, "actions" +i);
PsecPermission perm = server.find(PsecPermission.class).where().eq("name", permNames[i]).findUnique();
assertThat(perm.getTarget()).isEqualTo("target" + i);
assertThat(perm.getActions()).isEqualTo("actions" + i);
permissions.add(perm);
}
PsecRole orgRole = helper.createOrUpdateRole(ROLE, false, permNames);
testRole(permNames, orgRole);
PsecRole role = server.find(PsecRole.class).where().eq("name", ROLE).findUnique();
testRole(permNames, role);
}
private void testRole(String[] permNames, PsecRole role) {
assertThat(role).isNotNull();
assertThat(role.getName()).isEqualTo(ROLE);
assertThat(role.isDefaultRole()).isEqualTo(false);
assertThat(role.getPermissions()).hasSize(permNames.length);
}
Which fails if it checks the number of permissions at the readed role. It's always 0.
I looked into the database and found that psec_role_psec_permission is alway empty.
Any idea what's wrong with the code?
You can get a pure Ebean-example from https://github.com/opensource21/ebean-samples/downloads it uses the eclipse-plugin from ebean.
There are two solutions for this problem:
Simply add cascade option at PsceRole
#ManyToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
private List<PsecPermission> psecPermissions;
and remove server.saveManyToManyAssociations(result, "psecPermissions"); you find it in the cascade-solution-branch.
The cleaner solution, because you don't need to define cascase- perhaps you don't want it:
Just don't replace the list, just add your entries to the list. Better is to add new and remove old one. This mean in createOrUpdateRole:
result.getPsecPermissions().addAll(permissionObjects);
instead of
result.setPsecPermissions(permissionObjects);