I am creating a program that takes an address that the user inputs, and using GeoCoder, places that address on a map. This is done through oracle adf thematic map and java for the backing bean. The issue I'm getting is that the input works, but only if there are no spaces in the user's input. When an input is entered that DOES have a space, I get this error:
<oracle.adf.view> <PartialResponseUtils> <handleError> <ADF_FACES-60096:Server Exception during PPR, #1>
javax.el.ELException: .../map.jsf #76,86 pointX="#{row.lattitude}": java.lang.NullPointerException
Since GeoCoder doesn't care about spaces, I'm guessing the error is in the map code? Here's the code for the map jsf page:
<af:form id="f1">
<af:panelStretchLayout topHeight="50px" id="psl1">
<f:facet name="top">
<af:panelHeader text="Regional Map" id="ph1">
<f:facet name="context"/>
<f:facet name="menuBar"/>
<f:facet name="toolbar"/>
<f:facet name="legend"/>
<f:facet name="info"/>
</af:panelHeader>
</f:facet>
<f:facet name="center">
<af:panelSplitter id="ps1" splitterPosition="289">
<f:facet name="first">
<af:decorativeBox id="db1">
<f:facet name="center">
<af:panelGroupLayout layout="scroll" id="pgl1">
<af:panelFormLayout id="pfl1">
<f:facet name="footer">
<af:commandButton text="Add Location" id="cb1" partialSubmit="true"
actionListener="#{locationsCollector.addCurrentLocation}"/>
</f:facet>
<af:inputText label="Label" id="it1" autoSubmit="true"
value="#{currentLocation.label}"/>
<af:inputText label="Description" id="it1a" autoSubmit="true"
value="#{currentLocation.description}"/>
<af:inputText label="Location (NO SPACES)" id="it2" autoSubmit="true"
value="#{currentLocation.location}"/>
</af:panelFormLayout>
<af:spacer id="spac1" height="40"/>
<af:table value="#{locationsCollector.locations}" var="row"
rowBandingInterval="0" id="t1" partialTriggers="::cb1">
<af:column sortable="false" headerText="Label" align="start" id="c1">
<af:outputText value="#{row.label}" id="ot1"
shortDesc="#{row.description}"/>
</af:column>
<af:column sortable="false" headerText="Description" align="start" id="c2">
<af:outputText value="#{row.description}" id="ot2"/>
</af:column>
<!--<af:column sortable="false" headerText="Country" align="start" id="c3">
<af:outputText value="#{row.country}" id="ot3"/>
</af:column>-->
</af:table>
</af:panelGroupLayout>
</f:facet>
<!--<f:facet name="top">
<af:panelHeader text="Enter location details" id="ph2">
<f:facet name="context"/>
<f:facet name="menuBar"/>
<f:facet name="toolbar"/>
<f:facet name="legend"/>
<f:facet name="info"/>
</af:panelHeader>
</f:facet>-->
</af:decorativeBox>
</f:facet>
<f:facet name="second">
<dvt:thematicMap basemap="usa" id="tm1" partialTriggers="::cb1" summary="map">
<dvt:areaLayer layer="states" id="al1" rendered="true">
<dvt:pointDataLayer id="pdl1c" value="#{locationsCollector.locations}" var="row">
<dvt:pointLocation id="pl1c" type="pointXY" pointX="#{row.lattitude}"
pointY="#{row.longitude}">
<dvt:marker id="m1c" labelDisplay="on" value="#{row.label}"
labelPosition="top"
shortDesc="#{row.description} #{row.location} "/>
</dvt:pointLocation>
</dvt:pointDataLayer>
</dvt:areaLayer>
</dvt:thematicMap>
</f:facet>
</af:panelSplitter>
<!-- id="af_one_column_header_stretched" -->
</f:facet>
</af:panelStretchLayout>
</af:form>
And here is the bean for getting the latitude and longitude from Geocoder to add to the map's point detail:
public class Location {
private String location;
private String country;
private String label;
private String description;
private float[] coordinates;
private static float[] getCoordinatesForLocation(String location) {
URL geoCodeUrl;
String url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + location
+ "&oe=utf8&sensor=false";
try {
geoCodeUrl
= new URL(url);
} catch (MalformedURLException e) {
System.out.println(e.getMessage() + " url=" + url);
return null;
}
BufferedReader in;
String coord = null;
try {
in = new BufferedReader(new InputStreamReader(geoCodeUrl.openStream()));
char[] buf = new char[8000];
in.read(buf);
coord = new StringBuilder().append(buf).toString();
in.close();
} catch (IOException e) {
System.out.println(e.getMessage() + " IO Exception ");
return null;
}
if (coord != null) {
float[] coordinates;
try {
// find first occurrence of lat
int posLAT = coord.indexOf("\"lat\"");
String latString = coord.substring(posLAT, posLAT + 21);
String lat = latString.split(":")[1].replaceAll(" ", "").replaceAll(",", "");
// find first occurrence of lng
int posLNG = coord.indexOf("\"lng\"");
String lngString = coord.substring(posLNG, posLNG + 21);
String lng = lngString.split(":")[1].replaceAll(" ", "").replaceAll(",", "");
coordinates
= new float[]{Float.parseFloat(lat), Float.parseFloat(lng)};
return coordinates;
} catch (Exception e) {
System.out.println("Coordinates stank " + coord);
}
}
System.out.println("Failed to create proper coordinates; sorry!");
return null;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountry() {
return country;
}
public void setLabel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public void setCoordinates(float[] coordinates) {
this.coordinates = coordinates;
}
public float[] getCoordinates() {
if (coordinates == null) {
coordinates = getCoordinatesForLocation(location);
}
return coordinates;
}
public float getLongitude() {
return getCoordinates()[0];
}
public float getLattitude() {
return getCoordinates()[1];
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
All I'm looking for is the ability for the program to accept an address with spaces so the program is more user friendly. Thanks for looking this over!
Related
I have two combo boxes. The items of the second one are retrieved using the selected value of the first one. When the default empty value is selected in the first combo box, the second combo box is not rendered.
Everything works well except for one scenario :
select a value in the first combo box -> the second combo box appears
select a value in the second combo box
select the default empty value in the first combo box -> the second combo box disappears
select the same value that was selected at step 1 in the first combo box
The second combo box should appear with the empty default value selected, but instead displays the value that was selected at step 2.
If I select a different value at step 4, the second combo box is loaded correctly, with the default empty value selected.
The view :
<ui:composition template="/pages/include/templatePrincipal.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui" xmlns:d="http://iec.composants"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core">
<ui:define name="pageActive">
<f:view>
<h:form>
<p:panel id="panelModifierUnParametreFonctionnel"
header="LISTE DES FE FILLES ORPHELINES">
<h:panelGrid columns="6">
<p:outputLabel
value="#{feFillesOrphelinesBean.labelComboRegion}" />
<p:selectOneMenu
value="#{feFillesOrphelinesBean.regionOption}"
valueChangeListener="#{feFillesOrphelinesBean.regionChanged}"
onchange="submit()">
<f:selectItems value="#{feFillesOrphelinesBean.listRegion}" />
</p:selectOneMenu>
<p:outputLabel
value="#{feFillesOrphelinesBean.labelComboCorps}"
rendered="#{feFillesOrphelinesBean.rendreComboCorps}" />
<p:selectOneMenu
value="#{feFillesOrphelinesBean.corpsOption}"
rendered="#{feFillesOrphelinesBean.rendreComboCorps}"
valueChangeListener="#{feFillesOrphelinesBean.corpsChanged}"
onchange="submit()">
<f:selectItems value="#{feFillesOrphelinesBean.listCorps}" />
</p:selectOneMenu>
</h:panelGrid>
</p:panel>
</h:form>
</f:view>
</ui:define>
</ui:composition>
The java bean :
public class FEFillesOrphelinesBean implements Serializable {
public final static String LABEL_COMBO_REGION = "Chaîne fonctionnelle :";
public final static String LABEL_COMBO_CORPS = "Corps :";
private String labelComboRegion;
private String labelComboCorps;
private List<SelectItem> listRegion;
private Integer regionOption;
private List<SelectItem> listCorps;
private Integer corpsOption;
private Boolean rendreComboCorps;
public String init() {
this.chargerRegions();
this.chargerCorps();
this.setLabelComboRegion(LABEL_COMBO_REGION);
this.setLabelComboCorps(LABEL_COMBO_CORPS);
return "success";
}
public void chargerRegions() {
this.setListRegion(new ArrayList<>());
this.setRegionOption(new Integer(-1));
RegionAdmin[] tabRegions = ServiceFactory.getInstance().getGestionRegionSrv().findAll();
this.getListRegion().add(new SelectItem(new Integer(-1), " "));
for (RegionAdmin region : tabRegions) {
SelectItem regionItem = new SelectItem(region.getId(), region.getLib() + ": " + region.getLibelle());
this.getListRegion().add(regionItem);
}
}
public void chargerCorps() {
this.setListCorps(new ArrayList<>());
this.setCorpsOption(new Integer(-1));
if (this.getRegionOption().equals(new Integer(-1))) {
this.setRendreComboCorps(false);
} else {
Corps[] tabCorps = ServiceFactory.getInstance().getGestionCorpsSrv().findCorps(this.getRegionOption());
this.getListCorps().add(new SelectItem(new Integer(-1), " "));
for (Corps corps : tabCorps) {
SelectItem corpsItem = new SelectItem(corps.getId(), corps.getLib() + ": " + corps.getLibelle());
this.getListCorps().add(corpsItem);
}
this.setRendreComboCorps(true);
}
}
public void regionChanged(ValueChangeEvent event) {
Integer newRegionOption = (Integer) event.getNewValue();
this.setRegionOption(newRegionOption);
this.chargerCorps();
}
public void corpsChanged(ValueChangeEvent event) {
Integer newCorpsOption = (Integer) event.getNewValue();
this.setCorpsOption(newCorpsOption);
}
public String getLabelComboRegion() {
return labelComboRegion;
}
public void setLabelComboRegion(String labelComboRegion) {
this.labelComboRegion = labelComboRegion;
}
public String getLabelComboCorps() {
return labelComboCorps;
}
public void setLabelComboCorps(String labelComboCorps) {
this.labelComboCorps = labelComboCorps;
}
public List<SelectItem> getListRegion() {
return listRegion;
}
public void setListRegion(List<SelectItem> listRegion) {
this.listRegion = listRegion;
}
public Integer getRegionOption() {
return regionOption;
}
public void setRegionOption(Integer regionOption) {
this.regionOption = regionOption;
}
public List<SelectItem> getListCorps() {
return listCorps;
}
public void setListCorps(List<SelectItem> listCorps) {
this.listCorps = listCorps;
}
public Integer getCorpsOption() {
return corpsOption;
}
public void setCorpsOption(Integer corpsOption) {
this.corpsOption = corpsOption;
}
public Boolean getRendreComboCorps() {
return rendreComboCorps;
}
public void setRendreComboCorps(Boolean rendreComboCorps) {
this.rendreComboCorps = rendreComboCorps;
}
}
As you can see, the regionChanged method is called when the selected value of the first combo box changes, then it calls the chargerCorps method which set the corpsOption to the -1 default value. This means that in the scenario that I've described, the displayed selected value is not the same as the selected value in the bean, which can cause a lot of issues.
I have a Primefaces 6.0 DataTable working with a LazyDataModel bean. After I changed to the lazy implementation, the cell edition stopped working.
The reason for that is whenever I call my onCellEdit method, and try to get the clicked row contents by calling event.getRowkey() , I get a null object.
As per Primefaces Documentation I'm have a rowKey attribute to bind the tuple with the bean value, but it doesn't seems to work.
EDIT: I can update the value now, but the dataTable doesn't reload the cell UiElement. To see the changes i have to F5 the page.
Here is my ata.xhtml DATATABLE(Sanitized)
<p:tabView id="tab" value="#{setorMB.listaSetor}" var="tabView"
activeIndex="#{ataGerencialMB.activeTabIndex}">
<p:ajax event="tabChange" listener="#{ataGerencialMB.onTabChange}"
update="tab ,formListagemCapacitacao" />
<p:tab title="#{tabView.sigla}">
<p:dataTable id="dtCapacitacao"
value="#{ataGerencialMB.lazyModelAtaGerencial}"
var="gerencial"
lazy="true"
paginator="true"
rows="#{Config.NUM_ROWS}"
currentPageReportTemplate="#{Config.CURRENT_PAGE_REPORT_TEMPLATE}"
paginatorTemplate="#{Config.PAGINATOR_TEMPLATE}"
rowsPerPageTemplate="#{Config.ROWS_PER_PAGE_TEMPLATE}"
sortBy="#{gerencial.idAta}"
sortOrder="ascending"
reflow="true"
editable="true"
editMode="cell"
rowKey="#{gerencial.idAta}">
<p:ajax event="cellEdit"
listener="#{ataGerencialMB.onCellEdit}" oncomplete="onCellEdit()"/>
<p:column>
<p:rowToggler/>
</p:column>
<p:column headerText="Tipo Assunto" >
<p:cellEditor>
<f:facet name="output">
<h:outputText value="#{gerencial.tipo}"
rendered="true" />
</f:facet>
<f:facet name="input">
<p:inputTextarea id="tipo"
value="#{gerencial.tipo}"
style="width:96%" />
</f:facet>
</p:cellEditor>
</p:column>
</p:dataTable>
</p:tab>
</p:tabView>
Class that extends the LazyDataModel AtaGerencialLazyDataModel
public class AtaGerencialLazyDataModel extends LazyDataModel<AtaGerencialBean> {
AtaGerencialBusiness ataBusiness = new AtaGerencialBusiness();
Map<String, Object> customFilters = new HashMap<String, Object>();
private List<AtaGerencialBean> listaAtaGerencialBean = new ArrayList<AtaGerencialBean>();
public AtaGerencialLazyDataModel(){
this.setRowCount(ataBusiness.getAtaGerencialTotalCount(null));
}
public AtaGerencialLazyDataModel(SetorBean setor){
customFilters.put("setor", setor);
this.setRowCount(ataBusiness.getAtaGerencialTotalCount(customFilters));
}
#Override
public List<AtaGerencialBean> load(int first, int pageSize, String sortField,
SortOrder sortOrder, Map<String, Object> filters){
List<AtaGerencialBean> list = ataBusiness.fetchLazyAtaGerencial(first, pageSize, sortField, sortOrder, customFilters);
this.setRowCount(ataBusiness.getAtaGerencialTotalCount(customFilters));
setListaAtaGerencialBean(list);
setWrappedData(list);
return list;
}
#Override
public AtaGerencialBean getRowData(String rowKey){
try{
long id = Long.parseLong(rowKey);
for (AtaGerencialBean bean : listaAtaGerencialBean) {
if (bean.getIdAta() == id){
return bean;
}
}
}catch(Exception e){
System.out.println(e.getMessage());
}
return null;
}
#Override
public Object getRowKey(AtaGerencialBean p) {
return p.getIdAta();
}
public List<AtaGerencialBean> getListaAtaGerencialBean() {
return listaAtaGerencialBean;
}
public void setListaAtaGerencialBean(
List<AtaGerencialBean> listaAtaGerencialBean) {
this.listaAtaGerencialBean = listaAtaGerencialBean;
}
}
The onCellEdit method
#ManagedBean
#ViewScoped
public class AtaGerencialMB extends MB<AtaGerencialBean,
AtaGerencialBusiness> {
private LazyDataModel<AtaGerencialBean> lazyModelAtaGerencial;
#SuppressWarnings("unused")
public void onCellEdit(CellEditEvent event) {
try{
DataTable controladorTabela = (DataTable) event.getComponent();
//rowindex is fine, it brings the index of the edited row in the
datatable (from 0 onwards)
Integer rowIndex = event.getRowIndex();
String rowKey = event.getRowKey();
//rowKey is always null
System.out.println("rowKey value:" + rowKey);
AtaGerencialBean entity = (AtaGerencialBean) controladorTabela.getRowData(event.getRowKey());
this.setRegistroDefinido(entity);
super.atualizar();
}catch(NullPointerException ex){
System.out.println(ex.getMessage());
}
}
}
EDIT
I was able to circumvent the problem by NOT using the rowKey to retrieve the data and modifying the onCellEdit method to get the data from the Datamodel inside the Datatable.
I am not sure whether it is a good/bad practice, or if that's how you're supposed to retrieve the row when using LazyLoading.
Also, following #Kukeltje suggestion, I am now using PRIMEFACES 6.2
Modified onCellEdit method
#ManagedBean
#ViewScoped
public class AtaGerencialMB extends MB<AtaGerencialBean, AtaGerencialBusiness> {
private LazyDataModel<AtaGerencialBean> lazyModelAtaGerencial;
#SuppressWarnings("unused")
public void onCellEdit(CellEditEvent event) {
try{
DataTable controladorTabela = (DataTable) event.getComponent();
DataModel dm = (DataModel) controladorTabela.getValue();
AtaGerencialBean entity = (AtaGerencialBean) dm.getRowData();
this.setRegistroDefinido(entity);
super.atualizar();
}catch(NullPointerException ex){
System.out.println(ex.getMessage());
}
}
}
I was able to circumvent the problem by NOT using the rowKey to retrieve the data and modifying the onCellEdit method to get the data from the Datamodel inside the Datatable.
I am not sure whether it is a good/bad practice, or if that's how you're supposed to retrieve the row when using LazyLoading.
Also, following #Kukeltje suggestion, I am now using PRIMEFACES 6.2
Modified onCellEdit method
#SuppressWarnings("unused")
public void onCellEdit(CellEditEvent event) {
try{
DataTable controladorTabela = (DataTable) event.getComponent();
DataModel dm = (DataModel) controladorTabela.getValue();
AtaGerencialBean entity = (AtaGerencialBean) dm.getRowData();
this.setRegistroDefinido(entity);
super.atualizar();
}catch(NullPointerException ex){
System.out.println(ex.getMessage());
}
}
https://github.com/primefaces/primefaces/issues/2688
You may refer to this issue on github. You should enable selection for your datatable
chart
"Nível" and "Nivel".
i want only one legend. but i have two being generated. what is going on? who resolve this problem?
another problem, i already put details in this post, who much details i need to post...
xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html 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"
xmlns:namespace="http://java.sun.com/jsf/composite/namespace"
xmlns:sec="http://www.springframework.org/security/facelets/tags">
<ui:composition template="Template.xhtml">
<ui:define name="content">
<div class="content_wrapper">
<div class="content">
<h:form id="formtest">
<p:growl id="meuGrowl" />
<p:poll interval="5" listener="#{PortaBean.verificarplaca}"
update="meuGrowl" />
</h:form>
<h:form id="formtest1">
<p:growl id="meuGrowl1" />
<p:poll interval="60" listener="#{PortaBean.Grafico}"
update="meuGrowl1" />
</h:form>
<h:form id="formtest2">
<p:growl id="meuGrowl2" />
<p:poll interval="5" listener="#{PortaBean.verificarPorta}"
update="meuGrowl2" />
</h:form>
<h:form id="formGrid">
<p:selectOneMenu value="#{chartView.reservatorio.idReservatorio}"
style="width:170px" required="true"
requiredMessage="Selecione algum.">
<f:selectItem itemLabel="Selecione o Reservatório" itemValue="0" />
<f:selectItems value="#{chartView.listaReservatorio}"
var="reservatorio" itemLabel="#{reservatorio.nomeReservatorio}"
itemValue="#{reservatorio.idReservatorio}" />
</p:selectOneMenu>
<p:calendar id="popup" value="#{chartView.data}" />
<p:commandButton value="Gerar gráfico" update="chart"
actionListener="#{chartView.LinearModel}" />
<p:chart id="chart" type="line" model="#{chartView.lineModel1}"
style="height:300px;" />
</h:form>
</div>
</div>
</ui:define>
</ui:composition>
</html>
Bean:
#ManagedBean
public class ChartView implements Serializable {
private Grafico grafico = new Grafico();
private GraficoCrudAnnotations graficoDAO = new GraficoCrudAnnotations();
private List<Grafico> listaGrafico = new ArrayList<>();
private List<Grafico> listaGraficoFinal = new ArrayList<>();
private Reservatorio reservatorio = new Reservatorio();
private Reservatorio reservatorio1 = new Reservatorio();
private List<Reservatorio> listaReservatorio = new ArrayList<>();
private ReservatorioCrudAnnotations reservatorioDAO = new ReservatorioCrudAnnotations();
private Date data;
private LineChartModel lineModel1;
private GraficoBean Gb = new GraficoBean();
#PostConstruct
public void init() {
LinearModel();
}
public LineChartModel getLineModel1() {
return lineModel1;
}
private List<Grafico> Grafico = new ArrayList<>();
public List<Grafico> getGrafico() {
return Grafico;
}
public void setGrafico(List<Grafico> grafico) {
Grafico = grafico;
}
public void refreshChart() {
GraficoBean Gb = new GraficoBean();
Gb.gerarGrafico();
}
private void createLineModels() {
System.out.println("createLineModels()");
lineModel1 = (LineChartModel) LinearModel();
lineModel1.setTitle("Gráfico de Reservatório");
lineModel1.setLegendPosition("e");
Axis yAxis = lineModel1.getAxis(AxisType.Y);
yAxis.setLabel("Nível");
yAxis.setMin(0);
yAxis.setMax(100);
Axis xAxis = lineModel1.getAxis(AxisType.X);
xAxis.setLabel("Hora do dia");
xAxis.setMin(0);
xAxis.setMax(23);
xAxis.setTickInterval("1");
}
public CartesianChartModel LinearModel() {
LineChartModel model = new LineChartModel();
LineChartSeries series1 = new LineChartSeries();
// try{
// if(series1.getLabel().equalsIgnoreCase("Nivel"))
// {
// System.out.println("já existe legenda");
//
// }
// }
//
// catch(Exception e){
//
//
//
try{
LegendPlacement OUTSIDE=LegendPlacement.OUTSIDE;
series1.set(0, 0);
//series1.set(0, 0);
model.addSeries(series1);
series1.setLabel("Nível");
series1.setFill(true);
lineModel1 =(LineChartModel) model;
//lineModel1.setSeriesColors("58BA27,FFCC33,F74A4A,F52F2F,A30303");
//lineModel1.setExtender("chartExtender");
lineModel1.setTitle("Gráfico de Reservatório");
lineModel1.setLegendPlacement(OUTSIDE);
lineModel1.setLegendPosition("e");
Axis yAxis = lineModel1.getAxis(AxisType.Y);
yAxis.setMin(0);
yAxis.setMax(100);
yAxis.setLabel("Nível");
Axis xAxis = lineModel1.getAxis(AxisType.X);
xAxis.setLabel("Hora do dia");
xAxis.setMin(0);
xAxis.setMax(23);
xAxis.setTickInterval("1");
int nivel;
System.out.println("AQUI:: "+listaReservatorio.size());
try
{
System.out.println("Id do reservatorio: "+reservatorio.getIdReservatorio());
DateFormat dataFormatada = new SimpleDateFormat("dd/MM/yyyy");
for (int i = 0; i < listaReservatorio.size(); i++) {
if (listaReservatorio.get(i).getIdReservatorio() == reservatorio
.getIdReservatorio()) {
reservatorio1 = listaReservatorio.get(i);
}
}
System.out.println("graficoDAO: "+graficoDAO.listar().size());
listaGrafico = graficoDAO.listar();
System.out.println("Meu reservatorio: "+reservatorio1.getNomeReservatorio());
String date;
for (int i = 0; i < listaGrafico.size(); i++) {
date = listaGrafico.get(i).getData().substring(0, 10);
if ((listaGrafico.get(i).getReservatorio().getIdReservatorio() == reservatorio1.getIdReservatorio()) && (dataFormatada.format(data).equalsIgnoreCase(date)) ) {
System.out.println("Dentro do IF: "+i);
listaGraficoFinal.add(listaGrafico.get(i));
System.out.println("Dentro do IF");
}
}
System.out.println("Lista Grafico final size: "+ listaGraficoFinal.size());
}catch(Exception e)
{
System.out.println("É NULA: "+e.getCause());
e.printStackTrace();
listaGraficoFinal=null;
}
System.out.println("InitLinear aqui");
if (listaGraficoFinal != null) {
System.out.println("AQUI O QUE INTERESSA Não é null");
try {
System.out.println("Tamanho:" + listaGraficoFinal.size());
for (int i = 23; i >= 0; i--) {
//System.out.println("Nivel: " + listaGraficoFinal.get(i).getNivel());
//System.out.println("Data: "
// + listaGraficoFinal.get(i).getData().substring(11, 13));
int x =listaGraficoFinal.get(i).getNivel();
int y =Integer.parseInt(listaGraficoFinal.get(i).getData().substring(11, 13));
System.out.println("X : "+x);
System.out.println("Y : "+y);
System.out.println("========================");
series1.set(y,x);
}
//series1.set(20, 20);
} catch (Exception e) {
System.out.println("Erro aqui 1: " + e.getCause());
System.out.println("Erro 2: ");
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage(null,new FacesMessage("Não existe informação o suficiente no banco para gerar o gráfico."));
}
} else {
System.out.println("Aqui é null");
series1.set(0, 0);
series1.set(0, 0);
}
}catch(Exception e){
FacesContext
.getCurrentInstance()
.addMessage(
null,
new FacesMessage(
"Selecione uma data em que exista informação."));
}
model.addSeries(series1);
return model;
}
public GraficoCrudAnnotations getGraficoDAO() {
return graficoDAO;
}
public void setGraficoDAO(GraficoCrudAnnotations graficoDAO) {
this.graficoDAO = graficoDAO;
}
public List<Grafico> getListaGrafico() {
return listaGrafico;
}
public void setListaGrafico(List<Grafico> listaGrafico) {
this.listaGrafico = listaGrafico;
}
public List<Grafico> getListaGraficoFinal() {
return listaGraficoFinal;
}
public void setListaGraficoFinal(List<Grafico> listaGraficoFinal) {
this.listaGraficoFinal = listaGraficoFinal;
}
public Reservatorio getReservatorio() {
return reservatorio;
}
public void setReservatorio(Reservatorio reservatorio) {
this.reservatorio = reservatorio;
}
public Reservatorio getReservatorio1() {
return reservatorio1;
}
public void setReservatorio1(Reservatorio reservatorio1) {
this.reservatorio1 = reservatorio1;
}
public List<Reservatorio> getListaReservatorio() {
return listaReservatorio=reservatorioDAO.listar();
}
public void setListaReservatorio(List<Reservatorio> listaReservatorio) {
this.listaReservatorio = listaReservatorio;
}
public ReservatorioCrudAnnotations getReservatorioDAO() {
return reservatorioDAO;
}
public void setReservatorioDAO(ReservatorioCrudAnnotations reservatorioDAO) {
this.reservatorioDAO = reservatorioDAO;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
public void setGrafico(Grafico grafico) {
this.grafico = grafico;
}
It seems to me you have the line
model.addSeries(series1);
twice. I guess that would explain it.
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;
}
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.