Why is GWT ArrayList of String objects truncating text with an ampersand? - gwt

I'm using GWT on the client side. I store String objects in an ArrayList instance, and when I add the value "AT&T", it only seems to be storing "AT". I suspect this is the result of the ArrayList truncating the text due to the ampersand, but I have yet to write a smaller proof-of-concept to be sure. Has anyone else encountered this problem?
GWT 2.1.1
Tomcat 7.0.5
Firefox 5.0.1
So this test succeeds:
ArrayList<String> test = new ArrayList<String>();
test.add( "testing&123");
Window.alert( test.get(0) + " - " + test.get(0).contains("&") );
My code effectively does this:
String test = "AT&T";
MyApp.getInstance().getDataStore().add( test );
Window.alert( test + " - " + MyApp.getInstance().getDataStore().getItems().get(0) );
public void DataStore.add( String item ) {
itemsList.add( item );
}
public ArrayList<String> getItems() {
return itemList;
}
The output is "AT&T - AT". So if the ArrayList is not the problem, is it the method calls?

Well, it turns out it was an interaction between my History Manager and the DataStore class. A very strange situation that no one could have helped me with given the limited amount of information I had provided.

Related

Alfresco audit query: fromTime/toTime seem to have no effect

I want to get all audit entries from an Alfresco audit application.
Following the Alfresco Audit REST API documentation, I wrote this query:
curl -u admin:admin "http://localhost:8080/alfresco/service/api/audit/query/audit-custom?fromId=1&toId=100000&fromTime=2017-02-19T18:46:09.212+09:00&toTime=2017-02-20T18:46:09.212+09:00&user=admin&forward=true&limit=0&verbose=true"
(Note the fromTime={2017-02-19T18:46:09.212+09:00}&toTime={2017-02-20T18:46:09.212+09:00} part)
PROBLEM: This returns the exact same 90 results as the request without the fromTime and toTime parameters. By the way, I installed Alfresco on 2017-02-21 so the query above should actually return zero results.
Same problem with { and } characters around the dates
Same problem with simpler dates like fromTime={2017-02-19}&toTime={2017-02-20}
Same problem without the extra parameters
How to use correctly the fromTime and toTime parameters?
It is not obvious in the documentation, but fromTime and longTime must be entered as long values.
Here is the relevant Alfresco source code:
public static final String PARAM_FROM_TIME = "fromTime";
protected Long getParamFromTime(WebScriptRequest req)
{
String paramStr = req.getParameter(PARAM_FROM_TIME);
try
{
return Long.parseLong(paramStr);
}
catch (NumberFormatException e)
{
return DEFAULT_TO_TIME;
}
}
As you can see, format problems are quietly dropped, and default values used instead, which is what is happening with the requests included in the question above.
With long values, a valid request could be:
curl -u admin:admin "http://localhost:8080/alfresco/service/api/audit/query/audit-custom?fromTime=1485152993728&toTime=1485239393728&verbose=true"
(Note the fromTime=1485152993728&toTime=1485239393728 part)
Here is a convenient Java snippet to convert dates to long values when performing tests:
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
long now = System.currentTimeMillis();
long lastMonth = now - TimeUnit.DAYS.toMillis(30);
long lastMonthPlusOne = now - TimeUnit.DAYS.toMillis(29);
System.out.println("Now:" + now);
System.out.println("Last month:" + lastMonth);
System.out.println("Last month plus one day:" + lastMonthPlusOne);
}
}

How to reject numeric values in Lucene.net?

I want to know whether is it possible to reject numeric phrases or numeric values while indexing or searching in Lucene.net.
For example (this is one line),
Hi all my no is 4756396
Now, when I index or search it should reject the numeric value 4756396 to be indexed or searched. I tried making a custom stop word list with 1, 2, 3, 4, 5, 6, etc, but I guess it will only ignore if a single number will appears.
You can copy the StandardAnalyzer and customize the grammar (simple JFlex stuff) to reject number tokens. If you do that, you'll need to port back the analyzer to Java since JFlex will generate java code, tho you could give it a try with C# Flex.
You could also write a TokenFilter that scans tokens one by one and rejects them if they are numbers. If you wanna filter only whole numbers and still retain numbers that are for example separate by hyphens, the filter could simply attempt a double.TryParse() and if it fails you accept the Token. A more robust and customizable solution would still use a lexical parser.
Edit:
Heres a quick sample of what I mean, with a little main method that shows how to use it. In this I used a TryParse() to filter out tokens, if it were for a more complex production system I'd use a lexical parser system. (take a look at C# Flex for that)
public class NumericFilter : TokenFilter
{
private ITermAttribute termAtt ;
public NumericFilter(TokenStream tokStream)
: base(tokStream)
{
termAtt = AddAttribute<ITermAttribute>();
}
public override bool IncrementToken()
{
while (base.input.IncrementToken())
{
string term = termAtt.Term;
double res ;
if(double.TryParse(term, out res))
{
// skip this token
continue;
}
// accept this token
return true;
}
// no more token in the stream
return false;
}
}
static void Main(string[] args)
{
RAMDirectory dir = new RAMDirectory();
IndexWriter iw = new IndexWriter(dir, new KeywordAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED);
Document d = new Document();
Field f = new Field("text", "", Field.Store.YES, Field.Index.ANALYZED);
d.Add(f);
// use our Filter here
f.SetTokenStream(new NumericFilter(new LowerCaseFilter(new WhitespaceTokenizer(new StringReader("I have 300 dollars")))));
iw.AddDocument(d);
iw.Commit();
IndexReader reader = iw.GetReader();
// print all terms in the text field
TermEnum terms = reader.Terms(new Term("text", ""));
do
{
Console.WriteLine(terms.Term.Text);
}
while (terms.Next());
reader.Dispose();
iw.Dispose();
Console.ReadLine();
Environment.Exit(42);
}

How to send a POJO as a callback param using PrimeFaces' RequestContext?

I can send callback param(s) and it works perfectly as long as I am only sending some primitive types like String. But the same thing does not work for even the simplest POJO. PrimeFaces guide says that the RequestContext.addCallbackParam() method can handle POJOs and it coverts them into JSON. I don't know why it's not working in my case.
Has anybody done that?
Solution found! ---------------------------------------------------------------------
I did some research and found the answer to this question.
And the solution was to use some JSON library (right now I am using GSON) to convert Java objects to JSON objects.
new Gson().toJson(someJavaObj)
returns string. Just send the string as the param and on the client side using js' eval or some js library's function to turn that into JSON again.
Actually, it was pretty clean and simple.
Sorry I actually did not post the solution. Below is the my solution -
Action method in the backing bean -
public void retrievePieData() {
List<String> categories = new ArrayList<String>();
categories.add("Electronic");
categories.add("Food");
categories.add("Liguor");
categories.add("Stationary");
categories.add("Mechanical");
List<Integer> itemCounts = new ArrayList<Integer>();
itemCounts.add(5);
itemCounts.add(20);
itemCounts.add(1);
itemCounts.add(50);
itemCounts.add(10);
RequestContext reqCtx = RequestContext.getCurrentInstance();
reqCtx.addCallbackParam("categories", new Gson().toJson(categories));
reqCtx.addCallbackParam("itemCounts", new Gson().toJson(itemCounts));
}
PrimeFaces p:commandButton in the view -
<p:commandLink action="#{pieDataProvider.retrievePieData}" oncomplete="feedPieData(xhr, status, args);" value="Pie chart demo" update="pieData" />
Javascript function -
function feedPieData(xhr, status, args) {
var categories = eval('(' + args.categories + ')');
var itemCounts = eval('(' + args.itemCounts + ')');
options.xAxis.categories = categories;
var series = {
data: []
};
series.name = new Date().toString();
series.data = itemCounts;
options.series = [series];
chart = new Highcharts.Chart(options);
}
I would really appreciate and welcome any suggestion or opinion.
Thank you!

What is the better way to do the below program(c#3.0)

Consider the below program
private static bool CheckFactorPresent(List<FactorReturn> factorReturnCol)
{
bool IsPresent = true;
StringBuilder sb = new StringBuilder();
//Get the exposure names from Exposure list.
//Since this will remain same , so it has been done outside the loop
List<string> lstExposureName = (from item in Exposures
select item.ExposureName).ToList<string>();
foreach (FactorReturn fr in factorReturnCol)
{
//Build the factor names from the ReturnCollection dictionary
List<string> lstFactorNames = fr.ReturnCollection.Keys.ToList<string>();
//Check if all the Factor Names are present in ExposureName list
List<string> result = lstFactorNames.Except(lstExposureName).ToList();
if (result.Count() > 0)
{
result.ForEach(i =>
{
IsPresent = false;
sb.AppendLine("Factor" + i + "is not present for week no: " + fr.WeekNo.ToString());
});
}
}
return IsPresent;
}
Basically I am checking if all the FactorNames[lstFactorNames] are present in
ExposureNames[lstExposureName] list by using lstFactorNames.Except(lstExposureName).
And then by using the Count() function(if count() > 0), I am writing the error
messages to the String Builder(sb)
I am sure that someone can definitely write a better implementation than the one presented.
And I am looking forward for the same to learn something new from that program.
I am using c#3.0 and dotnet framework 3.5
Thanks
Save for some naming convention issues, I'd say that looks fine (for what I can figure out without seeing the rest of the code, or the purpose in the effort. The naming conventions though, need some work. A sporadic mix of ntnHungarian, PascalCase, camelCase, and abbrv is a little disorienting. Try just naming your local variables camelCase exclusively and things will look a lot better. Best of luck to you - things are looking good so far!
- EDIT -
Also, you can clean up the iteration at the end by just running a simple foreach:
...
foreach (var except in result)
{
isPresent = false;
builder.AppendFormat("Factor{0} is not present for week no: {1}\r\n", except, fr.WeekNo);
}
...

how to maintain the spaces between the characters?

i am using the following code
String keyword=request.getParameter("keyword");
keyword = keyword.toLowerCase();
keyword.replaceAll(" "," "); //first double space and then single space
keyword = keyword.trim();
System.out.println(keyword);
i am given the input as t s
but iam getting as
[3/12/10 12:07:10:431 IST] 0000002c SystemOut O t s // here i am getting the two spaces
how can decrease two single space
use the follwoing program
public class whitespaces {
public static void main(String []args){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
System.out.println( str.replaceAll("\b\s{2,}\b", " "));
}catch(Exception e){
e.printStackTrace();
}
}
}
thanks,
murali
If your database always have only one space, you could use some keypress event to automatically ignore any occurrences of multiple spaces (by replace double spaces with single space in the search string or something).
StackOverflow has solved the same (or at least a similar) problem regarding spaces in tags, by not having them. Instead, if you want to denote a space in a tag on SO, use - (dash). You could run a query to replace all spaces with - in your database (even though it would probably take quite some time to run you'll only have to do it once). If you want to display them as spaces on the page, just do a replace when you render.