Validating xp:inputTextArea field not containing Return characters - validation

In my xpages application I have a validation on a inputTextArea control e.g.
<xp:inputTextarea
id="inpRelPresentation"
value="#{matterBean.matter.busRelations}"
validator="#{matterValidators.valBusinessRelation}">
<xp:this.validators>
<xp:validateRequired>
<xp:this.message><![CDATA[#{javascript:xptI18NBean.getValue("matter.msg_valid_business_relation")}]]></xp:this.message>
</xp:validateRequired>
</xp:this.validators>
<xp:this.required><![CDATA[#{javascript:return ( submittedBy('btnSendToCommitee'))}]]></xp:this.required>
</xp:inputTextarea>
The validator has a simple check that no spaces are entered. I would to extend the validator so it also removed black lines and return characters but I wonder how to apply this?
public void valBusinessRelation(FacesContext facesContext, UIComponent component, Object value) {
try {
String msg = null;
if (value.toString().replaceAll("\\s+","").equals("")){
utils.printToConsole(this.getClass().getSimpleName().toString() + " " + methodName + " -> FAILED. Component: " + component.getId() + ". Value = " + value.toString());
msg = propStrings.getProperty("msg_valid_business_relation");
FacesMessage message = new FacesMessage(msg);
throw new ValidatorException(message);
}
} catch (Exception e) {
XspOpenLogUtil.logErrorEx(e, JSFUtil.getXSPContext().getUrl().toString(), Level.SEVERE, null);
}
}
Any suggestions?

Related

Web Crawling with Spring Batch

I have a crawl function that also checks whether the content contains the param. If it contains I will write that to the database. How can I use the following code as a Read Job for the spring batch?
public void crawl(String baseUrl, String url, String postgresParam) {
if (!urls.contains(url) && url.startsWith(baseUrl)) {
// System.out.println(">> count: " + count + " [" + url + "]");
urls.add(url);
try {
Connection connection = Jsoup.connect(url).userAgent(USER_AGENT);
Document htmlDocument = connection.get();
Elements linksOnPage = htmlDocument.select("a[href]");
bodyContent = htmlDocument.body().text();
String title = htmlDocument.title();
searchParameters(url, title);
// count++;
for (Element link : linksOnPage) {
crawl(baseUrl, link.absUrl("href"), postgresParam);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void searchParameters(String URL, String title) {
for (String param : postgresParamArray) {
if (bodyContent.toLowerCase().contains(param.toLowerCase())) {
System.out.println(">>>>>> Found: " + " [" + param + "]" + " [" + URL + "]" + " [" + title + "]");
}
}
}

Bot Framework with LUIS - Issue with opening Form one after another

My bot is supposed to help delete appointment.
A prompt for user's nric will be done (in RetrieveAppt.cs)
Subsequently, if there is such user in my database, it should go on to prompt user to enter the apptId which he/she wants to delete (as there may be multiple appointments made by same person) (in DeleteAppt.cs)
Issue Description
Exception thrown: 'Microsoft.Bot.Builder.Internals.Fibers.InvalidNeedException' in Microsoft.Bot.Builder.dll
Code Example
RetrieveAppt.cs
using Microsoft.Bot.Builder.FormFlow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Bot.Models
{
[Serializable]
public class RetrieveAppt
{
[Prompt("Please provide your NRIC:")]
public string Nric { get; set; }
public override string ToString()
{
var builder = new StringBuilder();
builder.AppendFormat(Nric);
return builder.ToString();
}
}
}
DeleteAppt.cs
using Microsoft.Bot.Builder.FormFlow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Bot.Models
{
[Serializable]
public class DeleteAppt
{
[Prompt("Please enter the appointment id that you wish to delete/cancel :")]
public string apptId { get; set; }
public override string ToString()
{
var builder = new StringBuilder();
builder.AppendFormat(apptId);
return builder.ToString();
}
}
}
ApptLuisDialog.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.FormFlow;
using Microsoft.Bot.Connector;
using Bot.Models;
using System.Data.SqlClient;
using System.Globalization;
namespace Bot.Dialogs
{
[LuisModel("I have my own key", "I have my own key")]
[Serializable]
class ApptLuisDialog : LuisDialog<ApptLuisDialog>
{
String sql = #"Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=Temp.DB; User Id = (insert your username here); Password = (insert your password here); Integrated Security=true;MultipleActiveResultSets = true";
private static IForm<RetrieveAppt> BuildRetrieveForm()
{
var builder = new FormBuilder<RetrieveAppt>();
return builder.AddRemainingFields().Build();
}
private static IForm<DeleteAppt> BuildDeleteForm()
{
var builder = new FormBuilder<DeleteAppt>();
return builder.AddRemainingFields().Build();
}
[LuisIntent("")]
[LuisIntent("None")]
public async Task None(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: B");
await context.PostAsync("I'm sorry I don't understand you. However, I can help you to: \n\n" + "1) Retrieve Appointment \n\n" + "2) Create Appointment \n\n" + "3) Delete Appointment \n\n" + "4) Edit Appointment");
context.Wait(MessageReceived);
}
[LuisIntent("RetrieveAppointment")]
public async Task RetrieveAppointment(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: C");
var form = new RetrieveAppt();
var entities = new List<EntityRecommendation>(result.Entities);
var retrieveAppt = new FormDialog<RetrieveAppt>(form, BuildRetrieveForm, FormOptions.PromptInStart);
context.Call(retrieveAppt, RetrieveComplete);
}
private async Task RetrieveComplete(IDialogContext context, IAwaitable<RetrieveAppt> result)
{
RetrieveAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You cancelled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String nric = appt.Nric.ToString();
List<string> apptInfo = new List<string>();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command
SqlCommand cmd = new SqlCommand("SELECT * FROM Appointment a WHERE a.Nric ='" + nric + "'", con);
//Open sql connection
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String date = dr["AptDate"].ToString();
String[] temp = date.Split(null);
apptInfo.Add("Appointment ID: " + dr["ApptId"].ToString() + "\n\n"
+ "Nric: " + dr["Nric"].ToString() + "\n\n"
+ "Date: " + temp[0] + "\n\n"
+ "Time: " + dr["AptStartTime"].ToString() + "\n\n"
+ "Location: " + dr["Location"].ToString() + "\n\n"
+ "Purpose: " + dr["Purpose"].ToString());
}
//Close sql connection
dr.Close();
con.Close();
if (apptInfo.Count == 0)
{
await context.PostAsync("You do not have an appointment/no such NRIC");
}
else
{
for (int i = 0; i < apptInfo.Count(); i++)
{
await context.PostAsync("Your Appointment Info is: " + "\n\n" + apptInfo[i]);
}
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
[LuisIntent("DeleteAppointment")]
public async Task DeleteAppointment(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: A");
var form = new RetrieveAppt();
var retrieveAppt = new FormDialog<RetrieveAppt>(form, BuildRetrieveForm, FormOptions.PromptInStart);
context.Call(retrieveAppt, Delete);
}
private async Task Delete(IDialogContext context, IAwaitable<RetrieveAppt> result)
{
RetrieveAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You cancelled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String nric = appt.Nric.ToString().ToUpper();
List<string> apptInfo = new List<string>();
//SqlAdapter for inserting new records
SqlDataAdapter sda = new SqlDataAdapter();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command to check existing patient
SqlCommand cmd = new SqlCommand("SELECT * FROM Appointment a WHERE a.Nric ='" + nric + "'", con);
//Open sql connection
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String date = dr["AptDate"].ToString();
String[] temp = date.Split(null);
apptInfo.Add("Appointment ID: " + dr["ApptId"].ToString() + "\n\n"
+ "Nric: " + dr["Nric"].ToString() + "\n\n"
+ "Date: " + temp[0] + "\n\n"
+ "Time: " + dr["AptStartTime"].ToString() + "\n\n"
+ "Location: " + dr["Location"].ToString() + "\n\n"
+ "Purpose: " + dr["Purpose"].ToString());
}
if (apptInfo.Count != 0)
{
**//this is the part that has error, i can't prompt for the appointment id that user wants to delete**
System.Diagnostics.Debug.WriteLine("Entered here: AA");
var form = new DeleteAppt();
var deleteAppt = new FormDialog<DeleteAppt>(form, BuildDeleteForm, FormOptions.PromptInStart);
context.Call(deleteAppt, DeleteComplete);
}
else
{
//Close sql connection
dr.Close();
con.Close();
await context.PostAsync("Invalid NRIC/No current appointment");
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
private async Task DeleteComplete(IDialogContext context, IAwaitable<DeleteAppt> result)
{
DeleteAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You canceled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String apptId = appt.apptId.ToString();
List<string> newApptInfo = new List<string>();
//SqlAdapter for inserting new records
SqlDataAdapter sda = new SqlDataAdapter();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command to check existing patient
String cmd = "DELETE FROM Appointment a WHERE a.ApptId ='" + apptId + "'";
//Open sql connection
con.Open();
try
{
sda.InsertCommand = new SqlCommand(cmd, con);
sda.InsertCommand.ExecuteNonQuery();
//Close sql connection
con.Close();
await context.PostAsync("Appointment " + apptId + " cancelled successfully.");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception caught: " + ex);
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
}
}
Expected Behavior
For example, after bot prompts user to input NRIC, user inputs "123456". So let's say, there are 3 appointments linked to NRIC "123456". So it will show all 3 appointments (with the following details: apptId, apptDate, apptTime, locatoin) first.
Next, I want the bot to prompt the user for the appointment that he/she wants to delete base on the apptId. (But this prompt is not showing)
Actual Results
Exception thrown: 'Microsoft.Bot.Builder.Internals.Fibers.InvalidNeedException' in Microsoft.Bot.Builder.dll
Help needed here definitely
adding a "return" statement would solve it.
When making the call to context.Call(deleteAppt, DeleteComplete); there should not follow a call to context.Wait(MessageReceived). So add a return statement after context.Call(deleteAppt, DeleteComplete);
if (apptInfo.Count != 0)
{
//this is the part that has error, i can't prompt for the appointment id that user wants to delete
System.Diagnostics.Debug.WriteLine("Entered here: AA");
var form = new DeleteAppt();
var deleteAppt = new FormDialog<DeleteAppt>(form, BuildDeleteForm, FormOptions.PromptInStart);
context.Call(deleteAppt, DeleteComplete);
return;
}

How to get entity relationship with annotations using testing class?

I have created a simple Spring-boot application with two entities as Company.java and User.java. These two has #OneToMany relationship. And I have a created a test file for generating typescript file with printing those two entity's attributes. Here is the my test case.
#Inject
RepositoryRestMvcConfiguration configuration;
#Test
public void getEndPoints() {
configuration.resourceMappings().forEach(c -> {
String className = c.getDomainType().getName();
try {
Class<?> entityClass = Class.forName(className);
Field[] fields = entityClass.getDeclaredFields();
File tsClassDir = new File("data/tsClass");
File tsClass = new File(tsClassDir, entityClass.getSimpleName() + ".ts");
if (!tsClass.getParentFile().exists()) {
tsClass.getParentFile().mkdirs();
}
tsClass.createNewFile();
String code = "export interface " + entityClass.getSimpleName() + "{\n";
for (Field field : fields) {
try {
NotNull notNullAnnotation = field.getDeclaredAnnotation(NotNull.class);
Class<?> filedClass = Class.forName(field.getType().getName());
if (notNullAnnotation == null){
code += "\t" + field.getName() + "?: " + filedClass.getSimpleName().trim() + ";" + "\n";
}else{
code += "\t" + field.getName() + ": " + filedClass.getSimpleName().trim() + ";" + "\n";
}
} catch (Exception e) {
// TODO: handle exception
}
// System.err.println(field.getName());
}
code += "}";
Files.write(tsClass.toPath(), code.getBytes());
System.err.println(code);
} catch (Exception e) {
// TODO: handle exception
}
});
}
After test run I got the result given below.
export interface User{
userName: String;
password: String;
email: String;
company?: Company;
}
export interface Company{
name: String;
email: String;
users?: Set;
}
But I need to print that Company and User has #OneToMany relationship in the typescript file. How do I do that?

Writing a precise pointcut expression

I am using Spring AOP for logging wherein I want to log input/output of all methods present in package. I have written following pointcut for target package.
#Pointcut("within(com.mypackage.model.*)")
public void allmethods(){};
My logging method is as below.
#Before("allmethods()")
public void LoggingAdviceBefore(JoinPoint joinPoint)
{
StringBuffer logMessage = new StringBuffer();
if(joinPoint != null && joinPoint.getTarget()!=null && joinPoint.getTarget().getClass()!=null)
{
logMessage.append(joinPoint.getTarget().getClass().getName());
logMessage.append(".");
logMessage.append(joinPoint.getSignature().getName());
logMessage.append("(");
// append args
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
logMessage.append(args[i]).append(",");
}
if (args.length > 0) {
logMessage.deleteCharAt(logMessage.length() - 1);
}
logMessage.append(")");
log.info(logMessage.toString());
}
}
The code is working fine.
My problem is, even if I do some simple operations like, populating an array list within my code, even that information is getting logged. I don't want such information to be logged.
I want to log inputs only for the methods that I had written in the classes present in target package & not for the code written inside those methods. How do I achieve this?
You can use the below code which I had written months back to understand SNMP framework implementation, it prints i/o of all the methods in package and subpackage, you can remove irrelevant classes and modify according to your needs, if required.
#Aspect
public class Snmp4JProfiler {
private static final Logger LOG = LoggerFactory.getLogger(Snmp4JProfiler.class);
#Pointcut("execution (* org.snmp4j.Snmp.*(..))")
public void allSnmpServices() {
}
#Pointcut("execution (* org.snmp4j.security.U*.*(..))")
public void allUSMServices() {
}
#Around("allUSMServices() || allSnmpServices()")
public Object executionTimeOfService(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
String className = pjp.getSignature().getDeclaringTypeName();
final String methodName = methodSignature.getName();
String methodArgs = "";
for (Object obj : pjp.getArgs()) {
if (obj == null) {
methodArgs += "no args or null,";
} else if (obj instanceof UsmTimeEntry) {
UsmTimeEntry timeEntry = (UsmTimeEntry) obj;
methodArgs += obj.toString() + "[" + timeEntry.getEngineBoots() + "," + timeEntry.getLatestReceivedTime() + ","
+ timeEntry.getTimeDiff() + "," + timeEntry.getEngineID() + "]";
} else if (obj instanceof Object[]) {
methodArgs += obj.toString() + " " + Arrays.toString((Object[]) obj);
} else {
methodArgs += obj;
}
}
LOG.info("Start of method#" + methodName + " #class#" + className + " #args#" + methodArgs);
try {
Object output = pjp.proceed();
String rtValues = "";
if (output == null) {
rtValues += "no args or null,";
} else if (output instanceof UsmTimeEntry) {
UsmTimeEntry timeEntry = (UsmTimeEntry) output;
rtValues += output.toString() + "[" + timeEntry.getEngineBoots() + "," + timeEntry.getLatestReceivedTime() + ","
+ timeEntry.getTimeDiff() + "," + timeEntry.getEngineID() + "]";
} else if (output instanceof Object[]) {
rtValues += output.toString() + " " + Arrays.toString((Object[]) output);
} else {
rtValues += output;
}
LOG.info("End of method#" + methodName + " #class#" + className + " #return#" + rtValues);
return output;
} catch (Exception ex) {
LOG.info("End of method#" + methodName + " #class#" + className + " #error#" + ex.getMessage());
throw ex;
}
}
}

Clickable URL in Windows Phone Message box

I want to display an URL in my message box that the user can click and navigate to on Wp7 mango. Is this Possible? If yes how do i implement it ?
My message box is coded as below:
public static void customizedMessageBox(int messageboxtype, string title, string text, IEnumerable<string> buttons, int focusbutton, MessageBoxIcon icon, AsyncCallback callback, object state)
{
if (!Guide.IsVisible)
{
try
{
ProgressBarControl.dismissProgressBar();
Guide.BeginShowMessageBox(" ", text, buttons, focusbutton, MessageBoxIcon.None, callback, state);
messageboxType = messageboxtype;
}
catch (GuideAlreadyVisibleException ex)
{
Logger.log("MsgBox", "Exception : messageboxtype: " + messageboxtype
+ "\n" + ex.Message + "\n" + ex.StackTrace);
}
}
//return messageboxtype;
}
public static void OnMessageBoxClosed(IAsyncResult ar)
{
int? dialogResult = Guide.EndShowMessageBox(ar);
Game game;
try
{
Logger.log("MsgBox", "result: " + dialogResult + " msg type: " + messageboxType);
switch (messageboxType)
{ case 7:
//ERROR E4000 case
switch (dialogResult)
{
case 0:
string url;
//url = CacheManager.getInstance().getApplicationSettings(CacheManager.APP_APK_UPGRADE_URI);
url = DataManager.URL_VALUE;
if (Utils.isNullString(url))
{
//url = CacheManager.getInstance().getUpgradeURL();
}
WebBrowserTask browse = new WebBrowserTask();
browse.URL = url;
browse.Show();
break;
default:
//delete data from the DB
ProgressBarControl.displayProgressBar(0, 10, AppResources.DOWNLOADING);
try
{
//byte[] data = (byte[])CacheManager.getInstance().getPersistanceData(Utils.MINOR_UPGRADE_DATA);
byte[] data = (byte[])CacheManager.getInstance().getDataFromDataFile();
if (data != null && data.Length > 0)
{
DataManager.getInstance().processMyWidgetResponse(data);
DataManager.getInstance().refresUI();
}
}
catch (Exception ex)
{
}
finally
{
//CacheManager.getInstance().deletaFromApplicationCache(Utils.MINOR_UPGRADE_DATA);
}
break;
}
break;
default:
break;
}
}
catch (Exception ex)
{
Logger.log(TAG, ex.Message);
}
finally
{
ProgressBarControl.dismissProgressBar();
}
}
I am calling the messagebox like this:-
UIListen.customizedMessageBox(Utils.ERROR_CODE_E4000, ERROR_FORCE_REGISTRATION, responseHeaders[HEADER_URL_NAME, 1], Utils.valuesOk, 0);
take a look a this: http://coding4fun.codeplex.com/
explore different kind of custom dialogs\message boxed he made. You can take this as ref and make your own or you can directly use the existing one.
consider showing a custom screen or xaml page which gives user the correct options. You can provide whatever options you want. Buttons etc .

Resources