Conflict in applying rules during Reading ICD text file - java

LINE READING RULES:
no indent/dash == major disease
one indent/dash(-) == subIndent1
two indent/dash(--)== subIndent2
three indent/dash(---)== subIndent3
four indent/dash(----)== subIndent4
five indent/dash(-----)== subIndent5
six indent/dash(-----)== subIndent6
Disease.txt(original short sample)
http://www.cdc.gov/nchs/data/dvs/2e_volume3_2014.pdf (full Disease ICD file sample)
Aars Q87.1
Abdomen, abdominal — see also condition
- acute R10.0
-- convulsive
equivalent G40.8
Abdominalgia R10.4
Abduction contracture, hip or other joint —see Contraction, joint
Aberrant (congenital) — see also Malposition, congenital
- adrenal gland Q89.1
- artery (peripheral) NEC Q27.8
- breast Q83.8
Aberration, mental F99.0
- endocrine gland NEC Q89.2
- hepatic duct Q44.5
- pancreas Q45.3
-- vein (peripheral)
pender NEC Q27.8
I have tried following code. All Above rules are working fine on reading line by line Disease text file.
Bean for major disease: DiseaseCategory.java
public class DiseaseCategory {
private int mdId;
private String mdName;
private String mdCode;
DiseaseCategory(int mdId, String mdName, String mdCode){
this.mdId=mdId;
this.mdName=mdName;
this.mdCode=mdCode;
//setter and getters below
}
Bean for sub indent disease: SubDiseaseCategory .java
public class SubDiseaseCategory {
SubDiseaseCategory(int sdId, int mdId, String sdIndent1,String sdCode1,
String sdIndent2, String sdCode2, String sdIndent3,String sdCode3,String sdIndent4,String sdCode4,
String sdIndent5,String sdCode5,String sdIndent6, String sdCode6)
{
this.sdId=sdId;
this.mdId=mdId;
this.sdIndent1=sdIndent1;
this.sdCode1=sdCode1;
this.sdIndent2=sdIndent2;
this.sdCode2=sdCode2;
this.sdIndent3=sdIndent3;
this.sdCode3=sdCode3;
this.sdIndent4=sdIndent4;
this.sdCode4=sdCode4;
this.sdIndent5=sdIndent5;
this.sdCode5=sdCode5;
this.sdIndent6=sdIndent6;
this.sdCode6=sdCode6;
}
private int sdId;
private int mdId;
private String sdIndent1;
private String sdCode1 ;
private String sdIndent2;
private String sdCode2 ;
private String sdIndent3;
private String sdCode3 ;
private String sdIndent4;
private String sdCode4 ;
private String sdIndent5;
private String sdCode5 ;
private String sdIndent6;
private String sdCode6 ;
//all setters and getters
}
Main function performing in DataMigeration.java
public class DataMigeration
{
public static void main(String args[]) throws IOException
{
String FILE_NAME="c://com/best/uibeans/diseases.txt";
File file=new File(FILE_NAME);
DataMigeration ob=new DataMigeration();
//ob.connection();
ob.readAndSaveFile(file);
}
private Connection conn=null;
private Statement stmt=null;
public void connection() {
String userName = "guest";
String password = "";
String url="jdbc:sqlserver://JAVASERVER2\\MTS;databaseName=ICD";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver Loaded.........");
} catch (ClassNotFoundException e) {
System.out.println("Driver not Loaded..........");
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connection Established..........");
stmt=conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Connection not Established..........");
}
}
public void SaveMajorDisease(int mdId, String mdName, String mdCode){
try {
String query="";
mdName= mdName.replace("'", "");
mdName=mdName.trim();
query="insert into MAJOR_DISEASE(md_id, md_name, md_code) " +
"values ("+mdId+",'"+mdName+"','"+mdCode+"')";
c(query);
stmt.executeUpdate(query);
System.out.println("Data Inserted Succesfully....");
} catch (SQLException e) {
System.out.println("Data Not Inserted Succesfully....");
e.printStackTrace();
}
}
public void SaveSubDisease(
int sdId, int mdId,
String sdIndent1, String sdCode1,
String sdIndent2, String sdCode2,
String sdIndent3, String sdCode3,
String sdIndent4, String sdCode4,
String sdIndent5, String sdCode5,
String sdIndent6, String sdCode6
){
try {
String query="";
sdIndent1= sdIndent1.replace("'", "");
sdIndent1=sdIndent1.trim();
sdIndent2= sdIndent2.replace("'", "");
sdIndent2=sdIndent2.trim();
sdIndent3= sdIndent3.replace("'", "");
sdIndent3=sdIndent3.trim();
sdIndent4= sdIndent4.replace("'", "");
sdIndent4=sdIndent4.trim();
sdIndent5= sdIndent5.replace("'", "");
sdIndent5=sdIndent5.trim();
sdIndent6= sdIndent6.replace("'", "");
sdIndent6=sdIndent6.trim();
query="insert into SUB_DISEASE(sd_id, md_id, " +
" sd_indent1, sd_code1 , " +
" sd_indent2, sd_code2 , " +
" sd_indent3, sd_code3 , " +
" sd_indent4, sd_code4 , " +
" sd_indent5, sd_code5 , " +
" sd_indent6, sd_code6 " +
" ) " +
"values ("+sdId+","+mdId+", " +
" '"+sdIndent1+"' , '"+sdCode1+"' , " +
"'"+sdIndent2+"' , '"+sdCode2+"' ," +
"'"+sdIndent3+"' , '"+sdCode3+"' ," +
"'"+sdIndent4+"' , '"+sdCode4+"' ," +
"'"+sdIndent5+"' , '"+sdCode5+"' ," +
"'"+sdIndent6+"' , '"+sdCode6+"' " +
" ) ";
c(query);
stmt.executeUpdate(query);
System.out.println("Data Inserted Succesfully....");
} catch (SQLException e) {
System.out.println("Data Not Inserted Succesfully....");
e.printStackTrace();
}
}
public void readAndSaveFile(File file)
{
List<DiseaseCategory> majorDiseaseList=new ArrayList<DiseaseCategory>();
List<SubDiseaseCategory> subDiseaseList=new ArrayList<SubDiseaseCategory>();
try
{
String data="";
String line;
BufferedReader br = new BufferedReader(new FileReader(file));
String majorDiseaseCode="";
String majorDisease="";
String sdIndent1="";
String sdCode1="" ;
String sdIndent2="";
String sdCode2="" ;
String sdIndent3="";
String sdCode3="" ;
String sdIndent4="";
String sdCode4="" ;
String sdIndent5="";
String sdCode5="" ;
String sdIndent6="";
String sdCode6="" ;
// _________________________________________________________//
/* major disease record: majorDiseaseList */
int mdId=0;
int sdId=0;
while ((line = br.readLine()) != null)
{
majorDisease="";
majorDiseaseCode="";
if(!line.equals("")){
if(lineContainsNoIndentAtFirst(line)==0)
{
String tokens[]=line.split(" ");
for(int i=0;i<tokens.length;i++)
{
if(tokens[i].contains(".")) if(tokens[i]!="0") majorDiseaseCode=tokens[i];
if(!tokens[i].contains(".")) if(tokens[i]!="0") majorDisease+=" "+tokens[i];
}
if(!majorDisease.equals(null) && !majorDisease.equals("") && majorDisease!="" && majorDisease!=null){
mdId++;
majorDiseaseList.add(new DiseaseCategory(mdId, majorDisease, majorDiseaseCode));
}
}//end if
else if(lineContainsNoIndentAtFirst(line)!=0)// for no dash or no any suffix at beginning
{
sdId++;
if(lineContainsOneIndentAtFirst(line)==0) // for one '-' only
{
String tokens1[]=line.split(" ");
sdIndent1="";
for(int i=0;i<tokens1.length;i++)
{
if(tokens1[i].contains(".")) if(tokens1[i]!="0") sdCode1=tokens1[i];
if(!tokens1[i].contains(".")) if(tokens1[i]!="0") sdIndent1+=" "+tokens1[i];
sdIndent1= sdIndent1.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,
sdIndent1,
sdCode1,"","","","","","","","","",""
));
}//end if: lineContainsOneIndentAtFirst()
else if(lineContainsTwoIndentAtFirst(line)==0) // for two '--' only
{
String tokens2[]=line.split(" ");
sdIndent2="";
for(int i=0;i<tokens2.length;i++)
{
if(tokens2[i].contains(".")) if(tokens2[i]!="0") sdCode2=tokens2[i];
if(!tokens2[i].contains(".")) if(tokens2[i]!="0") sdIndent2+=" "+tokens2[i];
sdIndent2= sdIndent2.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,"","",
sdIndent2,
sdCode2,"","","","","", "", "", ""
));
}//end if: lineContainsTwoIndentAtFirst()
else if(lineContainsThreeIndentAtFirst(line)==0) // for three '---' only
{
String tokens3[]=line.split(" ");
sdIndent3="";
for(int i=0;i<tokens3.length;i++)
{
if(tokens3[i].contains(".")) if(tokens3[i]!="0") sdCode3=tokens3[i];
if(!tokens3[i].contains(".")) if(tokens3[i]!="0") sdIndent3+=" "+tokens3[i];
sdIndent3= sdIndent3.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,"","","","",
sdIndent3,
sdCode3,"","","", "", "", ""
));
}//end if: lineContainsThreeIndentAtFirst()
else if(lineContainsFourIndentAtFirst(line)==0) // for Four '----' only
{
String tokens4[]=line.split(" ");
sdIndent4="";
for(int i=0;i<tokens4.length;i++)
{
if(tokens4[i].contains(".")) if(tokens4[i]!="0") sdCode4=tokens4[i];
if(!tokens4[i].contains(".")) if(tokens4[i]!="0") sdIndent4+=" "+tokens4[i];
sdIndent4= sdIndent4.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,"","","","","","",
sdIndent4,
sdCode4,"", "", "", ""
));
}//end if: lineContainsFourIndentAtFirst()
else if(lineContainsFiveIndentAtFirst(line)==0) // for Four '----' only
{
String tokens5[]=line.split(" ");
sdIndent5="";
for(int i=0;i<tokens5.length;i++)
{
if(tokens5[i].contains(".")) if(tokens5[i]!="0") sdCode5=tokens5[i];
if(!tokens5[i].contains(".")) if(tokens5[i]!="0") sdIndent5+=" "+tokens5[i];
sdIndent5= sdIndent5.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,"","","","","","","","",
sdIndent5,
sdCode5, "", ""
));
}//end if: lineContainsFiveIndentAtFirst()
else if(lineContainsSixIndentAtFirst(line)==0) // for Four '----' only
{
String tokens6[]=line.split(" ");
for(int i=0;i<tokens6.length;i++)
{
if(tokens6[i].contains(".")) if(tokens6[i]!="0") sdCode6=tokens6[i];
if(!tokens6[i].contains(".")) if(tokens6[i]!="0") sdIndent6+=" "+tokens6[i];
sdIndent6= sdIndent6.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,"","","","","","","","","","",
sdIndent6,
sdCode6
));
}//end if: 5indent
}//end if: suffix: '-'
}//if for not null index
}// end while loop for line by line reading from text
//Retrieving.....
int maxRecords=1;
int masterMax=1;
for(DiseaseCategory obj: majorDiseaseList){
masterMax++;
// System.out.print("\n"+obj.getMdId()+" : "+obj.getMdName()+" : "+obj.getMdCode());
//saving Major disease
String mdName=obj.getMdName();
// String tokensEscape[]=mdName.split("\'");
// for(int i=0;i<tokensEscape.length;i++) mdName+="\'"+tokensEscape[i];
//
// System.out.print("\n"+obj.getMdId()+" : "+mdName+" : "+obj.getMdCode());
//
SaveMajorDisease(obj.getMdId(),mdName,obj.getMdCode());
}
System.out.println("\n____size:"+subDiseaseList.size()+"_________________________________________________________________________________________________________________________________\n");
for(SubDiseaseCategory obj: subDiseaseList){
maxRecords++;
String msg="";
msg+= obj.getSdId()+" : "+obj.getMdId();
if(!obj.getSdIndent1().equals("")) msg+= ": i: "+obj.getSdIndent1()+" : \t\t\tcode1: "+obj.getSdCode1();
if(!obj.getSdIndent2().equals("")) msg+= ": ii: "+obj.getSdIndent2()+" : \t\t\tcode2: "+obj.getSdCode2();
if(!obj.getSdIndent3().equals("")) msg+= ": iii: "+obj.getSdIndent3()+" : \t\t\tcode3: "+obj.getSdCode3();
if(!obj.getSdIndent4().equals("")) msg+= ": iv: "+obj.getSdIndent4()+" : \t\t\tcode4: "+obj.getSdCode4();
if(!obj.getSdIndent5().equals("")) msg+= ": v: "+obj.getSdIndent5()+" : \t\t\tcode5: "+obj.getSdCode5();
if(!obj.getSdIndent6().equals("")) msg+= ": vi: "+obj.getSdIndent6()+" : \t\t\tcode6: "+obj.getSdCode6();
// System.out.println(msg);
//saving sub_disease
SaveSubDisease(
obj.getSdId(), obj.getMdId(),
obj.getSdIndent1(), obj.getSdCode1(),
obj.getSdIndent2(), obj.getSdCode2(),
obj.getSdIndent3(), obj.getSdCode3(),
obj.getSdIndent4(), obj.getSdCode4(),
obj.getSdIndent5(), obj.getSdCode5(),
obj.getSdIndent6(), obj.getSdCode6()
);
}
br.close();
}
catch(IOException ioe){}
}
public int lineContainsNoIndentAtFirst(String str)
{
int contains=0;
// if(!str.startsWith("-"))
// {
String dashCheck = str.substring(0,1)+"";
if( dashCheck.contains("-")) contains++;
if(!dashCheck.contains("-")) contains=0;
// String tokensDotCheck[]=str.split(" ");
// for(int i=0;i<tokensDotCheck.length;i++)
// {
// if(i==0){
// if(tokensDotCheck[i].contains(".")){
// contains++;
// }
// }
// }
//
// }else{
// contains++;
// }
return contains;
}
public int lineContainsOneIndentAtFirst(String str)
{
String dashCheck = str.substring(0,3)+"";
int contains=0;
if(dashCheck.contains("- -")) contains++;
return contains;
}
public int lineContainsTwoIndentAtFirst(String str){
String dashCheck = str.substring(0,6)+"";
int contains=0;
if(dashCheck.contains("- - - ")) contains++;
return contains;
}
public int lineContainsThreeIndentAtFirst(String str){
String dashCheck = str.substring(0,8)+"";
int contains=0;
if(dashCheck.contains("- - - - ")) contains++;
return contains;
}
public int lineContainsFourIndentAtFirst(String str){
String dashCheck = str.substring(0,10)+"";
int contains=0;
if(dashCheck.contains("- - - - - ")) contains++;
return contains;
}
public int lineContainsFiveIndentAtFirst(String str){
String dashCheck = str.substring(0,12)+"";
int contains=0;
if(dashCheck.contains("- - - - - - ")) contains++;
return contains;
}
public int lineContainsSixIndentAtFirst(String str){
String dashCheck = str.substring(0,14)+"";
int contains=0;
if(dashCheck.contains("- - - - - - ")) contains++;
return contains;
}
public void c(String msg){ System.out.print("\n| "+msg);}
}
above code is working fine on rules but problem is below,
Problem:
Abdomen, abdominal — see also condition
- acute R10.0
-- convulsive
equivalent G40.8
wrapped sub disease indent is counting on Rule 1 that no indent/dash is equals to major disease but it that is wrapped text of above line.it should not be counted in major disease but it should be counted in previous sub disease indent line.
how to solve this conflict?
possibly i have shared all things if any one have any difficulty in giving answer you can ask through comment.I will tell you.

Related

How to replace a word based on its length?

All words having the given length wordLength in the string sentence must be replaced with the word myWord. All parameters come from user input and may vary. I have tried this way but it only returns the initial string with the initial words.
Here is my source code:
package main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
String sentence = "";
int wordLength = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLength = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
Text myText = new Text(myWord, sentence, wordLength);
myText.changeSentence();
System.out.println("New string" + myText.getSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getSentence() {
return newSentence;
}
public void changeSentence() {
int firstPos = 0;
int i;
for (i = 0; i < mySentence.length(); i++) {
if (mySentence.charAt(i) == ' ') {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
} else if (i == mySentence.length() - 1) {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
}
}
}
}
I changed your code a little bit:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
String sentence = "";
int wordLenght = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
try {
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLenght = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Text myText = new Text(myWord, sentence, wordLenght);
System.out.println(myText.getChangeSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getChangeSentence() {
String[] words = mySentence.split(" ");
for(int i = 0 ; i < words.length ; i++) {
if(words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
for (String word : words) {
newSentence += word + " ";
}
return newSentence;
}
}
Input : This is a test
word length : 2
word to replace : ii
output: This ii a test
As I can see the only separator of words that is currently considered to appear in the input text is a single white space " ". If that's true, then the changeSentence method can be quite short. There is no need to do parse the sentence character by characted. Having in mind that the white space is a separator, you can simply split the sentence by the characted " " and collect them as words. After that you can just iterate through words and replace ones that lenght matches given input characters number. After that, you can just join words together with the previously used separator and that's it.
Examples if you want to try with loops
public void changeSentence() {
final String[] words = mySentence.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
newSentence = String.join(" ", words);
}
or with regular expressions
public void changeSentence() {
String regex = "\\b\\w{" + charNumber+ "}\\b";
newSentence = mySentence.replaceAll(regex, wordToChange);
}
or with the stream API
public void changeSentence() {
newSentence = Arrays.stream(mySentence.split(" "))
.map(s -> s.length() == charNumber ? wordToChange : s)
.collect(Collectors.joining(" "));
}

Removing statics from project

Is their an easy way to pass the variables and arrays between these methods without having a super long method signature? Currently I am using these statics but I know that's not the "correct" way of doing it but if I pass them in the signature it starts to make everything look ugly. So what would be the "correct" way to pass the variables like lastName, firstName, and role?
// Program wide variables
//static String firstName; // First name from the file
static String lastName; // Last name from the file
static String username; // Username
static String password;
static String role;
static String email;
static String answersFile; // Answers file in use with path and ext
static String[] answeredQ = new String[questAsks]; // Recording the question asked
static Boolean[] answeredA = new Boolean[questAsks]; //Recording users answer
static Boolean[] answeredC = new Boolean[questAsks]; //Recording the correct answer
public static void main(String Args[]) throws FileNotFoundException, IOException {
// Main method that contains major control functions; a quick summary of the program; magic
}
public static void quiz(String testType) throws HeadlessException, IOException {
String testBankFile = path + testType + ".txt";
Random rand = new Random();
int questionCount = 0, right = 0, wrong = 0;
long startTime = System.currentTimeMillis(); // Setting the start time in milliseconds
while (questionCount < questAsks) { // Loop that will ask all the questions
int r = rand.nextInt(getLines(testBankFile));
boolean ans = promptQuestion(read(r, testBankFile), questionCount + 1); // For some reason this makes it work
answeredQ[questionCount] = read(r, testBankFile);
answeredA[questionCount] = ans;
answeredC[questionCount] = parseA(read(r, answersFile));
if (ans != parseA(read(r, answersFile))) {
wrong++;
} else if (ans == parseA(read(r, answersFile))) {
right++;
}
questionCount++;
}
JOptionPane.showMessageDialog(null, "You got " + wrong + " wrong and " + right + " correct.");
long endDiff = (System.currentTimeMillis() - startTime);
makeReport(firstName, lastName, username, printTime(endDiff), testType, right);
}
// Generates a report report(first, last, score, time, array of answers)
public static void makeReport(String first, String last, String user, String time, String testType, int score) throws IOException {
DateFormat dateF = new SimpleDateFormat(dateFormat);
Date date = new Date();
String fileName = user + "_COSC236_Quiz_" + dateF.format(date) + ".txt";
File file = new File(fileName);
file.createNewFile();
FileWriter out = new FileWriter(fileName);
double percent = (((double) score) / ((double) questAsks) * 100);
out.write("Name: " + first + " " + last + "\n");
out.write("Score: " + percent + "%\n");
out.write("Elapsed time: " + time + "\n");
out.write("Test type: " + testType + "\n");
out.write("---------------------------------------------------------------------\n");
out.write(" Users\tCorrect\tQuestion\n");
for (int i = 0; i < answeredQ.length; i++) {
out.write(i + 1 + ".) ");
out.write(answeredA[i].toString() + "\t");
out.write(answeredC[i].toString() + "\t");
out.write(answeredQ[i] + "\n");
}
out.close();
}
// Boolean login method | login(tries allowed, source file)
public static void login(int tries, String source) throws FileNotFoundException, IOException {
String[] loginInfo;
boolean invalid = false;
for (int x = 0; x < tries; x++) {
invalid = false;
loginInfo = promptLogin();
if (loginInfo[0].toLowerCase().equals("done")) {
System.exit(0);
}
for (int i = 0; i < getLines(source); i++) {
StringTokenizer st = null;
st = new StringTokenizer(read(i, source));
String user = st.nextToken();
String pass = st.nextToken();
if (user.equals(loginInfo[0])) {
if (pass.equals(loginInfo[1])) {
username = loginInfo[0];
password = loginInfo[1];
firstName = st.nextToken();
lastName = st.nextToken();
email = st.nextToken();
role = st.nextToken();
if (role.toLowerCase().equals("instructor")) {
promptInstructor();
JOptionPane.showMessageDialog(null, exitedInstructorMode);
break;
} else {
run();
}
} else {
invalid = true;
}
} else {
invalid = true;
}
}
if(invalid) {
JOptionPane.showMessageDialog(null, invalidLogin);
}
}
JOptionPane.showMessageDialog(null, tooManyAttempts);
}
}
Why not just make a class that holds the values that you need to pass around
Use OOP. Create clss to you object
example:
class User{
String lastName;
String username;
String password;
String role;
String email;
...
public static User login(int tries, String source) throws FileNotFoundException, IOException {
//this you read User param and add new User
return user;
}
}
And now, where you need lastName, username, password, role or email, you can
pass User instance

How do I edit a value in an OMElement

I'm trying to replace a value in the Value tag in an OMElement.
My code is only adding to it (the 564.12 value below it).
<b:UI022002D>
<b:Description>Box 2a (Taxable Amount)</b:Description>
<b:UIRef>UI022002D</b:UIRef>
<b:Value>564.1200</b:Value>
564.12
</b:UI022002D>
Code:
ArrayList
<OMElement>
aElem=getChildrenByPath(oForm, xpathNonUniueTag);
for(int i=0;i <aElem.size();i++) {
OMElement elem=aElem.get(i);
if (xpathNonUniueTag=="*/AmountFields/FormAmountField") {
if (sValue.length()> 2){
elem.setText(getChildText(elem, "Value").substring(0, sValue.length() - 2));
}
}
}
Found my answer:
private void mapNonUniqueNodes(OMElement oForm, String sFormID, String xpathNonUniueTag, String xpathChildNodeWithUniqueTag,
String sDescTag)
{
ArrayList<OMElement> aElem=getChildrenByPath(oForm, xpathNonUniueTag);
for(int i=0;i<aElem.size();i++)
{
OMElement elem=aElem.get(i);
String newTagName=getChildText(elem, xpathChildNodeWithUniqueTag);
newTagName=newTagName.replace("-", "");
String sDescTagValue=getChildText(elem, sDescTag);
if (xpathNonUniueTag == "*/AmountFields/FormAmountField") {
ArrayList<OMElement> aElem2=getChildrenByPath(elem, "*/Value");
log.info("aElem2 " + aElem2);
for(int e=0;e<aElem2.size();e++)
{
OMElement elem2=aElem2.get(e);
String sValue = elem2.getText();
if (sValue.length() > 2){
sValue = sValue.substring(0, sValue.length() - 2);
elem2.setText(sValue);
log.info("elem2 " + elem2);
log.info("elem2 text " + elem2.getText());
}
}
}
}

Threaded application writing duplicate lines to log file

I have written a multithreaded application that analyzes rows in a database with regex and updates them appropriately. I am writing each row to a log file for logging purposes. I have noticed that the same row is being written to the log file several times...sometimes upwards of 15 times. Here are snippets of the code.
Setting up ThreadPoolExecuter:
private static BlockingQueue<Runnable> worksQueue = new ArrayBlockingQueue<Runnable>(blockingQueueSize);
private static ThreadPoolExecutor exec = new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 10, TimeUnit.SECONDS, worksQueue);
In this part, I run a query, then go through the results:
rs = ps.executeQuery();
while (rs.next()) {
exec.execute(new UpdateMember(rs, conn, fileWriter));
if (worksQueue.size() == blockingQueueSize) {
//reach the maximum, stop refill
for (;;) {
Thread.yield();
//wait until the size of queue reached the minimum
if (worksQueue.size() == 0) {
//start refill
break;
}
}
}
}
UpdateMember (with only run and writeToLog methods showing):
public class UpdateMember implements Runnable {
ResultSet rs;
Connection conn;
FileWriter fw;
public UpdateMember(ResultSet rs, Connection conn, FileWriter fw) {
this.rs = rs;
this.conn = conn;
this.fw = fw;
}
#Override
public void run() {
try {
String regex = "((?<city>[a-zA-Z\\s\\.]+)\\s)?(?<provState>AB|ALB|Alta|alberta|BC|B\\.C\\.|British Columbia|LB|Labrador|MB|Man|Manitoba|N[BLTSU]|Nfld|NF|Newfoundland|NWT|Northwest Territories|Nova Scotia|New Brunswick|Nunavut|ON|ONT|Ontario|PE|PEI|Prince Edward Island|QC|PC|QUE|QU|Quebec|SK|Sask|Saskatchewan|YT|Yukon|Yukon Territories)(\\s(?<country>CA|CAN|CANADA))?$";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
BigDecimal memrecno = rs.getBigDecimal(2);
String addressLineTwo = rs.getString(4);
String addressLineThree = rs.getString(5);
String addressLineFour = rs.getString(6);
BigDecimal attrrecno = rs.getBigDecimal(9);
String addressBeingParsed = "";
String city = null;
String province = null;
String country = null;
boolean usingAddressThree = false;
boolean usingAddressFour = false;
if (addressLineFour == null) {
if (addressLineThree == null) {
city = "Unknown";
}
else
{
addressBeingParsed = addressLineThree;
usingAddressThree = true;
}
}
else
{
addressBeingParsed = addressLineFour;
usingAddressFour = true;
}
if (usingAddressThree || usingAddressFour) {
Matcher matcher = pattern.matcher(addressBeingParsed);
// if matches are found
if (matcher.matches()) {
city = matcher.group("city");
province = matcher.group("provState");
country = matcher.group("country");
if (city == null || city.isEmpty()) {
// cities are alpha characters and spaces only
String cityRegex = "(?<city>^[a-zA-Z\\s\\.]+$)";
Pattern cityPattern = Pattern.compile(cityRegex, Pattern.CASE_INSENSITIVE);
if (usingAddressFour && (addressLineThree != null) && !addressLineThree.isEmpty()) {
Matcher cityMatcher = cityPattern.matcher(addressLineThree);
if (cityMatcher.matches()) {
city = cityMatcher.group("city");
}
else
{
city = "Unknown";
}
}
else if (usingAddressThree && (addressLineTwo != null) && !addressLineTwo.isEmpty()) {
Matcher cityMatcher = cityPattern.matcher(addressLineTwo);
if (cityMatcher.matches()) {
city = cityMatcher.group("city");
}
else
{
city = "Unknown";
}
}
else
{
city = "Unknown";
}
}
if (province != null && !province.isEmpty()) {
province = createProvinceCode(province);
}
}
else
{
city = "Unknown";
}
}
// update attributes in database
boolean success = updateRow(memrecno, attrrecno, city, province);
String logLine = memrecno.toString() + "|" + attrrecno.toString() + "|" + addressLineTwo + "|" + addressLineThree + "|" + addressLineFour + "|" + city + "|" + province + "|" + country + "|" + success + "|" + String.valueOf(Thread.currentThread().getId());
writeToLog(logLine);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private synchronized void writeToLog(String line) {
try {
fw.write(line + "\r\n");
fw.flush();
}
catch (IOException ex)
{
System.out.println("Error writing to log file. " + ex.getMessage());
}
}
}
I don't know if the threads are also calling the updateRow method multiple times, but I'm assuming they are and that's really bad.
Any ideas as to why it would be doing this?
I don't think ResultSet is thread safe. From your code, you should get the value first and then pass the value instead of rs into the thread.

Java's String .replaceFirst is not working and I don't know if its a bug or I did it wrong

Ok I have a method that is replacing text when I use string.replace() it works but when I switch to relpaceFirst() as shown below it no longer works, what am I doing wrong or missing here?
private void acceptAccButtonActionPerformed(java.awt.event.ActionEvent evt) {
int selectedAcTableItem = validAcTable.getSelectedRow();
int selectedSugTableItem = suggestedAcTable.getSelectedRow();
if (selectedAcTableItem > 0) {
String acNameDefthmlText = htmlText;
String parensName = "";
String acName = validAcTable.getValueAt(selectedAcTableItem, 0).toString();
String acDef = validAcTable.getValueAt(selectedAcTableItem, 1).toString();
String acSent = validAcTable.getValueAt(selectedAcTableItem, 2).toString();
StringBuilder acBuilder = new StringBuilder(acDef);
acBuilder.append(" (").append(acName).append(")");
if (!acDef.equals("")) {
parensName = " (" + acName + ")";
if (htmlText.contains(acName) && !htmlText.contains(acBuilder)){
String acReplace = acBuilder.toString();
String acOrigDefName = acDefRow + parensName;
if (htmlText.contains(acOrigDefName) && parensName.contains(acOrigName)){
acNameDefthmlText = htmlText.replaceFirst(acOrigDefName, acReplace);
} else if (htmlText.contains(acName)) {
acNameDefthmlText = htmlText.replaceFirst(acName, acReplace);
}
htmlText = acNameDefthmlText;
}
validAcTable.setValueAt(true, selectedAcTableItem, 2);
Acronym acronym = createNewAcronym(acName, acSent, acDef, true);
try {
AcronymDefinitionController.sharedInstance().writeAcronymToExcelSheet(acName, acDef);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
} catch (InvalidFormatException ex) {
Exceptions.printStackTrace(ex);
}
if (validAcTable.getRowCount() - 1 >= validAcTable.getSelectedRow() + 1) {
validAcTable.changeSelection(selectedAcTableItem + 1, 0, true, true);
}
validAcTable.repaint();
}
}
If you notice the signature of two methods in question:
replace(char oldChar,char newChar);
replace(CharSequence target, CharSequence replacement);
replaceFirst(String regex, String replacement);
As you can see, in replaceFirst you matching argument is treated as regex(regular expression), which will cause the difference if any special chars are involved in the argument.
For example: consider below:
System.out.println("abcdab".replace("ab", "ef")); //<- replaces all
System.out.println("abcdab".replaceFirst("ab", "ef"));//<-replaces first
System.out.println("\\abcdab".replace("\\ab", "ef")); //<-replaces first
System.out.println("\\abcdab".replaceFirst("\\ab", "ef"));
//^ doesn't replace as `\` is an special char

Categories

Resources