primefaces (3.2) autocomplete pojo - autocomplete

I am trying to implement PF Autocomplete component (v3.2) with POJO. Things work fine when a user selects an entry from the possible drop down options provided. However, the scenario where a user enters some text into the input field and simply hits enter does not work well for me.
If a user simply enters some text to the autocomplete input box and hits enter, all I have to do is redirect them to a new page with 1 query parameter. I noticed that if I hit enter before AutoComplete has a chance to show suggestions, then the redirect happens just fine. Once drop down suggestions are shown, hitting enter simply clears the input box.
I would expect something like this to work just fine, so I must be doing something silly.
<h:form>
<p:autoComplete id="globalAutoComplete" value="#{autoCompleteBackingBean.selectedResult}" completeMethod="#{autoCompleteBackingBean.globalSearch}" var="aResult" itemValue="#{aResult}" converter="autoCompleteConverter" queryDelay="200" maxResults="6" minQueryLength="3">
<p:column>
#{aResult.label} <br/> #{aResult.desc} <span class='ui-icon #{aResult.icon} autocompleteResultsIcon'/>
</p:column>
</p:autoComplete>
<p:commandButton id="submitAutoComplete" type="submit" icon="ui-icon-suitcase" action="#{autoCompleteBackingBean.doRedirect}"/>
</h:form>
Converter:
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if (value == null || value.length() == 0 ) {
return null;
}
Object obj = null;
try {
List<AutoComplete> results = AutoCompleteBackingBean.getResults();
for (AutoComplete aResult : results){
if((aResult.getDreRef()).equals(value))
return aResult;
}
} catch (Exception e) {
System.err.println("AutoCompleteConverter getAsObject Error: " + e);
}
if (obj == null) {
AutoComplete empty = new AutoComplete();
empty.setDreRef(value);
return empty;
}
return obj;
}
public String getAsString(FacesContext fc, UIComponent uic, Object object) {
if (object == null) {
return null;
}
Class entityClass = getEntityClass();
String value = null;
if (entityClass.isInstance(object)) {
try {
value = ((AutoComplete)object).getDreRef();
}catch (Exception e){
System.err.println("AutoCompleteConverter getAsString Error: " + e);
value = "Unable to obtain String from Object";
}
}
else {
value = "AutoCompleteConverter.getAsString(): Object " + object + " is of type "
+ object.getClass().getSimpleName() + "; expected type: "
+ entityClass.getSimpleName();
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, value, null));
}
return value;
}
Backing bean:
private AutoComplete selectedResult = null;
//getter and setter
public String doRedirect() {
System.out.println("doRedirect()");
return "entities.jsf?query=" + selectedResult.getDreRef() + "&faces-redirect=true";
}

Related

how to get drop down list by type respective alphabet in ComboBoxViewerCellEditor

In ComboBoxViewerCellEditor I want to write something and as a result I will get the matching dropdown value.
Can you suggest how to get this? Please find the code below:
public TCOperationColumnEditable(TableViewer viewer) {
super(viewer);
try
{
this.viewer = viewer;
//this.editor = new TextCellEditor(this.viewer.getTable());
OperationGSON[] allOperations = OperationAPIHandler.getInstance().getAllOperations();
ArrayList<String> opnName = new ArrayList<String>();
for(OperationGSON opn : allOperations)
{
opnName.add(opn.opnName);
}
this.editor = new ComboBoxViewerCellEditor(this.viewer.getTable(), SWT.FULL_SELECTION );
this.editor.setLabelProvider(new LabelProvider());
this.editor.setContentProvider(new ArrayContentProvide());
this.editor.setInput(opnName);
String[] stockArr = new String[opnName.size()];
stockArr = opnName.toArray(stockArr);
new AutoCompleteField(this.viewer.getControl(), new CComboContentAdapter(), stockArr);
}
catch(Exception e)
{
System.out.println("[" + getClass().getName() + " : TCOperationColumnEditable()] - Exception : " + e.getMessage());
e.printStackTrace();
}
}
enter image description here
Subclass TextCellEditor.
For a content proposal, use field assist API of JFace
(org.eclipse.jface.fieldassist). Content assist is enabled
when the cell editor is activated for the first time:
if (contentProposalAdapter == null) {
....
// enable content assist on the cell editor's text widget
contentProposalAdapter = new ContentProposalAdapter(text, new TextContentAdapter(), proposalProvider, activationKeyStroke, null);
} else {
contentProposalAdapter.setEnabled(true);
}
super.activate();
....
Make sure to also override method
TextCellEditor#dependsOnExternalFocusListener() to return false always.
Otherwise, you'll face some serious problems concerning focus.

GWT-RPC method returns empty list on success

I am creating a webpage having CellTable.I need to feed this table with data from hbase table.
I have written a method to retrieve data from hbase table and tested it.
But when I call that method as GWT asynchronous RPC method then rpc call succeeds but it returns nothing.In my case it returns empty list.The alert box show list's size as 0.
Following is the related code.
Please help.
greetingService.getDeviceIDData(new AsyncCallback<List<DeviceDriverBean>>(){
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
System.out.println("RPC Call failed");
Window.alert("Data : RPC call failed");
}
public void onSuccess(List<DeviceDriverBean> result) {
//on success do something
Window.alert("Data : RPC call successful");
//deviceDataList.addAll(result);
Window.alert("Result size: " +result.size());
// Add a text column to show the driver name.
TextColumn<DeviceDriverBean> nameColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
Window.alert(object.getName());
return object.getName();
}
};
table.addColumn(nameColumn, "Name");
// Add a text column to show the device id
TextColumn<DeviceDriverBean> deviceidColumn = new TextColumn<DeviceDriverBean>() {
#Override
public String getValue(DeviceDriverBean object) {
return object.getDeviceId();
}
};
table.addColumn(deviceidColumn, "Device ID");
table.setRowCount(result.size(), true);
// more code here to add columns in celltable
// Push the data into the widget.
table.setRowData(0, result);
SimplePager pager = new SimplePager();
pager.setDisplay(table);
VerticalPanel vp = new VerticalPanel();
vp.add(table);
vp.add(pager);
// Add it to the root panel.
RootPanel.get("datagridContainer").add(vp);
}
});
Code to retrieve data from hbase (server side code)
public List<DeviceDriverBean> getDeviceIDData()
throws IllegalArgumentException {
List<DeviceDriverBean> deviceidList = new ArrayList<DeviceDriverBean>();
// Escape data from the client to avoid cross-site script
// vulnerabilities.
/*
* input = escapeHtml(input); userAgent = escapeHtml(userAgent);
*
* return "Hello, " + input + "!<br><br>I am running " + serverInfo +
* ".<br><br>It looks like you are using:<br>" + userAgent;
*/
try {
Configuration config = HbaseConnectionSingleton.getInstance()
.HbaseConnect();
HTable testTable = new HTable(config, "driver_details");
byte[] family = Bytes.toBytes("details");
Scan scan = new Scan();
int cnt = 0;
ResultScanner rs = testTable.getScanner(scan);
for (Result r = rs.next(); r != null; r = rs.next()) {
DeviceDriverBean deviceDriverBean = new DeviceDriverBean();
byte[] rowid = r.getRow(); // Category, Date, Sentiment
NavigableMap<byte[], byte[]> map = r.getFamilyMap(family);
Iterator<Entry<byte[], byte[]>> itrt = map.entrySet()
.iterator();
deviceDriverBean.setDeviceId(Bytes.toString(rowid));
while (itrt.hasNext()) {
Entry<byte[], byte[]> entry = itrt.next();
//cnt++;
//System.out.println("Count : " + cnt);
byte[] qual = entry.getKey();
byte[] val = entry.getValue();
if (Bytes.toString(qual).equalsIgnoreCase("account_number")) {
deviceDriverBean.setAccountNo(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("make")) {
deviceDriverBean.setMake(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("model")) {
deviceDriverBean.setModel(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("driver_name")) {
deviceDriverBean.setName(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("premium")) {
deviceDriverBean.setPremium(Bytes.toString(val));
} else if (Bytes.toString(qual).equalsIgnoreCase("year")) {
deviceDriverBean.setYear(Bytes.toString(val));
} else {
System.out.println("No match found");
}
/*
* System.out.println(Bytes.toString(rowid) + " " +
* Bytes.toString(qual) + " " + Bytes.toString(val));
*/
}
deviceidList.add(deviceDriverBean);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// System.out.println("Message: "+e.getMessage());
e.printStackTrace();
}
return deviceidList;
}
Could this be lazy fetching on the server side by hbase. This means if you return the list hbase won't get a trigger to actually read the list and you will simple get an empty list. I don't know a correct solution, in the past I've seen a similar problem on GAE. This could by solved by simply asking the size of the list just before returning it to the client.
I don't have the exact answer, but I have an advise. In similar situation I put my own trace to check every step in my program.
On the server side before return put : System.out.println("size of table="+deviceidList.size());
You can put this trace in the loop for deviceidList;

Dozer NullPointerException on deep-mapping with custom getter

Im getting this exception:
Field mapping error -->
MapId: null
Type: null
Source parent class: com.ParentObject
Source field name: field1
Source field type: class com.OnOff1BitEnum
Source field value: OFF
Dest parent class: com.SubParent
Dest field name: subParent.field2
Dest field type: java.lang.Boolean java.lang.NullPointerException
at org.dozer.util.ReflectionUtils.invoke(ReflectionUtils.java:270)
at org.dozer.propertydescriptor.GetterSetterPropertyDescriptor.getDeepSrcFieldValue(GetterSetterPropertyDescriptor.java:116)
at org.dozer.propertydescriptor.GetterSetterPropertyDescriptor.getPropertyValue(GetterSetterPropertyDescriptor.java:69)
at org.dozer.fieldmap.FieldMap.getDestValue(FieldMap.java:141)
This is the mapping field:
<mapping>
<class-a>com.ParentObject</class-a>
<class-b>com.SubParent</class-b>
<field custom-converter="com.OnOffEnumToBooleanConverter">
<a>field1</a>
<b get-method="isField2">subParent.field2</b>
</field>
</mapping>
The version of dozer i am using is 5.4.0
UPDATE:
Added the converter code to this post.
When i put a break point here this is not being reached
public class OnOffEnumToBooleanConverter implements org.dozer.CustomConverter {
/**
* {#inheritDoc}
*/
#Override
public Object convert(Object dest, Object src, Class<?> destClass, Class<?> srcClass) {
if (src == null) {
return null;
}
if (src instanceof com.OnOff1BitEnum) {
boolean canonicalObject;
if ((com.OnOff1BitEnum) src == com.OnOff1BitEnum.ON) {
canonicalObject = true;
} else if ((com.OnOff1BitEnum) src == com.OnOff1BitEnum.OFF) {
canonicalObject = false;
} else { // Unreachable Code To Test
throw new MappingException("Converter " + this.getClass().getCanonicalName() + " used incorrectly. Arguments passed in were: "
+ dest + " and " + src);
}
return canonicalObject;
}
}
Perhaps it happens because you are missing "set configuration", try specifying it explicitly and see if that solves it or a different error happens, e.g.
<field custom-converter="com.OnOffEnumToBooleanConverter">
<a>field1</a>
<b get-method="isField2" set-method="field2">subParent.field2</b>
</field>
UPDATE:
I had to properly format your java code to be able to read...here is the problem you have "if and else" for a boolean value...there is no 3rd condition...just carefully look at it:
if (src instanceof com.OnOff1BitEnum)
{
boolean canonicalObject;
if ((com.OnOff1BitEnum) src == com.OnOff1BitEnum.ON)
{
canonicalObject = true;
}
else
{
if ((com.OnOff1BitEnum) src == com.OnOff1BitEnum.OFF)
{
canonicalObject = false;
}
else
{ // Unreachable Code To Test
throw new MappingException("Converter " + this.getClass().getCanonicalName()
+ " used incorrectly. Arguments passed in were: " + dest + " and " + src);
}
}
return canonicalObject;
}
That's the evil of "if else construct" that has no brackets in your original code.
Also your "convert" method returns Object...so your "boolean canonicalObject" has to be "Boolean canonicalObject" not primitive type.
Should be:
#Override
public Object convert(Object dest, Object src, Class<?> destClass, Class<?> srcClass)
{
if (src instanceof com.OnOff1BitEnum)
{
if ((com.OnOff1BitEnum) src == com.OnOff1BitEnum.ON)
{
return Boolean.TRUE;
}
else
{
return Boolean.FALSE;
}
}
return null;
}

Binding ObservableCollection to datagrid in MVVM

Im new to XAML, i am trying to bind ObservableCollection to datagrid in MVVM.
I want to get notified when CollectionChanged. But its throwing null exception.
Please let me know when im going wrong. Thanks in advance.
The following is Code behind for viewModel:
public class MainwindowViewModel : INotifyPropertyChanged
{
MyObject myObj;
ObservableCollection<MyObject> _ocObj;
public MainwindowViewModel()
{
_ocObj = new ObservableCollection<MyObject>();
myObj = new MyObject();
myObj.ID = 0;
myObj.Name = "Name";
_ocObj.Add(myObj);
_ocObj.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_ocMyobj_CollectionChanged);
}
void _ocMyobj_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
System.Windows.MessageBox.Show("propeties changed # " + e.NewStartingIndex.ToString()
+ " old items starting # " + e.OldStartingIndex + " olditems count " + e.OldItems.Count.ToString()
+ " action " + e.Action.ToString());
}
public ObservableCollection<MyObject> ocObj
{
get { return _ocObj; }
set
{
PropertyChanged(this, new PropertyChangedEventArgs("ocMyobj"));
}
}
public string Name
{
get { return myObj.Name; }
set
{
if (value !=null)
{
myObj.Name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
public int ID
{
get { return myObj.ID; }
set
{
if (myObj.ID != value)
{
myObj.ID = value;
PropertyChanged(this, new PropertyChangedEventArgs("ID"));
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
public class MyObject
{
public string Name { get; set; }
public int ID { get; set; }
}
Below is XAML:
<Window.Resources>
<vm:MainwindowViewModel x:Key="someObj"/>
</Window.Resources>
<DataGrid ItemsSource="{Binding ocObj}" DataContext="{Binding Source={StaticResource someObj}}" AutoGenerateColumns="True" />
Take a look at the documentation on the NotifyCollectionChangedEventArgs class. Note that the OldItems object only "Gets the list of items affected by a Replace, Remove, or Move action." What this means is that for other actions, OldItems will be null.
Therefore, if an Add action is performed against your ObservableCollection, OldItems is null (and valid). Just perform a check for it in your code, such as:
System.Windows.MessageBox.Show("propeties changed # " + e.NewStartingIndex.ToString()
+ " old items starting # " + e.OldStartingIndex + " olditems count " +
(e.OldItems == null ? "0" : e.OldItems.Count.ToString())
+ " action " + e.Action.ToString());

Prevent sending email and show message via plug-in

I am writing crm2011 plugin in "Email" entity with "Send" Message of Pre_operation. What i want to do is when i click "Send" button in email entity, I do the necessary checking before send. If the checking is not correct, I want to prevent and stop the sending email and show "the alert message" and stop the second plugin(this plugin send email and create the associated entity to convert "Case"). Please give me some suggestion for that plugin?
Should i use pre-Validation stage or Pre_operation state? And how can I return false to stop plugin.
public void Execute(IServiceProvider serviceProvider)
{
try
{
string message = null;
_serviceProvider = serviceProvider;
_context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
_currentUser = _context.UserId;
message = _context.MessageName.ToLower();
if (message == "send")
{
if (_context.InputParameters != null && _context.InputParameters.Contains("EmailId"))
{
object objEmailId = _context.InputParameters["EmailId"];
if (objEmailId != null)
{
_emailId = new Guid(objEmailId.ToString());
FindEmailInfo();
if (_email != null)
{
if (_email.Attributes.Contains("description") && _email.Attributes["description"] != null)//Email descritpion is not null
{
string emaildescription = StripHTML();
//Find KB Article prefix no in system config entity
serviceguideprefix = "ServiceGuidesPrefix";
QueryByAttribute query = new QueryByAttribute("ppp_systemconfig");
query.ColumnSet = new ColumnSet(true);
query.AddAttributeValue(sysconfig_name, serviceguideprefix);
EntityCollection sysconfig = _service.RetrieveMultiple(query);
if (sysconfig.Entities.Count > 0)
{
Entity e = sysconfig.Entities[0];
if (e.Attributes.Contains("ppp_value"))
{
ppp_value = e.Attributes["ppp_value"].ToString();
}
}
if (ppp_value != null && ppp_value != string.Empty)
{
//var matches = Regex.Matches(emaildescription, #"KBA-\d*-\w*").Cast<Match>().ToArray();
var matches = Regex.Matches(emaildescription, ppp_value + #"-\d*-\w*").Cast<Match>().ToArray();
//ReadKBNo(emaildescription);
foreach (Match kbnumber in matches)
{
EntityCollection kbarticlecol = FindKBArticleIds(kbnumber.ToString());
if (kbarticlecol.Entities.Count > 0)
{
Entity kbariticle = kbarticlecol.Entities[0];
if (kbariticle.Attributes.Contains("mom_internalkm"))
{
bool internalserviceguide = (bool)kbariticle.Attributes["mom_internalkm"];
if (internalserviceguide) found = true;
else found = false;
}
else found = false;
}
}
}
if (found)
{
//-----
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
Well stopping the plugin is dead easy you just throw InvalidPluginException, the message you give it will be shown to the user in a alert window. You will have to do this on the pre of the send. In this case I don't think it will matter if its pre-validation or pre-operation.
Edit:
Yes, you should throw an InvalidPluginException even if no exception has happened in code. I accept this isnt what we would normally do, but its the way its meant to work. Msdn has more details: http://msdn.microsoft.com/en-us/library/gg334685.aspx
So for example the code would look like:
public void Execute(IServiceProvider serviceProvider)
{
try
{
//This is where we validate the email send
if(emailIsOkay)
{
//Do something
}
else if(emailIsNotOkay)
{
//Throw and exception that will stop the plugin and the message will be shown to the user (if its synchronous)
throw new InvalidPluginExecutionException("Hello user, your email is not correct!!");
}
}
catch (InvalidPluginExecutionException invalid)
{
//We dont to catch exception for InvalidPluginExecution, so just throw them on
throw;
}
catch (Exception ex)
{
//This exception catches if something goes wrong in the code, or some other process.
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm;
using Microsoft.Xrm.Sdk;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace SendEmail
{
public class Email : IPlugin
{
public void Execute(IServiceProvider serviceprovider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));
if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
return;
//entity
Entity ent = (Entity)context.InputParameters["Target"];
if (ent.LogicalName != "entityName")//EntityName
throw new InvalidPluginExecutionException("Not a Service Request record! ");
//service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
string Email="";
if (ent.Contains("emailidfiled"))
Email = (string)ent["emailidfiled"];
#region email template
QueryExpression query = new QueryExpression()
{
EntityName = "template",
Criteria = new FilterExpression(LogicalOperator.And),
ColumnSet = new ColumnSet(true)
};
query.Criteria.AddCondition("title", ConditionOperator.Equal, "templateName");
EntityCollection _coll = _service.RetrieveMultiple(query);
if (_coll.Entities.Count == 0)
throw new InvalidPluginExecutionException("Unable to find the template!");
if (_coll.Entities.Count > 1)
throw new InvalidPluginExecutionException("More than one template found!");
var subjectTemplate = "";
if (_coll[0].Contains("subject"))
{
subjectTemplate = GetDataFromXml(_coll[0]["subject"].ToString(), "match");
}
var bodyTemplate = "";
if (_coll[0].Contains("body"))
{
bodyTemplate = GetDataFromXml(_coll[0]["body"].ToString(), "match");
}
#endregion
#region email prep
Entity email = new Entity("email");
Entity entTo = new Entity("activityparty");
entTo["addressused"] =Email;
Entity entFrom = new Entity("activityparty");
entFrom["partyid"] = "admin#admin.com";
email["to"] = new Entity[] { entTo };
email["from"] = new Entity[] { entFrom };
email["regardingobjectid"] = new EntityReference(ent.LogicalName, ent.Id);
email["subject"] = subjectTemplate;
email["description"] = bodyTemplate;
#endregion
#region email creation & sending
try
{
var emailid = _service.Create(email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailid;
req.IssueSend = true;
GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();
GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
_service.Execute(wod_GetTrackingTokenEmailRequest);
req.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;
_service.Execute(req);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Email can't be saved / sent." + Environment.NewLine + "Details: " + ex.Message);
}
#endregion
}
private static string GetDataFromXml(string value, string attributeName)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
XDocument document = XDocument.Parse(value);
// get the Element with the attribute name specified
XElement element = document.Descendants().Where(ele => ele.Attributes().Any(attr => attr.Name == attributeName)).FirstOrDefault();
return element == null ? string.Empty : element.Value;
}
}
}