Change css chips on validation error - css

I am working with primefaces and using the element "chips" to introduce multiple e-mails, i validate the format of them and im trying to change the style of the "bubbles" to ui-state-error if the validation is wrong
My chips:
<div class="ui-grid-col-1" style="margin-right: 5px;">
<p:chips id="chips" required="true" value="#{Contactos.lista_email}"
placeholder="Email" style="color: red;"
requiredMessage="ERROR: El campo 'Email' es obligatorio"
validator="ValidMail"/>
</div>
My validator:
#FacesValidator(value = "ValidMail")
public class validatorMail implements Validator{
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
#Override
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
ArrayList<String> aux = (ArrayList<String>) value;
String error = null;
final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
//Check if user has typed only blank spaces
if(value.toString().trim().isEmpty()){
FacesMessage msg = new FacesMessage("ERROR: Email requiere un formato válido", "Email: requiere un formato válido");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
throw new ValidatorException(msg);
}
else {
pattern = Pattern.compile(EMAIL_PATTERN);
for (String temp : aux){
boolean valid = this.validate(temp);
if (valid == false){
if (error == null) error = temp;
else error = error + "\n" + temp;
}
}
if (error != null){
chips.setValid(false);
FacesMessage msg = new FacesMessage("ERROR DE FORMATO: "+"\n" + error, " ");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
chips.setValid(false);
throw new ValidatorException(msg);
}
}
}
Thanks all

There is currently no way to set seperate chip-elements invalid. The primefaces component org.primefaces.component.chips.Chips doesn't provide means for that in version 6.1. You could of course open a feature request on github.
The only way for now is to set the whole component invalid and provide an appropriate text inside your FacesMessage
((UIInput) component).setValid(false);

Related

Inspite of checking for null with usercontrol checkboxlist is returning object reference not set to an instance of an object

I have a group of 7 checkboxes in checkboxlist user control. I build a string in the selectedIndexchanged event for the boxes checked, pass to ViewState and then pass ViewState to the Property. I do this because in the instance when no checkboxes are selected I want to handle null. The problem is no matter how I check for null, the system is throwing object reference error. This current setup works fine if at least one checkbox is checked but if none are checked it fails. How do I check for null? Should I be checking for null in the property or the host aspx page?
I have researched difference ways to do this and I have tried many. My thought is using IsNullOrEmpty or IsNullOrWhiteSpace would be the correct way to go but neither are working.
User Control class - global variable
private string _daysOffInputString = string.Empty;
User Control Property
public string DaysOffSelectedValues
{
get
{
if (string.IsNullOrEmpty(ViewState["DaysOff"].ToString()))
{
_daysOffInputString = string.Empty;
}
else
{
_daysOffInputString = ViewState["DaysOff"].ToString();
}
return _daysOffInputString;
}
set { _daysOffInputString = value; }
User Control event
protected void CbDaysOff_SelectedIndexChanged(object sender, EventArgs e)
{
CheckBoxList chkbx = (CheckBoxList)sender;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chkbx.Items.Count; i++)
{
if (chkbx.Items[i].Selected)
{
sb.Append(chkbx.Items[i].Text + ", ");
}
if (!String.IsNullOrEmpty(sb.ToString()))
{
//Remove last comma & space from string
_daysOffInputString = sb.ToString().Substring(0, sb.ToString().Length - 2);
}
else
{
_daysOffInputString = string.Empty;
}
}
ViewState["DaysOff"] = _daysOffInputString;
}
aspx page - snippet where I retrieve uc property value:
case 2:
blnFlag = false;
ucDaysOff uc3 = row.Cells[3].FindControl("ucDaysOff3") as ucDaysOff;
strAnswer = uc3.DaysOffSelectedValues; //e.g. "Sat, Sun"
break;
SOLUTION: In the user control property DaysOffSelectedValues I was casting ViewState["DaysOff"] to string before checking for null which was the problem. Here's the code that works:
public string DaysOffSelectedValues
{
get
{
if (ViewState["DaysOff"] == null)
{
//_daysOffInputString = string.Empty; }
_daysOffInputString = "Nothing to see here.";
}
else
{
_daysOffInputString = ViewState["DaysOff"].ToString();
}
return _daysOffInputString;
}
set { _daysOffInputString = value; }
}
You should always check if the object, in this case ViewState, is null before using it. Lets say ViewState["DaysOff"] has not been created or has been removed.
Then this will throw a nullreference:
string str = String.IsNullOrEmpty(ViewState["DaysOff"].ToString());
Because you are not checking the ViewState object for null, but the string it is supposed to hold.
So do this
if (ViewState["DaysOff"] != null)
{
string str = ViewState["DaysOff"].ToString();
}

Get property of person Alfresco in JAVA

I'm using Alfresco 5.1 Community, and i'm trying to get a property value of a current person logged for example, in the user I have:
"{http://www.someco.org/model/people/1.0}customProperty"
How can I obtain this in java?
Is a custom property, so, in http://localhost:8080/alfresco/service/api/people it does not appear. How can I do this?
I try this to obtain at least nodeRef:
protected ServiceRegistry getServiceRegistry() {
ProcessEngineConfigurationImpl config = Context.getProcessEngineConfiguration();
if (config != null) {
// Fetch the registry that is injected in the activiti spring-configuration
ServiceRegistry registry = (ServiceRegistry) config.getBeans().get(ActivitiConstants.SERVICE_REGISTRY_BEAN_KEY);
if (registry == null) {
throw new RuntimeException("Service-registry not present in ProcessEngineConfiguration beans, expected ServiceRegistry with key" + ActivitiConstants.SERVICE_REGISTRY_BEAN_KEY);
}
return registry;
}
throw new IllegalStateException("No ProcessEngineConfiguration found in active context");
}
public void writeToCatalina() {
PersonService personService = getServiceRegistry().getPersonService();
System.out.println("test");
String name = AuthenticationUtil.getFullyAuthenticatedUser();
System.out.println(name);
NodeRef personRef = personService.getPerson(name);
System.out.println(personRef);
}
But I got:
No ProcessEngineConfiguration found in active context
Help me !
You can query Alfresco using CMIS and call the API:
GET /alfresco/service/api/people/{userName}.
For first you can define the method to create the session CmisSession:
public Session getCmisSession() {
logger.debug("Starting: getCmisSession()");
// default factory implementation
SessionFactory factory = SessionFactoryImpl.newInstance();
Map<String, String> parameter = new HashMap<String, String>();
// connection settings
parameter.put(SessionParameter.ATOMPUB_URL, url + ATOMPUB_URL);
parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
parameter.put(SessionParameter.AUTH_HTTP_BASIC, "true");
parameter.put(SessionParameter.USER, username);
parameter.put(SessionParameter.PASSWORD, password);
parameter.put(SessionParameter.OBJECT_FACTORY_CLASS, "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
List<Repository> repositories = factory.getRepositories(parameter);
return repositories.get(0).createSession();
}
Then execute the query (this method returns more than one result, you probably need to change it):
public void doQuery(String cql, int maxItems) {
Session cmisSession = getCmisSession();
OperationContext oc = new OperationContextImpl();
oc.setMaxItemsPerPage(maxItems);
ItemIterable<QueryResult> results = cmisSession.query(cql, false, oc);
for (QueryResult result : results) {
for (PropertyData<?> prop : result.getProperties()) {
logger.debug(prop.getQueryName() + ": " + prop.getFirstValue());
}
}
}
If you need to get the token, use this:
public String getAuthenticationTicket() {
try {
logger.info("ALFRESCO: Starting connection...");
RestTemplate restTemplate = new RestTemplate();
Map<String, String> params = new HashMap<String, String>();
params.put("user", username);
params.put("password", password);
Source result = restTemplate.getForObject(url + AFMConstants.URL_LOGIN_PARAM, Source.class, params);
logger.info("ALFRESCO: CONNECTED!");
XPathOperations xpath = new Jaxp13XPathTemplate();
return xpath.evaluateAsString("//ticket", result);
}
catch (RestClientException ex) {
logger.error("FATAL ERROR - Alfresco Authentication failed - getAuthenticationTicket() - " + ex );
return null;
}
catch (Exception ex) {
logger.error("FATAL ERROR - Alfresco Authentication failed - getAuthenticationTicket() - " + ex );
return null;
}
}
You need to obtain your user noderef using this API then access its properties this way!
Edit : You need to inject service registry on your bean!
String name = AuthenticationUtil.getFullyAuthenticatedUser()
You can use this. Let me know if it works.
This will give you current logged in user name and detail.
String name = AuthenticationUtil.getFullyAuthenticatedUser();
System.out.println("Current user:"+name);
PersonService personService=serviceRegistry.getPersonService();
NodeRef node=personService.getPerson(name);
NodeService nodeService=serviceRegistry.getNodeService();
Map<QName, Serializable> props=nodeService.getProperties(node);
for (Entry<QName, Serializable> entry : props.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}

Solr : Autolink on body from words dictionnary

I'm looking for to generate auto link in body result in solr. Words on link must be in a dictionnary.
For example :
a doc :
<doc>
[...]
<str name="title">Il faut, quand on gouverne, voir les hommes tels qu’ils sont, et les choses telles qu’elles devraient être.</str>
<str name="path">citation/faut-gouverne-voir-hommes-tels-choses-telles-devraient-etre-15.php</str>
<str name="ss_field_citation_keywords">#faut#gouverne#voir#hommes#tels#choses#telles#devraient#etre#</str>
[...]
</doc>
Body from title to display :
Il faut, quand on gouverne, voir les hommes tels qu’ils sont, et les choses telles qu’elles devraient être.
Links from ss_field_citation_keywords :
#faut#gouverne#voir#hommes#tels#choses#telles#devraient#etre#
Body must be display like this :
Il faut, quand on gouverne, voir les hommes tels qu’ils sont, et les choses telles qu’elles devraient être.
Il faut, quand on gouverne, voir les hommes tels qu’ils sont, et les choses telles qu’elles devraient être
Do you have any idea?
You have two phases here:
Identify the keywords. For this you want to build your analyzer chain properly. Whitespace tokenizer, lowercase filter and - that's the key part - KeepWordFilterFactory . This will make Solr keep only your keywords with offsets in the text.
Get those offsets. There is might be several ways, but one of them is to reuse Field Analyzer which you can experiment with in admin WebUI of latest (4+) Solr. Make sure to check the Verbose box. That uses /analysis/field end point and you can use it too (with verbose flag). The result is probably too verbose for you but good enough to start. Then you can look for better implementation or copy/reduce the one currently done.
a proposal for internal processing with velocity and a java class
public class autoLinkCitationDirective extends Directive{
public String getName() {
return "autolinkcitation";
}
public int getType() {
return LINE;
}
public boolean render(InternalContextAdapter context, Writer writer, Node node)
throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
String CitationMe = null;
String KeyWords = null;
String SchemaUrl = null;
//params
if (node.jjtGetChild(0) != null) {
CitationMe = String.valueOf(node.jjtGetChild(0).value(context));
}
if (node.jjtGetChild(1) != null) {
KeyWords = String.valueOf(node.jjtGetChild(1).value(context));
}
//schema url
if (node.jjtGetChild(2) != null) {
SchemaUrl = String.valueOf(node.jjtGetChild(2).value(context));
}
writer.write(autoLinkCitation(CitationMe, KeyWords, SchemaUrl));
return true;
}
public String autoLinkCitation(String CitationMe, String KeyWords, String SchemaUrl) {
if (CitationMe == null) {
return null;
}
List<String> tokens = new ArrayList<String>();
StringTokenizer stkKeyWords = new StringTokenizer(KeyWords, "#");
while ( stkKeyWords.hasMoreTokens() ) {
tokens.add(stkKeyWords.nextToken());
}
String patternString = "\\b(" + StringUtils.join(tokens, "|") + ")\\b";
Pattern pattern = Pattern.compile(patternString);
String strippedHtml = CitationMe.replaceAll("<(.|\n)*?>", "");
StringTokenizer st = new StringTokenizer(strippedHtml, ".,! ()[]");
while (st.hasMoreTokens())
{
String token = st.nextToken().trim();
if (token.length() > 3)
{
Matcher matcher = pattern.matcher(cleanString(token));
while (matcher.find()) {
if(CitationMe.indexOf( SchemaUrl + cleanString(token) + "'") == -1)
{
String tmpStringreplacement = "<a href='" + SchemaUrl + cleanString(token) + "'>"+token+"</a>";
CitationMe = CitationMe.replaceAll("\\b"+token+"\\b(?!/)",tmpStringreplacement);
}
}
}
}
return CitationMe;
}
public String cleanString(String CleanStringMe) {
if (CleanStringMe == null) {
return null;
}
CleanStringMe = Normalizer.normalize(CleanStringMe, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
CleanStringMe = CleanStringMe.toLowerCase();
CleanStringMe = CleanStringMe.replaceAll("[^A-Za-z0-9]", "-");
return CleanStringMe;
}
}
and to display:
#autolinkcitation($doc.getFieldValue('body'),$doc.getFieldValue('ss_field_citation_keywords'), '/citations/mot.php?mot=' )

Error when try to save in Windows Azure Table

I did a method which add a user in storage. Below is the code and the error that I'm getting.
public string addusr(string nome, string cidade, string cpf, string email, string telefone)
{
try
{
if (nome.Length == 0)
return "f:Preencha o campo nome.";
if (cidade.Length == 0)
return "f:Preencha o campo cidade.";
if (cpf.Length == 0)
return "f:Preencha o campo cpf.";
if (!Valida(cpf))
return "f:CPF Invalido.";
if (email.Length == 0)
return "f:Preencha o campo email.";
Regex rg = new Regex(#"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$");
if (!rg.IsMatch(email))
{
return "f:Email Invalido";
}
List<UserEntity> lst = new List<UserEntity>();
var _account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Conn"));
var _context = new CRUDUserEntities(_account.TableEndpoint.ToString(), _account.Credentials);
if (_context.Select(cpf).Count() > 0)
return "dup";
var account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("Conn"));
var context = new CRUDUserEntities(account.TableEndpoint.ToString(), account.Credentials);
UserClientEntity entity = new UserClientEntity() { nome = nome, cidade = cidade, cpf = cpf, email = email, telefone = telefone };
context.ADDUSociate(entity);
return "k";
}
catch (Exception exc)
{
string error = "f:" + exc.Message + "|" + exc.StackTrace;
// Trace.WriteLine("Erro no login: " + error , "Information");
return error;
}
}
When I try to add a user...I'm getting this error:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
f:An error occurred while processing this request.| at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.get_Result()
at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.ExecuteAndWait()
at Microsoft.WindowsAzure.StorageClient.CommonUtils. <LazyEnumerateSegmented>d__0`1.MoveNext()
at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)
at mobile.Service1.addusr(String nome, String cidade, String cpf, String email, String telefone)
</string>
I don't know what is wrong..
Not sure whats causing the error but you do miss a context.SaveChanges(); after
context.ADDUSociate(entity);
"I suggest you start with getting the emulator working for azure storage and debug this in visual studio."
I think you dont have the correct Azure sdk installed. Try to reinstall it and the emulator should work. You can follow this guide: http://www.windowsazure.com/en-us/develop/net/how-to-guides/blob-storage/

Java mail getInputStream left recipient

i'm writing a mail send method with javamail.
I can not understand why I get and error as: Recipient not set.
This is my code:
public static void sendMail(String to, String subj, String body, String attachmentName, byte[] attachment, String mime) throws Exception {
Properties p = System.getProperties();
Session session = Session.getInstance(p);
MimeMessage dummyMessage = new MimeMessage(session);
dummyMessage.setFrom(new InternetAddress(LovProvider.getOpzioni().get("mail.address")));
dummyMessage.setSubject(subj);
String[] tos = to.split(";");
Address[] tosAddr = new InternetAddress[tos.length];
for (int i = 0; i < tos.length; i++) {
tosAddr[i] = new InternetAddress(tos[i]);
}
dummyMessage.setRecipients(Message.RecipientType.TO, tosAddr);
Multipart mp = new MimeMultipart();
MimeBodyPart bp = new MimeBodyPart();
bp.setText(body);
mp.addBodyPart(bp);
if (attachmentName != null && attachment != null) {
DataSource dataSource = new ByteArrayDataSource(attachment, mime);
MimeBodyPart attachBodyPart = new MimeBodyPart();
attachBodyPart.setDataHandler(new DataHandler(dataSource));
attachBodyPart.setFileName(attachmentName);
mp.addBodyPart(attachBodyPart);
}
dummyMessage.setContent(mp);
//***** DEBUGGING here I find the recipient
sendMail(dummyMessage.getInputStream());
}
public static void sendMail(InputStream emlFile) throws Exception {
Properties props = System.getProperties();
props.put("mail.host", LovProvider.getOpzioni().get("mail.out.host"));
props.put("mail.transport.protocol", LovProvider.getOpzioni().get("mail.out.protocol"));
props.put("mail." + LovProvider.getOpzioni().get("mail.out.protocol") + ".port", LovProvider.getOpzioni().get("mail.out.port"));
Session mailSession = Session.getDefaultInstance(props, PasswordAuthentication.getAuth(LovProvider.getOpzioni().get("mail.out.user"), LovProvider.getOpzioni().get("mail.out.password")));
MimeMessage message = new MimeMessage(mailSession, emlFile);
//***** DEBUGGING here I CAN NOT find the recipient
Transport.send(message);
}
As I wrote in comments in debug mode i can see the recipient correctly set in the first part, whant i convert it to InputStream to the second method I can not find recipient anymore.
I can't debugging your code, but maybe this examples can help you:
Examples about sending/receiving mail via/from gmail
http://famulatus.com/component/search/?searchword=gmail&searchphrase=all&Itemid=9999

Resources