Chart line, one line but two Subtitles? - primefaces

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.

Related

MvvmCross Android: Linking kills SwitchCompat.Checked propety

I have layout with SwitchCompat binding to ViewModel
<android.support.v7.widget.SwitchCompat
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
app:MvxBind="Checked FlashlightEnabled;
Click FlashlightCheckedCommand"/>
I also add in LinkerPleaseInclude.cs file some Include methods
public void Include(Switch s)
{
s.CheckedChange += (sender, args)
=> s.Checked = !s.Checked;
s.Checked = true;
}
public void Include(SwitchCompat sc)
{
sc.CheckedChange += (sender, args)
=> sc.Checked = !sc.Checked;
sc.Checked = true;
}
But when I set the Sdk and User Assemblies linking, my Checked binding is removed.
Output Message:
2018-10-16 12:31:17 [WARN] (MvxBind) Failed to create target binding for binding Checked for FlashlightEnabled10-16 12:31:17.143 I/mono-stdout( 5716): at System.Activator.CreateInstance (System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Object[]
Make sure you've added [Android.Runtime.Preserve(AllMembers = true)] to your LinkerPleaseInclude class. If not the class will be ignored.
Here you have the latest LinkerPleaseInclude please be sure you have the same:
using Android.App;
using Android.Views;
using Android.Widget;
using MvvmCross.Binding.BindingContext;
using MvvmCross.Navigation;
using MvvmCross.ViewModels;
using System;
using System.Collections.Specialized;
using System.Windows.Input;
namespace $YourNameSpace$
{
// This class is never actually executed, but when Xamarin linking is enabled it does how to ensure types and properties
// are preserved in the deployed app
[Android.Runtime.Preserve(AllMembers = true)]
public class LinkerPleaseInclude
{
public void Include(Button button)
{
button.Click += (s, e) => button.Text = button.Text + "";
}
public void Include(CheckBox checkBox)
{
checkBox.CheckedChange += (sender, args) => checkBox.Checked = !checkBox.Checked;
}
public void Include(Switch #switch)
{
#switch.CheckedChange += (sender, args) => #switch.Checked = !#switch.Checked;
}
public void Include(View view)
{
view.Click += (s, e) => view.ContentDescription = view.ContentDescription + "";
}
public void Include(TextView text)
{
text.AfterTextChanged += (sender, args) => text.Text = "" + text.Text;
text.Hint = "" + text.Hint;
}
public void Include(CheckedTextView text)
{
text.AfterTextChanged += (sender, args) => text.Text = "" + text.Text;
text.Hint = "" + text.Hint;
}
public void Include(CompoundButton cb)
{
cb.CheckedChange += (sender, args) => cb.Checked = !cb.Checked;
}
public void Include(SeekBar sb)
{
sb.ProgressChanged += (sender, args) => sb.Progress = sb.Progress + 1;
}
public void Include(RadioGroup radioGroup)
{
radioGroup.CheckedChange += (sender, args) => radioGroup.Check(args.CheckedId);
}
public void Include(RadioButton radioButton)
{
radioButton.CheckedChange += (sender, args) => radioButton.Checked = args.IsChecked;
}
public void Include(RatingBar ratingBar)
{
ratingBar.RatingBarChange += (sender, args) => ratingBar.Rating = 0 + ratingBar.Rating;
}
public void Include(Activity act)
{
act.Title = act.Title + "";
}
public void Include(INotifyCollectionChanged changed)
{
changed.CollectionChanged += (s, e) => { var test = $"{e.Action}{e.NewItems}{e.NewStartingIndex}{e.OldItems}{e.OldStartingIndex}"; };
}
public void Include(ICommand command)
{
command.CanExecuteChanged += (s, e) => { if (command.CanExecute(null)) command.Execute(null); };
}
public void Include(MvvmCross.IoC.MvxPropertyInjector injector)
{
injector = new MvvmCross.IoC.MvxPropertyInjector();
}
public void Include(System.ComponentModel.INotifyPropertyChanged changed)
{
changed.PropertyChanged += (sender, e) =>
{
var test = e.PropertyName;
};
}
public void Include(MvxTaskBasedBindingContext context)
{
context.Dispose();
var context2 = new MvxTaskBasedBindingContext();
context2.Dispose();
}
public void Include(MvxNavigationService service, IMvxViewModelLoader loader)
{
service = new MvxNavigationService(null, loader);
}
public void Include(ConsoleColor color)
{
Console.Write("");
Console.WriteLine("");
color = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.ForegroundColor = ConsoleColor.Magenta;
Console.ForegroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Gray;
Console.ForegroundColor = ConsoleColor.DarkGray;
}
}
}

Error parsing data JSON, Fragment Android Studio

Someone please help me why my result always error parsing data ?
My app run smoothly but does not display anything. i feel so stuck here.
this is my code
Sorry for bad english
API JSON
public function getkategori2(){
$data = array();
$token = $this->input->post('f_token');
$tabel = $this->input->post('f_tabel');
if ($token == '' || $tabel == ''){
$data['result'] = false;
$data['msg'] = "Data Kosong";
echo json_encode($data);
return;
}
$sql = 'SELECT * FROM '.$tabel.'_kategori INNER JOIN files WHERE '.$tabel.'_kategori.id_kategori = files.id_kategori';
$q = $this->db->query($sql);
if ($q->num_rows()>0) {
foreach ($q->result() as $value) {
$kategori = array(
'nama_kategori' => $value->nama_kategori,
'file_name' => $value->file_name,
);
};
$data['result'] = true;
$data['kategori_data'] = $kategori;
$data['msg'] = '';
} else {
$data['result'] = false;
$data['msg'] = 'error';
}
echo json_encode($data);
}
JSON Result
{
"result":true,
"kategori_data":
{
"nama_kategori":"Pasta",
"file_name":"1_Pasta.jpg"
},
"msg":""
}
KategoriAdapter
public class KategoriAdapter extends RecyclerView.Adapter<KategoriAdapter.ViewHolder> {
private ArrayList<Kategori> mData;
private Context context;
private SessionManager sesi;
public KategoriAdapter (Context context, ArrayList<Kategori> mData){
this.context = context;
this.mData = mData;
}
#Override
public KategoriAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view = LayoutInflater.from(context)
.inflate(R.layout.item_list_kategori, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(KategoriAdapter.ViewHolder holder, int position) {
Kategori k = mData.get(position);
String kategori = k.getKategoriNama();
String gambar = k.getImg();
//masukan kedalam object viewholder
holder.tvKategori.setText(kategori);
Picasso.with(context)
.load(Constant.BASE_IMAGE + sesi.getTabel() + "/kategori/" + gambar)
.into(holder.ivKategori);
}
//buta object interface onAdapterjabatanListener
private OnAdapterListener listener;
//buat method untuk mendefiniskan listenernya
public void setListener(OnAdapterListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
return mData == null ? 0 : mData.size();
}
//buat class yang extend dari ViewHolder
class ViewHolder extends RecyclerView.ViewHolder{
public LinearLayout container;
public TextView tvKategori;
public ImageView ivKategori;
public ViewHolder(View v){
super(v);
//baru hubungkan variablenya dengan item yang ada di class layout item
container = v.findViewById(R.id.container);
tvKategori = v.findViewById(R.id.tvKategori);
ivKategori = v.findViewById(R.id.ivKategori);
}
}
KategoriFragment
public class KategoriFragment extends Fragment {
SessionManager sesi;
private ArrayList<Kategori> data;
private OkHttpClient okClient;
private RecyclerView rvData;
public KategoriFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_kategori, container, false);
sesi = new SessionManager(getActivity());
data = new ArrayList<>();
okClient = new OkHttpClient();
rvData = rootView.findViewById(R.id.rvData);
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity());
rvData.setLayoutManager(manager);
getData();
return rootView;
}
private void getData(){
data.clear();
String url = Constant.BASE_URL + "getkategori2";
FormBody parameters = new FormBody.Builder()
.add("f_token", sesi.getToken())
.add("f_tabel", sesi.getTabel())
.build();
//buat request untuk ambil data
Request request = new Request.Builder()
.url(url)
.post(parameters)
.build();
okClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
e.printStackTrace();
RbHelpers.pesan(getActivity(),
"error :" + e.getMessage());
}
});
}
#Override
public void onResponse(Call call,final Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//hilangkan dialognya
}});
final String responData = response.body().string();
RbHelpers.pre("respon data : " + responData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//debug hasilnya kedalam android monitor
try {
//parsing json
try {
JSONObject json = new JSONObject(responData);
Log.d("tagJSON",json.toString());
//check hasilnya apakah true or false
boolean hasil = json.getBoolean("result");
if (hasil){
//ada datanya
//buat object jsonArray
JSONArray jArray = json.getJSONArray("kategori_data");
//looping data dan masukkan kedalam arraylist
for (int i = 0; i < jArray.length(); i++){
JSONObject jObj = jArray.getJSONObject(i);
Kategori kategori = new Kategori();
kategori.setKategoriNama(jObj.getString("nama_kategori"));
kategori.setImg(jObj.getString("file_name"));
//tinggal masukan ke arraylist
data.add(kategori);
}
} else {
String msg = json.getString("msg");
RbHelpers.pesan(getActivity(), msg);
}
//tinggal masukin ke recylerview
//UserAdapter adapter = new UserAdapter
KategoriAdapter adapter = new KategoriAdapter(getActivity(), data);
rvData.setAdapter(adapter);
} catch (JSONException e){
RbHelpers.pesan(getActivity(), "Error parsing data");
e.printStackTrace();
}
} catch (Exception e) {
RbHelpers.pesan(getActivity(), "Error ambil data");
e.printStackTrace();
}
}
});
}
});
}
Think this is the wrong part "kategori_data" is a JSONObject , not a JSONArray, Check the correct format in jsonBlob as
Here you have an example of a mine working project where i have a model Articulo(Product) and I make a request to retrieve that object data
try{
// Get the JSON array
JSONObject result = response.getJSONObject("articulo");
int i ;
for(i=0;i<1;i++){
JSONObject articulo = result;
ListaArticulos item = new ListaArticulos(
articulo.getString("IdArticulo"),
articulo.getString("Precio"),
articulo.getString("Stock"),
articulo.getString("Consultas"),
articulo.getString("IdCategoria"),
articulo.getString("Descripcion"),
articulo.getString("Observacion"),
articulo.getString("Codigo"),
articulo.getString("Imagen")
);
So in conclusion what you need to do is change JSONArray jArray = json.getJSONArray("kategori_data");
for
JSONObject jsonOb = json.getJSONObject("kategori_data");

Allowing user inputs that have spaces (" ")

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!

Primefaces: Cloning of Diagram Element does not work properly

i want to add multiple elements on an existing diagram in primefaces but it overwrites the created one all the time. It creates the first one and after that it keeps overwriting whenever i drop a new element on the diagram.
I'm using the panel via drag'n drop to add new element to the diagram.
See below my code (diagram.xhtml):
<h:form id="elementForm">
<p:panel id="epnl" header="Draggable Panel">
<h:outputText value="New Workflow Task" />
</p:panel>
<p:draggable for="epnl" helper="clone" />
<p:outputPanel id="selectedElements" style="height:600px">
<p:diagram id="diagramV" value="#{diagramFlowChartView.model}"
style="height:600px" styleClass="ui-widget-content" />
</p:outputPanel>
<p:droppable for="diagramV" widgetVar="dropWV">
<p:ajax listener="#{diagramFlowChartView.onElementDrop}"
update="elementForm, selectedElements, diagramV" />
</p:droppable>
</h:form>
<script type="text/javascript">
//<![CDATA[
PrimeFaces.widget.Droppable.prototype.bindDropListener = function() {
var _self = this;
this.cfg.drop = function(event, ui) {
if (_self.cfg.onDrop) {
_self.cfg.onDrop.call(_self, event, ui);
}
if (_self.cfg.behaviors) {
var dropBehavior = _self.cfg.behaviors['drop'];
if (dropBehavior) {
var ext = {
params : [ {
name : _self.id + '_dragId',
value : ui.draggable.attr('id')
}, {
name : _self.id + '_dropId',
value : _self.cfg.target
}, {
name : ui.draggable.attr('id') + '_left',
value : ui.position.left
}, {
name : ui.draggable.attr('id') + '_top',
value : ui.position.top
} ]
};
console.log(ui);
dropBehavior.call(_self, ext);
}
}
};
}
// ]]>
</script>
The related Bean (FormChartView.java):
#ManagedBean(name = "diagramFlowChartView")
#RequestScoped
public class FlowChartView {
private DefaultDiagramModel model;
private Element elm = new Element("", "25em", "10em");
private List<Element> elements = new ArrayList<Element>();
public void onElementDrop(DragDropEvent ddEvent) {
String dargId = ddEvent.getDropId();
System.out.println("dargId = " + dargId);
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String left = params.get(dargId + "_left");
String top = params.get(dargId + "_top");
elment = new Element("Test", left, top);
elment.setId(UUID.randomUUID().toString());
System.out.println("elm.id = " + elm.getId());
model.addElement(elm);
}
#PostConstruct
public void init() {
model = new DefaultDiagramModel();
elm = new Element("", "25em", "10em");
model.setMaxConnections(-1);
FlowChartConnector connector = new FlowChartConnector();
connector.setPaintStyle("{strokeStyle:'#C7B097',lineWidth:3}");
model.setDefaultConnector(connector);
Element start = new Element("Fight for your dream", "20em", "6em");
start.addEndPoint(new BlankEndPoint(EndPointAnchor.BOTTOM));
start.addEndPoint(new BlankEndPoint(EndPointAnchor.LEFT));
start.setDraggable(true);
start.setStyleClass("background-color: #98AFC7");
Element trouble = new Element("Do you meet some trouble?", "20em", "18em");
trouble.addEndPoint(new BlankEndPoint(EndPointAnchor.TOP));
trouble.addEndPoint(new BlankEndPoint(EndPointAnchor.BOTTOM));
trouble.addEndPoint(new BlankEndPoint(EndPointAnchor.RIGHT));
trouble.setDraggable(true);
Element giveup = new Element("Do you give up?", "20em", "30em");
giveup.addEndPoint(new BlankEndPoint(EndPointAnchor.TOP));
giveup.addEndPoint(new BlankEndPoint(EndPointAnchor.LEFT));
giveup.addEndPoint(new BlankEndPoint(EndPointAnchor.RIGHT));
Element succeed = new Element("Succeed", "50em", "18em");
succeed.addEndPoint(new BlankEndPoint(EndPointAnchor.LEFT));
succeed.setStyleClass("ui-diagram-success");
Element fail = new Element("Fail", "50em", "30em");
fail.addEndPoint(new BlankEndPoint(EndPointAnchor.LEFT));
fail.setStyleClass("ui-diagram-fail");
model.addElement(start);
model.addElement(trouble);
model.addElement(giveup);
model.addElement(succeed);
model.addElement(fail);
elements.add(start);
elements.add(trouble);
elements.add(giveup);
elements.add(succeed);
elements.add(fail);
model.connect(createConnection(start.getEndPoints().get(0), trouble.getEndPoints().get(0), null));
model.connect(createConnection(trouble.getEndPoints().get(1), giveup.getEndPoints().get(0), "Yes"));
model.connect(createConnection(giveup.getEndPoints().get(1), start.getEndPoints().get(1), "No"));
model.connect(createConnection(trouble.getEndPoints().get(2), succeed.getEndPoints().get(0), "No"));
model.connect(createConnection(giveup.getEndPoints().get(2), fail.getEndPoints().get(0), "Yes"));
}
public DefaultDiagramModel getModel() {
return model;
}
public void setModel(DefaultDiagramModel model) {
this.model = model;
}
public Element getElment() {
return elment;
}
public void setElment(Element elment) {
this.elment = elment;
}
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
private Connection createConnection(EndPoint from, EndPoint to, String label) {
Connection conn = new Connection(from, to);
conn.getOverlays().add(new ArrowOverlay(20, 20, 1, 1));
if(label != null) {
conn.getOverlays().add(new LabelOverlay(label, "flow-label", 0.5));
}
return conn;
}
}
My fault.
This is caused by the element list to be reinitialized each time an (ajax)request was made. Which in turn was caused by the bean scope being #RequestScoped
Changing #RequestScoped to #ViewScoped solved the issue.

event.getOverlay returns null eventhough the overlay is added

My xhtml code snippet
<p:gmap id="gMap" center="17.483333,78.416667" zoom="15" type="ROADMAP" model="#{routeMapngSysMBean.simpleModel}" style="width: 1150px; height: 450px;">
<p:ajax event="overlaySelect" listener="#{routeMapngSysMBean.onMarkerSelect}" />
<p:gmapInfoWindow>
<p:outputPanel style="text-align:center;display:block;">
<h:outputText value="#{routeMapngSysMBean.marker.data}" />
</p:outputPanel>
</p:gmapInfoWindow>
</p:gmap>
RouteMappingMBean.java
import org.primefaces.event.map.OverlaySelectEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;``
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;
#ManagedBean(name = "routeMapngSysMBean")
#SessionScoped
public class RouteMapngSysMBean extends AdminCommonMBean implements
Serializable, WebConstants, ErrorConstants {
private MapModel simpleModel;
public RouteMapngSysMBean() {
initiliaze();
String zone_cd = httpServletRequest
.getParameter("routeMapForm:location");
String vendor_cd = httpServletRequest
.getParameter("routeMapForm:vendor");
String dDate = httpServletRequest.getParameter("routeMapForm:date");
String slot = httpServletRequest.getParameter("routeMapForm:timeslot");
try {
if (orderMgmtBusn == null) {
orderMgmtBusn = (OrderMgmtBusn) BeansUtil.getBean(facesContext,
"orderMgmtBusn");
}
simpleModel = new DefaultMapModel();
if (ValidateUtil.isFieldNotEmpty(vendor_cd)
&& ValidateUtil.isFieldNotEmpty(zone_cd)
&& ValidateUtil.isFieldNotEmpty(dDate)
&& ValidateUtil.isFieldNotEmpty(slot)) {
mapDetails = orderMgmtBusn.getMapDetails(vendor_cd,slot,dDate, zone_cd);
}
List<GMapDetails> latlang = mapDetails;
for (GMapDetails var : latlang) {
if (ValidateUtil.isFieldNotEmpty(var.getLatitude()) && ValidateUtil.isFieldNotEmpty(var.getLongitude())) {
firstName = var.getCustomerFName();
customerId = var.getCustomerId();
orderId = var.getOrderId();
orderValue = var.getOrderValue();
String Customerdetails = "\n CustomerName:"+firstName+"\n CustomerId:"+customerId+"\n OrderId:"+orderId+"\n OrderValue:"+orderValue;
lat = Double.parseDouble(var.getLatitude());
lng = Double.parseDouble(var.getLongitude());
LatLng coord1 = new LatLng(lat, lng);
simpleModel.addOverlay(new Marker(coord1, var.getLocationName(),Customerdetails));
}
}
} catch (EMartBusnException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void initiliaze() {
try {
WebApplicationContext springContext = WebApplicationContextUtils
.getWebApplicationContext((ServletContext) facesContext
.getExternalContext().getContext());
if (emartAppBaseBusn == null) {
emartAppBaseBusn = (EmartAppBaseBusn) springContext
.getBean("emartAppBaseBusn");
}
avilableStoreTypes = BeanMappingUtil
.filterVendorZones(emartAppBaseBusn.retriveZones());
retriveAllVendorsList = emartAppBaseBusn.retriveAllVendorsList();
zonesList = BeanMappingUtil.filterVendorZones(emartAppBaseBusn
.getZones());
} catch (EMartBusnException e) {
logger.error(e);
}
}
public void onMarkerSelect(OverlaySelectEvent event) {
marker = (Marker) event.getOverlay();
}
public MapModel getSimpleModel() {
return simpleModel;
}
public void setSimpleModel(MapModel simpleModel) {
this.simpleModel = simpleModel;
}
public Marker getMarker() {
return marker;
}
Please try transforming 'simpleModel' field declaration from:
private MapModel simpleModel;
to:
private final static MapModel simpleModel = new DefaultMapModel();
...and of course remove this: 'simpleModel = new DefaultMapModel();' from the constructor.