Custom validation error don't work as expected - java

I want to validate a field to be able to accept values only between 1 and 100. It works fine, but when i write a something that is not an integer is don't see the custom message i expect.
This is the field:
<h:inputText id="discountPercentage" value="#{newOfferSupportController.discountPercentage}" validator="#{newOfferSupportController.validateDiscountPercentage}"/>
<span style="color: red;"><h:message for="discountPercentage"
showDetail="true" /></span>
This is the validator method:
public void validateDiscountPercentage(FacesContext context,
UIComponent validate, Object value) {
FacesMessage msg = new FacesMessage("");
String inputFromField = "" + value.toString();
String simpleTextPatternText = "^([1-9]|[1-9]\\d|100)$";
Pattern textPattern = null;
Matcher productValueMatcher = null;
textPattern = Pattern.compile(simpleTextPatternText);
productValueMatcher = textPattern.matcher(inputFromField);
if (!productValueMatcher.matches()) {
msg = new FacesMessage("Only values between 1 and 100 allowed");
throw new ValidatorException(msg);
}
for (int i = 0; i < inputFromField.length(); i++) {
// If we find a non-digit character throw Exception
if (!Character.isDigit(inputFromField.charAt(i))) {
msg = new FacesMessage("Only numbers allowed");
throw new ValidatorException(msg);
}
}
}
This is the error i message i see when i ester something that is not a number:
Why i don't see the message: Only numbers allowed?

Why don't you use jsf's LongRangeValidator for this purpose?
<h:inputText id="discountPercentage"
value="#{newOfferSupportController.discountPercentage}">
<f:validateLongRange minimum="1" maximum="100"/>
</h:inputText>
You can even define your own custom validation messages if the default messages don't fit your needs. See this answer for more information.
Besides this, your error message is for productValue and not for discountPercentage.

Related

error when get value from marketdataincremental refresh

I got an error in my quickfixj Application. First, I got an error like this:
Out of order repeating group members
After that, I added this text into my initiator.config:
ValidateUserDefinedFields=N
ValidateIncomingMessage=N
But now I got another error in my application:
quickfix.FieldNotFound: Field was not found in message, field=55
at quickfix.FieldMap.getField(FieldMap.java:223)
at quickfix.FieldMap.getString(FieldMap.java:237)
at com.dxtr.fastmatch.marketdatarequestapps.TestMarketdataRequest.fromApp(TestMarketdataRequest.java:38)
at quickfix.Session.fromCallback(Session.java:1847)
at quickfix.Session.verify(Session.java:1791)
at quickfix.Session.verify(Session.java:1862)
at quickfix.Session.next(Session.java:1047)
at quickfix.Session.next(Session.java:1204)
at quickfix.mina.SingleThreadedEventHandlingStrategy$SessionMessageEvent.processMessage(SingleThreadedEventHandlingStrategy.java:163)
at quickfix.mina.SingleThreadedEventHandlingStrategy.block(SingleThreadedEventHandlingStrategy.java:113)
at quickfix.mina.SingleThreadedEventHandlingStrategy.lambda$blockInThread$1(SingleThreadedEventHandlingStrategy.java:145)
at quickfix.mina.SingleThreadedEventHandlingStrategy$ThreadAdapter$RunnableWrapper.run(SingleThreadedEventHandlingStrategy.java:267)
at java.lang.Thread.run(Thread.java:748)
My code for get value of symbols is :
public void fromApp(quickfix.Message message, SessionID sessionID)
throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType {
try {
String symbol = message.getString(Symbol.FIELD);
System.out.println(" FromApp " + message);
message.getString(TransactTime.FIELD);
// String seqNo = message.getString(MsgSeqNum.FIELD);
double bid = message.getDouble(MDEntryPx.FIELD);
double ask = message.getDouble(MDEntryPx.FIELD);
// System.out.println(seqNo + " " + message);
} catch (FieldNotFound fieldNotFound) {
fieldNotFound.printStackTrace();
}
}
I have also using this code
public void onMessage (MarketDataIncrementalRefresh message, SessionID sessionID) throws FieldNotFound{
try
{
MDReqID mdreqid = new MDReqID();
SendingTime sendingtime = new SendingTime();
NoMDEntries nomdentries = new NoMDEntries();
quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries group
= new quickfix.fix42.MarketDataIncrementalRefresh.NoMDEntries();
MDUpdateAction mdupdateaction = new MDUpdateAction();
DeleteReason deletereason = new DeleteReason();
MDEntryType mdentrytype = new MDEntryType();
MDEntryID mdentryid = new MDEntryID();
Symbol symbol = new Symbol();
MDEntryOriginator mdentryoriginator = new MDEntryOriginator();
MDEntryPx mdentrypx = new MDEntryPx();
Currency currency = new Currency();
MDEntrySize mdentrysize = new MDEntrySize();
ExpireDate expiredate = new ExpireDate();
ExpireTime expiretime = new ExpireTime();
NumberOfOrders numberoforders = new NumberOfOrders();
MDEntryPositionNo mdentrypositionno = new MDEntryPositionNo();
message.getField(nomdentries);
message.getField(sendingtime);
message.getGroup(1, group);
int list = nomdentries.getValue();
for (int i = 0; i < list; i++)
{
message.getGroup(i + 1, group);
group.get(mdupdateaction);
if (mdupdateaction.getValue() == '2')
System.out.println("Enter");
group.get(deletereason);
group.get(mdentrytype);
group.get(mdentryid);
group.get(symbol);
group.get(mdentryoriginator);
if (mdupdateaction.getValue() == '0')
group.get(mdentrypx);
group.get(currency);
if (mdupdateaction.getValue() == '0')
group.get(mdentrysize);
}
System.out.printf("Got Symbol {0} Price {1}",
symbol.getValue(), mdentrypx.getValue());
}catch (Exception ex)
{
System.out.println("error" + ex);
}
but i also get error like this
quickfix.FieldNotFound: Field was not found in message, field=55
at quickfix.FieldMap.getField(FieldMap.java:223)
at quickfix.FieldMap.getString(FieldMap.java:237)
at com.dxtr.fastmatch.marketdatarequestapps.TestMarketdataRequest.fromApp(TestMarketdataRequest.java:39)
at quickfix.Session.fromCallback(Session.java:1847)
at quickfix.Session.verify(Session.java:1791)
at quickfix.Session.verify(Session.java:1862)
at quickfix.Session.next(Session.java:1047)
at quickfix.Session.next(Session.java:1204)
at quickfix.mina.SingleThreadedEventHandlingStrategy$SessionMessageEvent.processMessage(SingleThreadedEventHandlingStrategy.java:163)
at quickfix.mina.SingleThreadedEventHandlingStrategy.block(SingleThreadedEventHandlingStrategy.java:113)
at quickfix.mina.SingleThreadedEventHandlingStrategy.lambda$blockInpacket_write_wait: Connection to 3.13.235.241 port 22: Broken pipe
and here the value i check in my message.log
8=FIX.4.2^A9=0217^A35=X^A34=7291^A49=Fastmatch1^A52=20200401-10:47:59.833^A56=MDValueTrade2UAT1^A262=VT_020^A268=02^A279=2^A55=GBP/CHF^A269=0^A278=1140851192^A270=1.19503^A271=02000000^A279=0^A55=GBP/CHF^A269=0^A278=1140851194^A270=1.19502^A271=06000000^A10=114^A
my broker have send to me the price and etc
My question is: how to fix my problem from this code ?
First, I got an error like this:
Out of order repeating group members
Your data dictionary doesn't match your counterparty's. Fix that and this will go away.
After that, I added this text into my initiator.config:
ValidateUserDefinedFields=N
ValidateIncomingMessage=N
This did not fix anything -- it HIDES your actual problem and has you looking at a new fake problem.
What you need to do:
Your configuration has this, right?
UseDataDictionary=Y
DataDictionary=path/to/FIXnn.xml
# or if FIX5:
AppDataDictionary=path/to/FIX5n.xml
TransportDataDictionary=path/to/FIXT.xml
Find your counterparty's documentation, and make sure your xml file's messages and fields match what they say they're going to send you. Make sure all repeating groups have the same fields in the same order.
Here is some documentation about how the Data Dictionary xml file is structured. It's pretty easy.

Mapping key and values, adding message in Java

I have a question about mapping, map key and map values.
I am writing a chat program : I have a problem to add a message. I can't add a message. That puts me in a empty web page with an error(can't see the number and reason of error)
Can you tell me where is the problem ?
// add a message to a chatroom
#RequestMapping(value="/addMessageSalon/{salon}/{pseudo}/{message}", method = {RequestMethod.GET, RequestMethod.POST})
public String addMessageSalon(HttpServletRequest request, #PathVariable("salon") String chatroom, #PathVariable("pseudo") String username, #PathVariable("message") String message) {
Message mes = null;
mes.setMessage(message);
mes.setPseudo(username);
GestionMessages addition = (GestionMessages)request.getSession().getServletContext().getAttribute("gestionMessages");
Map<String, ArrayList<Message>> resultat = addition.getMessages();
Iterator<Map.Entry<String, ArrayList<Message>>> entries = resultat.entrySet().iterator();
// iteration
while(entries.hasNext()) {
Map.Entry<String, ArrayList<Message>> entry = entries.next();
if(!entries.hasNext() && !entry.getKey().contains(chatroom)) {
// if chatroom does not exist, we give an error
throw new IllegalArgumentException("Chatroom '" + chatroom + "' doesn't exist");
}
if(entry.getKey().contains(chatroom)){
ControleurPrincipal.getUsersInDataBase().add(username);
addition.getMessagesSalon(chatroom).add(mes);
break;
}
}
resultat = addition.getMessages();
return "redirect:/";
}
First of all:
Message mes = null;
mes.setMessage(message);
This will throw a NullPointerException, every time. So either that's the error you're getting, or that is not your code.
If that's your actual code, then you need to instantiate Message first, like this:
Message mes = new Message();
Instead of doing this
if(!entries.hasNext() && !entry.getKey().contains(monSalon)) {
you might want to do
if(!resultat.contains(monSalon)) {
and do it before the while.

Add an attribute to an HTML tag

How want to convert an html input string, which is the from of:
String tag = "<input type=\"submit\" class=\"cssSubmit\"/>";
to
"<input type=\"submit\" class=\"cssSubmit disable\" disabled=\"disabled\"/>"
Is there any possible Java or Groovy way to do this?
For example:
String convert(String input) {
//input: <input type=\"submit\" class=\"cssSubmit\"/>
//process the input string
//processedString: <input type=\"submit\" class=\"cssSubmit disable\" disabled=\"disabled\"/>
return processedString;
}
You can do this in groovy:
String tag = "<input type=\"submit\" class=\"cssSubmit\"/>"
tag = new XmlSlurper().parseText(tag).with { x ->
x.#class = 'cssSubmit disable'
x.#disabled = 'disabled'
new groovy.xml.StreamingMarkupBuilder().bind { delegate.out << x}.toString()
}​
This is the most generic way I can think of:
public static String editTagXML(String tag,
Map<String, String> newAttributes,
Collection<String> removeAttributes)
throws SAXException, IOException,
ParserConfigurationException, TransformerConfigurationException,
TransformerException {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(tag)));
Element root = doc.getDocumentElement();
NamedNodeMap attrs = root.getAttributes();
for (String removeAttr : removeAttributes) {
attrs.removeNamedItem(removeAttr);
}
for (Map.Entry<String, String> addAttr : newAttributes.entrySet()) {
final Attr attr = doc.createAttribute(addAttr.getKey());
attr.setValue(addAttr.getValue());
attrs.setNamedItem(attr);
}
StringWriter result = new StringWriter();
final Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(doc), new StreamResult(result));
return result.toString();
}
public static void main(String[] args) throws Exception {
long start = System.nanoTime();
String tag = "<input type=\"submit\" class=\"cssSubmit\"/>";
String edited = editTagXML(tag, new HashMap<String, String>() {{
put("class", "cssSubmit disable");
put("disabled", "disabled");
}}, new ArrayList<>());
long time = System.nanoTime() - start;
System.out.println(edited);
System.out.println("Time: " + time + " ns");
start = System.nanoTime();
tag = "<input type=\"submit\" class=\"cssSubmit\"/>";
editTagXML(tag, new HashMap<String, String>() {{
put("class", "cssSubmit disable");
put("disabled", "disabled");
}}, new ArrayList<>());
time = System.nanoTime() - start;
System.out.println("Time2: " + time + " ns");
}
It is ugly, huge, complicated, throws a lot of checked exceptions and mixes up the attributes order which may or may not be important. It is probably not how it should be done. It is also pretty slow.
Here is the output:
<input class="cssSubmit disable" disabled="disabled" type="submit"/>
Time: 86213231 ns
Time2: 2379674 ns
The first run is probably so slow because it takes a while to load up the necessary libraries. The second run is surprisingly fast, but my PC is pretty powerful too. If you put some constraints on your input (like, attribute values are only quoted with ", and no " in attribute values and so on), there will be probably a much better way to do it, like using regular expressions or maybe even simple iteration.
For example, if your input always looks like that, this could work just as well:
start = System.nanoTime();
edited = tag.replaceFirst("\"cssSubmit\"", "\"cssSubmit disable\" disabled=\"disabled\"");
time = System.nanoTime() - start;
System.out.println(edited);
System.out.println("Time3: " + time + " ns");
Output:
<input type="submit" class="cssSubmit disable" disabled="disabled"/>
Time3: 1422672 ns
Hmm. The funny thing is, it's not that faster.
OK, but what if we want a more generic solution, but still simple enough? We could use regular expressions:
private static final Pattern classAttributePattern
= Pattern.compile("\\bclass=\"([^\"]+)\"");
public static String disableTag(String tag) {
Matcher matcher = classAttributePattern.matcher(tag);
if (!matcher.find()) {
throw new IllegalArgumentException("Doesn't match: " + tag);
}
int start = matcher.start();
int end = matcher.end();
String classValue = matcher.group(1);
if (classValue.endsWith(" disable")) {
return tag; // already disabled
} else {
// assume that if the class doesn't end with " disable",
// then the disabled attribute is not present as well
return tag.substring(0, start)
+ "class=\"" + classValue
+ " disable\" disabled=\"disabled\""
+ tag.substring(end);
}
}
Note that usually using regular expressions for XML/(X)HTML is extremely error-prone. Here is a non-exhaustive list of example inputs that could break the code above:
<input type="submit" class="cssSubmit disable " disabled="disabled"/> - this will break because of the space before the quote;
<input type="submit" class='cssSubmit disable' disabled="disabled"/> - this will break because single quotes are not expected by our code;
<input type="submit" class = "cssSubmit" disabled="disabled"/> - this will break because there are spaces around =;
<input title='this is an input with class="cssSubmit" that could be changed to class="cssSubmit disable"' type="submit" class="cssSubmit" disabled="disabled"/> - this will break because there is attribute-like text in another attribute's value.
Each of these cases can be fixed by modifying the pattern in some way (although I'm not sure about the last one), but then you can find yet another case when it breaks. So this technique is best used for the input that was generated by a program, rather than written by a human, and even then you should be careful about where the input for that program came from (it could easily contain attribute values like in the last example).

play framework's input text value always passes 0

I've been working on a play form for a couple of days and am extremely frustrated. I went through the documentation and used the "Play with Java" book, and created a userWeights model class:
public class UserWeights {
public HashMap<ServicesWeights, Float> userWeights = new HashMap<>();
#Constraints.Required
public String user;
#Constraints.Required
public String password;
public int sampleSize;
public int misSampleSize;
}
My controller:
public class Application extends Controller {
private static final Form<UserWeights> userWeightsForm = Form.form(UserWeights.class);
public static Result index() {
return ok(index.render("Your new application is ready."));
}
public static Result finder () {
return ok(finder.render(userWeightsForm));
}
public static Result runWithUserInput () {
Form<UserWeights> boundForm = userWeightsForm.bindFromRequest();
if (boundForm.hasErrors()) {
return badRequest(index.render("FAIL"));
}
UserWeights weights = boundForm.get();
if (weights.checkboxChoices.get(0) != null && weights.checkboxChoices.get(0).equals("1")) {
runMethodA();
} else if (weights.checkboxChoices.get(1) != null && weights.checkboxChoices.get(1).equals("2")) {
runMethodB();
}
return TODO;
}
And the view:
#(UserWeightsForm: Form[UserWeights])
#import helper._
#import helper.twitterBootstrap._
#main("finder") {
<h1>Please fill the required fields</h1>
#helper.form(action = routes.Application.runWithUserInput(), 'enctype -> "multipart/form-data") {
<fieldset>
<legend>Finder</legend>
#helper.inputText(UserWeightsForm("user"),'_label -> "User")
#helper.inputPassword(UserWeightsForm("password"), '_label -> "Password")
<br/>
<label for="checkboxInput">Input Type:</label><br/>
<span class="buttonSet" id="checkboxInput">
<input type = "checkbox" id = "genericCheckbox" name = 'checkboxChoices[0]' value = "1">
<label for = "genericCheckbox">Generic Sample</label>
<input type = "number" name = 'UserWeightsForm("sampleSize")' id = "genericInput" value = "#UserWeightsForm("sampleSize").value"><br/>
<input type = "checkbox" id = "misCheckbox" name = 'checkboxChoices[1]' value = "2">
<label for = "misCheckbox">MisSample</label>
<input type = "number" name = 'UserWeightsForm("misSampleSize")' id = "misInput" value = "#UserWeightsForm("misSampleSize").value"><br/>
</span>
What I want - if the first checkbox is selected, the user will fill in the sampleSize text input field, and that value will be bounded to the form, while the misSampleSize field will be blank/zero/whatever (in this case I'm not using it anyway). And vice versa.
The problem - when I check the checkbox and fill in the sample text input, it binds the value 0 to the form.
I've tried setting the value in the input tag to null, removing it completely and using the template helper (I prefer to avoid it because it's not as flexible). I can't understand why the number I enter into the text field is ignored, and my programs considers it to be 0.
So question 1: How do I stop the 0 value being populated?
question 2 How can I send a value for one of the text fields (sampleSize or misSampleSize), and leave the other one empty, without getting form errors?
Thanks!
I work in Scala, not Java. But you I think you need your input id and name fields to match your form field names. It uses those to bind. You don't show your UserWeightsForm, but you could try something like:
<input type="number" name='sampleSize' id="sampleSize" value="#UserWeightsForm("sampleSize").value.getOrElse("0")"><br/>
<input type="number" name='misSampleSize' id="misSampleSize" value="#UserWeightsForm("misSampleSize").value.getOrElse("0")"><br/>
I also use a "getOrElse" on the value in case (error perhaps) there is no value.

Web services in java me midlet

I am trying to make midlet with web services (Country Details). I am not sure about how to display results, everything else seems to work fine.
Here is the code for getting input information and results (which i can't get):
task = new SimpleCancellableTask();
task.setExecutable(new org.netbeans.microedition.util.Executable() {
public void execute() throws Exception {
String country = FieldCountry.getString();
result = CWS.getCurrencyByCountry(country);
System.out.println(result);
getResultBox().setString(String.valueOf(result));
}
});
In the run window I see it gets this information:
<NewDataSet>
<Table>
<Name>Norway</Name>
<CountryCode>no</CountryCode>
<Currency>Kroner</Currency>
<CurrencyCode>NOK</CurrencyCode>
</Table>
<Table>
<Name>Norway</Name>
<CountryCode>no</CountryCode>
<Currency>Kroner</Currency>
<CurrencyCode>NOK</CurrencyCode>
</Table>
</NewDataSet>
EDIT
I have used this code and it works fine now:
task = new SimpleCancellableTask();
task.setExecutable(new org.netbeans.microedition.util.Executable() {
public void execute() throws Exception {
country CWS = new country_Stub();
String country = FieldCountry.getString();
String result = CWS.getCurrencyByCountry(country);
if (list != null)
{list = null; }
String name = result.substring(result.indexOf("<Name>")+6, result.indexOf("</Name>"));
String countryc = result.substring(result.indexOf("<CountryCode>")+13, result.indexOf("</CountryCode>"));
String currency = result.substring(result.indexOf("<Currency>")+10, result.indexOf("</Currency>"));
String currencyc = result.substring(result.indexOf("<CurrencyCode>")+14, result.indexOf("</CurrencyCode>"));
getList().append("Country name: ", null);
getList().append(name, null);
getList().append("Country code: ", null);
getList().append(countryc, null);
getList().append("Country currency: ", null);
getList().append(currency, null);
getList().append("Country currency code: ", null);
getList().append(currencyc, null);
}
});
You've already got the XML file.
Now you only have to use a simple XML parser to parse the XML.
There are good XML parsers available for J2ME.
You can take a look at
KXML
NanoXML
KXML is a good choice as there are lots of documentation available for KXML.

Categories

Resources