I've written a method to read json and generate data based on different combination.
For example lets say I've 3 json parameter and i wanna pass different permutation of json data.
So combination would be :
1 - F,T,T
2 - T,F,T
3 - T,T,F
4 - T,T,T
I used negativeCaseList to get false data and postitiveCaseList to get true data.
My task is to optimize this code to make it more readable.
Any suggestion is highly appreciated.
for (int i = 0; i < negativeCaseList.size(); i++) {
if (!negativeCaseList.get(i).isEmpty()) {
ArrayList<?> negativeDataAsList = (ArrayList<?>) negativeCaseList.get(i);
for (int j = 0; j < negativeDataAsList.size(); j++) {
ParameterData negativeParameterData = (ParameterData) negativeDataAsList.get(j);
for (int k = 0; k < postitiveCaseList.size(); k++) {
ArrayList<?> positiveDataAsList = (ArrayList<?>) postitiveCaseList.get(k);
for (int l = 0; l < positiveDataAsList.size(); l++) {
ParameterData positiveParameterData = (ParameterData) positiveDataAsList.get(l);
if (Utility.validateString(negativeParameterData.getParameterName())) {
if (!negativeParameterData.getParameterName().equals(positiveParameterData.getParameterName())) {
if (!positiveParameterData.parameterType.startsWith("System")) {
dictionary.put(positiveParameterData.getParameterName(), positiveParameterData.getValue());
} else {
dictionary.put(positiveParameterData.getParameterName(), positiveParameterData.getValue());
}
paramName = positiveParameterData.getParameterName() + "," + paramName;
if (Utility.hasHTMLTags(positiveParameterData.getValue().toString())) {
paramValue = ("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + positiveParameterData.getValue().toString() + "</xmp>") + "," + paramValue;
} else {
paramValue = positiveParameterData.getValue() + "," + paramValue;
}
} else {
dictionary.put(negativeParameterData.getParameterName(), negativeParameterData.getValue());
paramName = negativeParameterData.getParameterName() + "," + paramName;
if (Utility.hasHTMLTags(negativeParameterData.getValue().toString())) {
paramValue = ("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + negativeParameterData.getValue().toString() + "</xmp>") + "," + paramValue;
} else {
paramValue = negativeParameterData.getValue() + "," + paramValue;
}
}
} else {
listofParameter = negativeParameterData.getValue();
if (Utility.hasHTMLTags(negativeParameterData.getValue().toString())) {
paramValue = ("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + negativeParameterData.getValue().toString() + "</xmp>") + "," + paramValue;
} else {
paramValue = negativeParameterData.getValue() + "," + paramValue;
}
}
}
}
//json ="";
if (!dictionary.isEmpty()) {
json = ParameterTransform.ObjectToString(dictionary);
} else {
json = ParameterTransform.ObjectToString(listofParameter);
}
preData.putAll(Utils.fillTestDetailsInPreData(requestRule));
if (requestRule.getiRegistrationNo()) {
JSONObject stringToJson = new JSONObject(json);
json = securityObject.buildMainJson("10401", "f41f9ac6-1090-4851-bc7a-4a2355dd10c4",
stringToJson);
}
jsons.add(json);
app_logs.info("Json " + jsons);
//reportData.add(json+"|"+paramName+"|"+paramValue);
if (Utility.hasHTMLTags(json)) {
reportData.add("<xmp style='padding:0px;margin:0px;white-space:nowrap'>" + json + "</xmp>");
} else {
reportData.add(json);
}
pName.add(paramName.toString());
pValue.add(paramValue.toString());
app_logs.info("data " + reportData);
//app_logs.info("pName : " + pName.toString());
//app_logs.info("pValue : " + pValue.toString());
paramName = "";
paramValue = "";
}
}
}
I am getting result in the form {a=2 ,b=5} after spel expression evaluation.
I want to convert it to json.
How do I do it?
Please help!
here is your solution:
public static void main(String[] args) {
String something = "{a=2 ,b=5}";
something = something.replace("{", "");
something = something.replace("}", "");
String[] pairs = something.split(",");
ArrayList<String> list = new ArrayList<String>();
for (String pair : pairs) {
list.add(pair);
}
for (int i = 0; i < list.size(); i++) {
String[] temp = list.get(i).split("=");
temp[0] = "\"" + temp[0] + "\"";
list.set(i, temp[0] + ":" + temp[1]);
}
String contents = "";
for (int i = 0; i < list.size(); i++) {
contents = contents + ", " + list.get(i);
}
contents = contents.replaceFirst(", ", "");
contents = "{" + contents + "}";
System.out.println("Contents: " + contents);
}
And here is your result:
Contents: {"a":2 , "b":5}
Im trying to read from a text file certain numbers. It was working a few days ago and now suddenly its not reading the numbers after certain words. Here are my java functions for write and read. NOTE THIS IS USED IN A JSP:
public void writeToFile() {
try {
File aFile = new File(nameOfFile + "MAIN" + ".txt");
aFile.createNewFile();
PrintWriter writeTo = new PrintWriter(aFile);
writeTo.print("Matrix 1" + "\nRows: " + row1 + "\n");
writeTo.print("Columns: " + column1 + "\n");
writeTo.println("Method used: " + operationName);
if("DotProduct".equals(operationName))
writeTo.println("Vector: " + vectorRow1);
writeTo.println();
for(int i = 0; i < getRow1(); i++) {
int counter = 0;
for(int j = 0; j < getCol1(); j++, counter++)
writeTo.print(matrixToFile[i][j] + "\t");
if(counter == getCol1()) {
writeTo.print("\n");
}
}
writeTo.close();
File aFile2 = new File(nameOfFile + "SECOND.txt");
aFile2.createNewFile();
writeTo = new PrintWriter(aFile2);
writeTo.print("Matrix 2" + "\nRows: " + row2 + "\n");
writeTo.print("Columns: " + column2 + "\n");
if("DotProduct".equals(operationName))
writeTo.println("Vector: " + vectorCol2);
writeTo.println();
for(int i = 0; i < getRow2(); i++) {
int counter = 0;
for(int j = 0; j < getCol2(); j++, counter++)
writeTo.print(matrix2ToFile[i][j] + "\t");
if(counter == getCol2()) {
writeTo.print("\n");
}
}
writeTo.close();
File aFile3 = new File(nameOfFile + "RESULT.txt");
aFile3.createNewFile();
writeTo = new PrintWriter(aFile3);
writeTo.print("Result" + "\nRows: " + row3 + "\n");
writeTo.print("Columns: " + column3 + "\n");
writeTo.println();
if("DotProduct".equals(operationName))
writeTo.println("Result:" + resultVector);
else {
for(int i = 0; i < getRow3(); i++) {
int counter = 0;
for(int j = 0; j < getCol3(); j++, counter++)
writeTo.print(result[i][j] + "\t");
if(counter == getCol3()) {
writeTo.print("\n");
}
}
}
writeTo.close();
nameOfFile = "/var/lib/tomcat7/webapps/Matrices/WEB-INF/MatrixData/";
errors.put("dataStored", "Your results have been stored!");
} catch(IOException ex) {
System.out.printf("Error!");
}
}
This is the read file:
public void readFromFile(String resultOrNot, String fileName) {
nameOfFile = "/var/lib/tomcat7/webapps/Matrices/WEB-INF/MatrixData/";
workMe = fileName;
try {
Scanner readFile = new Scanner(new File(nameOfFile + workMe));
readFile.useDelimiter("Rows: ");
while(readFile.hasNextInt()) {
stringRow = readFile.next();
}
setRow1VIAString(stringRow);
readFile.useDelimiter("Columns: ");
while(readFile.hasNextInt()) {
stringCol = readFile.next();
}
setColumn1VIAString(stringCol);
readFile.useDelimiter("Method used: ");
while(readFile.hasNext()) {
operationName = readFile.next();
}
readFile.useDelimiter("\n");
for(int i = 0; i < row1 || readFile.hasNextDouble(); i++)
for(int j = 0; j < column1; j++)
matrix1[i][j] = readFile.nextDouble();
readFile.close();
workMe = workMe.replace("MAIN", "SECOND");
readFile = new Scanner(new File(nameOfFile + workMe));
readFile.useDelimiter("Rows: ");
while(readFile.hasNextInt()) {
stringRow = readFile.next();
}
setRow2VIAString(stringRow);
readFile.useDelimiter("Columns: ");
while(readFile.hasNextInt()) {
stringCol = readFile.next();
}
setColumn2VIAString(stringCol);
readFile.useDelimiter("\n");
for(int i = 0; i < row1 || readFile.hasNextDouble(); i++)
for(int j = 0; j < column1; j++)
matrix1[i][j] = readFile.nextDouble();
readFile.close();
if("giveMeResult".equals(resultOrNot)) {
workMe = workMe.replace("SECOND", "RESULT");
readFile = new Scanner(new File(nameOfFile + workMe));
readFile.useDelimiter("Rows: ");
while(readFile.hasNextInt()) {
stringRow = readFile.next();
}
setRow3VIAString(stringRow);
readFile.useDelimiter("Columns: ");
while(readFile.hasNextInt()) {
stringCol = readFile.next();
}
setColumn3VIAString(stringCol);
readFile.useDelimiter("\n");
for(int i = 0; i < row3 || readFile.hasNextDouble(); i++)
for(int j = 0; j < column3; j++)
matrix1[i][j] = readFile.nextDouble();
}
} catch(IOException ex) {
ex.printStackTrace();
}
}
The converting function:
public void setRow1VIAString(String aRow) {
row1 = Integer.parseInt(aRow);
}
And this is the error:
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Integer.java:454)
java.lang.Integer.parseInt(Integer.java:527)
matrixcalculator.MatrixCalculator.setRow1VIAString(MatrixCalculator.java:171)
matrixcalculator.MatrixCalculator.readFromFile(MatrixCalculator.java:728)
org.apache.jsp.choosing_jsp._jspService(choosing_jsp.java:84)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
I know it means that the string trying to me parse is null, what I dont understand is why is it null now? Its been working alright and now suddenly its doing this. Im aware of the whitespaces but I got them counted so that there wont be any problems.
I have 2 string which I want to join as per my requirements. Say I have
String sa = {"as,asd,asdf"};
String qw = {"12,123,1234"};
String[] separated = ItemSumm.split(",");
String[] separateds = Itemumm.split(",");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < separateds.length; i++)
{
if (separated.length == i + 1)
{
sb.append(separated[i] + "(" + separateds[i] + ")");
} else
{
sb.append(separated[i] + "(" + separateds[i] + "),");
}
}
deleteListItem.list_summ.setText(sb.toString());
it gives as(12),asd(123),asdf(1234)
But problem is , it can be like
String sa = {"as,asdf"};
String qw = {"12,123,1234"};
So in this I want like
as(12),asdf(123),1234
Try this code :
String sa = {"as,asd"};
String qw = {"12,123,1234"};
String[] separated = ItemSumm.split(",");
String[] separateds = Itemumm.split(",");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < separateds.length; i++) {
if (separated.length == i + 1) {
if(separated.length == i) {
sb.append(separateds[i] + "");
} else {
sb.append(separated[i] + "(" + separateds[i] + ")");
}
} else {
if(separated.length == i) {
sb.append("," + separateds[i]);
} else {
sb.append(separated[i] + "(" + separateds[i] + "),");
}
}
}
deleteListItem.list_summ.setText(sb.toString());
// Answer : as(12),asd(123),1234
String sa = {"as,asd,asdf"};
String qw = {"12,123,1234"};
String[] separated = ItemSumm.split(",");
String[] separateds = Itemumm.split(",");
StringBuffer sb = new StringBuffer();
// first loop through separated, starting with a comma
for (int i = 0; i < separated.length; i++) {
sb.append(",").append(separated[i]).append("(").append(separateds[i]).append(")"));
}
// append remaining items in separateds
for (int i = separated.length; i < separateds.length; i++) {
sb.append(",").append(separateds[i]);
}
deleteListItem.list_summ.setText(sb.toString().substring(1)); // remove starting comma
if the lenghts of the strings are the sa, do the join
if (separated.length == i + 1 && (separated[i].lenght == separateds[i].lenght))
I used lingpipe for sentence detection but I don't have any idea if there is a better tool. As far as I have understood, there is no way to compare two sentences and see if they mean the same thing.
Is there anyother good source where I can have a pre-built method for comparing two sentences and see if they are similar?
My requirement is as below:
String sent1 = "Mary and Meera are my classmates.";
String sent2 = "Meera and Mary are my classmates.";
String sent3 = "I am in Meera and Mary's class.";
// several sentences will be formed and basically what I need to do is
// this
boolean bothAreEqual = compareOf(sent1, sent2);
sop(bothAreEqual); // should print true
boolean bothAreEqual = compareOf(sent2, sent3);
sop(bothAreEqual);// should print true
How to test if the meaning of two sentences are the same: this would be a too open-ended question.
However, there are methods for comparing two sentences and see if they are similar. There are many possible definition for similarity that can be tested with pre-built methods.
See for example http://en.wikipedia.org/wiki/Levenshtein_distance
Distance between
'Mary and Meera are my classmates.'
and 'Meera and Mary are my classmates.':
6
Distance between
'Mary and Meera are my classmates.'
and 'Alice and Bobe are not my classmates.':
14
Distance between
'Mary and Meera are my classmates.'
and 'Some totally different sentence.':
29
code:
public class LevenshteinDistance {
private static int minimum(int a, int b, int c) {
return Math.min(Math.min(a, b), c);
}
public static int computeDistance(CharSequence str1,
CharSequence str2) {
int[][] distance = new int[str1.length() + 1][str2.length() + 1];
for (int i = 0; i <= str1.length(); i++){
distance[i][0] = i;
}
for (int j = 0; j <= str2.length(); j++){
distance[0][j] = j;
}
for (int i = 1; i <= str1.length(); i++){
for (int j = 1; j <= str2.length(); j++){
distance[i][j] = minimum(
distance[i - 1][j] + 1,
distance[i][j - 1] + 1,
distance[i - 1][j - 1]
+ ((str1.charAt(i - 1) == str2.charAt(j - 1)) ? 0 : 1));
}
}
int result = distance[str1.length()][str2.length()];
//log.debug("distance:"+result);
return result;
}
public static void main(String[] args) {
String sent1="Mary and Meera are my classmates.";
String sent2="Meera and Mary are my classmates.";
String sent3="Alice and Bobe are not my classmates.";
String sent4="Some totally different sentence.";
System.out.println("Distance between \n'"+sent1+"' \nand '"+sent2+"': \n"+computeDistance(sent1, sent2));
System.out.println("Distance between \n'"+sent1+"' \nand '"+sent3+"': \n"+computeDistance(sent1, sent3));
System.out.println("Distance between \n'"+sent1+"' \nand '"+sent4+"': \n"+computeDistance(sent1, sent4));
}
}
Here is wat i have come up with. this is just a substitute till i get to the real thing but it might be of some help to people out there..
package com.examples;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.aliasi.sentences.MedlineSentenceModel;
import com.aliasi.sentences.SentenceModel;
import com.aliasi.tokenizer.IndoEuropeanTokenizerFactory;
import com.aliasi.tokenizer.Tokenizer;
import com.aliasi.tokenizer.TokenizerFactory;
import com.aliasi.util.Files;
import com.sun.accessibility.internal.resources.accessibility;
public class SentenceWordAnalysisAndLevenshteinDistance {
private static int minimum(int a, int b, int c) {
return Math.min(Math.min(a, b), c);
}
public static int computeDistance(CharSequence str1, CharSequence str2) {
int[][] distance = new int[str1.length() + 1][str2.length() + 1];
for (int i = 0; i <= str1.length(); i++) {
distance[i][0] = i;
}
for (int j = 0; j <= str2.length(); j++) {
distance[0][j] = j;
}
for (int i = 1; i <= str1.length(); i++) {
for (int j = 1; j <= str2.length(); j++) {
distance[i][j] = minimum(
distance[i - 1][j] + 1,
distance[i][j - 1] + 1,
distance[i - 1][j - 1]
+ ((str1.charAt(i - 1) == str2.charAt(j - 1)) ? 0
: 1));
}
}
int result = distance[str1.length()][str2.length()];
return result;
}
static final TokenizerFactory TOKENIZER_FACTORY = IndoEuropeanTokenizerFactory.INSTANCE;
static final SentenceModel SENTENCE_MODEL = new MedlineSentenceModel();
public static void main(String[] args) {
try {
ArrayList<String> sentences = null;
sentences = new ArrayList<String>();
// Reading from text file
// sentences = readSentencesInFile("D:\\sam.txt");
// Giving sentences
// ArrayList<String> sentences = new ArrayList<String>();
sentences.add("Mary and Meera are my classmates.");
sentences.add("Mary and Meera are my classmates.");
sentences.add("Meera and Mary are my classmates.");
sentences.add("Alice and Bobe are not my classmates.");
sentences.add("Some totally different sentence.");
// Self-implemented
wordAnalyser(sentences);
// Internet referred
// levenshteinDistance(sentences);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private static ArrayList<String> readSentencesInFile(String path) {
ArrayList<String> sentencesList = new ArrayList<String>();
try {
System.out.println("Reading file from : " + path);
File file = new File(path);
String text = Files.readFromFile(file, "ISO-8859-1");
System.out.println("INPUT TEXT: ");
System.out.println(text);
List<String> tokenList = new ArrayList<String>();
List<String> whiteList = new ArrayList<String>();
Tokenizer tokenizer = TOKENIZER_FACTORY.tokenizer(
text.toCharArray(), 0, text.length());
tokenizer.tokenize(tokenList, whiteList);
System.out.println(tokenList.size() + " TOKENS");
System.out.println(whiteList.size() + " WHITESPACES");
String[] tokens = new String[tokenList.size()];
String[] whites = new String[whiteList.size()];
tokenList.toArray(tokens);
whiteList.toArray(whites);
int[] sentenceBoundaries = SENTENCE_MODEL.boundaryIndices(tokens,
whites);
System.out.println(sentenceBoundaries.length
+ " SENTENCE END TOKEN OFFSETS");
if (sentenceBoundaries.length < 1) {
System.out.println("No sentence boundaries found.");
return new ArrayList<String>();
}
int sentStartTok = 0;
int sentEndTok = 0;
for (int i = 0; i < sentenceBoundaries.length; ++i) {
sentEndTok = sentenceBoundaries[i];
System.out.println("SENTENCE " + (i + 1) + ": ");
StringBuffer sentenceString = new StringBuffer();
for (int j = sentStartTok; j <= sentEndTok; j++) {
sentenceString.append(tokens[j] + whites[j + 1]);
}
System.out.println(sentenceString.toString());
sentencesList.add(sentenceString.toString());
sentStartTok = sentEndTok + 1;
}
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
return sentencesList;
}
private static void levenshteinDistance(ArrayList<String> sentences) {
System.out.println("\nLevenshteinDistance");
for (int i = 0; i < sentences.size(); i++) {
System.out.println("Distance between \n'" + sentences.get(0)
+ "' \nand '" + sentences.get(i) + "': \n"
+ computeDistance(sentences.get(0),
sentences.get(i)));
}
}
private static void wordAnalyser(ArrayList<String> sentences) {
System.out.println("No.of Sentences : " + sentences.size());
List<String> stopWordsList = getStopWords();
List<String> tokenList = new ArrayList<String>();
ArrayList<List<String>> filteredSentences = new ArrayList<List<String>>();
for (int i = 0; i < sentences.size(); i++) {
tokenList = new ArrayList<String>();
List<String> whiteList = new ArrayList<String>();
Tokenizer tokenizer = TOKENIZER_FACTORY.tokenizer(sentences.get(i)
.toCharArray(), 0, sentences.get(i).length());
tokenizer.tokenize(tokenList, whiteList);
System.out.print("Sentence " + (i + 1) + ": " + tokenList.size()
+ " TOKENS, ");
System.out.println(whiteList.size() + " WHITESPACES");
filteredSentences.add(filterStopWords(tokenList, stopWordsList));
}
for (int i = 0; i < sentences.size(); i++) {
System.out.println("\n" + (i + 1) + ". Comparing\n '"
+ sentences.get(0) + "' \nwith\n '" +
sentences.get(i)
+ "' : \n");
System.out.println(filteredSentences.get(0) + "\n and \n"
+ filteredSentences.get(i));
System.out.println("Percentage of similarity: "
+ calculateSimilarity(filteredSentences.get(0),
filteredSentences.get(i))
+ "%");
}
}
private static double calculateSimilarity(List<String> list1,
List<String> list2) {
int length1 = list1.size();
int length2 = list2.size();
int count1 = 0;
int count2 = 0;
double result1 = 0.0;
double result2 = 0.0;
int least, highest;
if (length2 > length1) {
least = length1;
highest = length2;
} else {
least = length2;
highest = length1;
}
// computing result1
for (String string1 : list1) {
if (list2.contains(string1))
count1++;
}
result1 = (count1 * 100) / length1;
// computing result2
for (String string2 : list2) {
if (list1.contains(string2))
count2++;
}
result2 = (count2 * 100) / length2;
double avg = (result1 + result2) / 2;
return avg;
}
private static List<String> getStopWords() {
String stopWordsString = ".,a,able,about,across,after,all,almost,also,am,among,an,and,any,are,as,at,be,because,been,but,by,can,cannot,could,dear,did,do,does,either,else,ever,every,for,from,get,got,had,has,have,he,her,hers,him,his,how,however,i,if,in,into,is,it,its,just,least,let,like,likely,may,me,might,most,must,my,neither,no,nor,not,of,off,often,on,only,or,other,our,own,rather,said,say,says,she,should,since,so,some,than,that,the,their,them,then,there,these,they,this,tis,to,too,twas,us,wants,was,we,were,what,when,where,which,while,who,whom,why,will,with,would,yet,you,your";
List<String> stopWordsList = new ArrayList<String>();
List<String> stopWordTokenList = new ArrayList<String>();
List<String> whiteList = new ArrayList<String>();
Tokenizer tokenizer = TOKENIZER_FACTORY.tokenizer(
stopWordsString.toCharArray(), 0, stopWordsString.length());
tokenizer.tokenize(stopWordTokenList, whiteList);
for (int i = 0; i < stopWordTokenList.size(); i++) {
// System.out.println((i + 1) + ":" + tokenList.get(i));
if (!stopWordTokenList.get(i).equals(",")) {
stopWordsList.add(stopWordTokenList.get(i));
}
}
System.out.println("No.of stop words: " + stopWordsList.size());
return stopWordsList;
}
private static List<String> filterStopWords(List<String> tokenList,
List<String> stopWordsList) {
List<String> filteredSentenceWords = new ArrayList<String>();
for (String sentenceToken : tokenList) {
if (!stopWordsList.contains(sentenceToken)) {
filteredSentenceWords.add(sentenceToken);
}
}
return filteredSentenceWords;
}
}