J2ME , Quizz using choiceGroups - java

I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help

Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}

Related

Java mail is there a better way to read emails?

I have some code to read people's inbox, with a filter on send TO or FROM. The time it takes to make it process the messages is far too long.
The search term filters my total emails down to 6 emails from a specific sender, yet to process the emails it takes 4 seconds to create my email objects. I'm wondering if there is a better / faster way to do this. since I want to use this for more than just 6 emails. I'm using imaps settings with user and password to authenticate.
public static List<Email> readBox(String host, String user, String pass, String protocol, String port,String downloadDir,String checksubject,String checkatt,List<String> checkfromemail,List<String> checktoemail,String mailFolder) throws Exception {
int iport = 0;
StopWatch stopwatch = new StopWatch();
stopwatch.start();
try{
iport = Integer.parseInt(port.trim());
}catch(Exception e){}
List<Email> emails = new ArrayList<Email>();
Properties props = new Properties();
Session session = Session.getDefaultInstance(props);
URLName urln = new URLName(protocol, host, iport, null, user, pass);
Store store = session.getStore(urln);
store.connect(host, user, pass);
Folder folder = store.getFolder(mailFolder);
folder.open(Folder.READ_WRITE);
try {
OrTerm orTerms = null;
SearchTerm terms = null;
if(checkfromemail.size()>0) {
SearchTerm [] search = new SearchTerm[checkfromemail.size()];
for(int j = 0; j < checkfromemail.size(); j++) {
search[j] = new FromStringTerm(checkfromemail.get(j).trim());
}
orTerms = new OrTerm(search);
}
if(checktoemail.size() > 0) {
SearchTerm [] search = new SearchTerm[checktoemail.size()];
for(int j = 0; j < checktoemail.size(); j++) {
search[j] = new RecipientStringTerm(Message.RecipientType.TO, checktoemail.get(0).trim());
}
orTerms = new OrTerm(search);
}
if(orTerms != null) {
emails = readInboxMailBox(folder.search(orTerms),downloadDir,checksubject,checkatt,checkfromemail,checktoemail,false,-1);
}else {
emails = readInboxMailBox(folder.getMessages(),downloadDir,checksubject,checkatt,checkfromemail,checktoemail,false,-1);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally {
folder.close(false);
store.close();
}
stopwatch.stop();
System.out.println("readed emails in " + stopwatch.getTotalTimeMillis() + " miliseconds ");
return emails;
}
private static List<Email> readInboxMailBox(Message[] messages,String downloadDir,String checksubject,String checkatt,List<String> checkfromemail,List<String> checkmailto,boolean delete,int numberOfMessages) {
List<Email> emails = new ArrayList<Email>();
StopWatch stopwatch = new StopWatch();
stopwatch.start();
try {
// Get directory listing
for (int i = 0; i < messages.length; i++) {
// get last message
if(numberOfMessages > 0) {
if(i < ( messages.length - numberOfMessages)) {
continue;
}
}
Email email = new Email();
// from
email.from = messages[i].getFrom()[0].toString();
// cc list
Address[] toArray = null;
try {
toArray = messages[i].getRecipients(Message.RecipientType.TO);
} catch (Exception e) { toArray = null; }
if (toArray != null) {
for (Address to : toArray) {
email.to.add(to.toString());
}
}
// cc list
Address[] ccArray = null;
try {
ccArray = messages[i].getRecipients(Message.RecipientType.CC);
} catch (Exception e) { ccArray = null; }
if (ccArray != null) {
for (Address c : ccArray) {
email.cc.add(c.toString());
}
}
// subject
email.subject = messages[i].getSubject();
if(!checksubject.trim().equals("")) {
if(!email.subject.toLowerCase().contains(checksubject.toLowerCase().trim())) {
continue;
}
}
// received date
if (messages[i].getReceivedDate() != null) {
email.received = messages[i].getReceivedDate();
} else {
email.received = new Date();
}
// body and attachments
email.body = "";
Object content = messages[i].getContent();
if (content instanceof java.lang.String) {
email.body = (String) content;
} else if (content instanceof Multipart) {
Multipart mp = (Multipart) content;
for (int j = 0; j < mp.getCount(); j++) {
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
if (disposition == null) {
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain") || mbp.isMimeType("text/html")) {
// Plain
email.body += (String) mbp.getContent();
}
else if (mbp.isMimeType("multipart/*")) {
MimeMultipart mimeMultipart = (MimeMultipart) mbp.getContent();
try {
email.body += getTextFromMimeMultipart(mimeMultipart);
}catch(Exception e) {
e.printStackTrace();
}
}
}
// else if ((disposition != null) && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE))) {
//
// if(decodeName(part.getFileName()).trim().endsWith(".vcf")){
// continue;
// }
// if(!checkatt.trim().equals("")) {
// String checkfile = decodeName(part.getFileName()).trim();
// if(!isFileMatchTargetFilePattern(checkfile,checkatt.trim())){
// continue;
// }
// }
// EmailAttachment attachment = new EmailAttachment();
//
// attachment.name = saveName(decodeName(part.getFileName()));
// File savedir = new File(downloadDir);
// savedir.mkdirs();
// File savefile = new File(downloadDir,attachment.name);
// String path = STR.Replace(savefile.getAbsolutePath(),attachment.name,"");
// attachment.path = path;
// attachment.size = saveFile(savefile, part);
// email.attachments.add(attachment);
//
// }
} // end of multipart for loop
} // end messages for loop
if(!checkatt.trim().equals("")) {
if(email.attachments.size()<=0) {
continue;
}
}
emails.add(email);
// Finally delete the message from the server.
if(delete) {
messages[i].setFlag(Flags.Flag.DELETED, true);
}else {
//messages[i].setFlag(Flags.Flag.SEEN, true);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
}
stopwatch.stop();
System.out.println("processed emails in " + stopwatch.getTotalTimeMillis() + " miliseconds ");
return emails;
}
private static String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException{
String result = "";
int count = mimeMultipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
if (bodyPart.isMimeType("text/plain")) {
result = result + "\n" + bodyPart.getContent();
break; // without break same text appears twice in my tests
} else if (bodyPart.isMimeType("text/html")) {
String html = (String) bodyPart.getContent();
result = result + "\n" + org.jsoup.Jsoup.parse(html).text();
} else if (bodyPart.getContent() instanceof MimeMultipart){
result = result + getTextFromMimeMultipart((MimeMultipart)bodyPart.getContent());
}
}
return result;
}

Drag and drop between two Jtables

So I managed to make Jtable working one way, from table1 to table2. but I don't really know how to make it work both ways(from table2 to table1). I was trying putting transferhandler on both Jtables, but I guess that they interfere with each other. So I'm pretty much stuck. Can someone explain how should I do it?
Here is the implementation (when I'm trying to do the same with the second Jtable it is not working):
table1.setDragEnabled(true);
table2.setTransferHandler(new TransferHandler() {
public boolean canImport(TransferSupport support) {
if (!support.isDrop()) {
return false;
}
if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return false;
}
return true;
}
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
int row2 = table1.getSelectedRow();
int rows[] = table1.getSelectedRows();
if (rows.length > 1){
Object strings2[][] = new String[rows.length][2];
for (int i=0; i<rows.length; i++) {
for (int j = 0; j < 2; j++)
strings2[i][j] = table1.getValueAt(rows[i], j);
}
String pathToCopy, pathToPaste;
for (int k=0; k<strings2.length; k++) {
if (path.equals("C:\\"))
pathToCopy = text1.getText() + trimmer(strings2[k][0].toString());
else
pathToCopy = text1.getText() + "\\" + trimmer(strings2[k][0].toString());
if (path2.equals("C:\\"))
pathToPaste = path2 + trimmer(strings2[k][0].toString());
else
pathToPaste = text2.getText() + "\\" + trimmer(strings2[k][0].toString());
File toCopy = new File(pathToCopy);
File toPaste = new File(pathToPaste);
try {
copyPaste(toCopy, toPaste);
} catch (IOException e) {
System.out.println("Nie można skopiować pliku!");
}
}
return true;
}
else {
if (row2 != -1) {
for (int i = 0; i < 2; i++)
strings[i] = table1.getValueAt(row2, i);
}
String pathToCopy, pathToPaste;
if (path.equals("C:\\"))
pathToCopy = text1.getText() + trimmer(strings[0].toString());
else
pathToCopy = text1.getText() + "\\" + trimmer(strings[0].toString());
if (path2.equals("C:\\"))
pathToPaste = path2 + trimmer(strings[0].toString());
else
pathToPaste = text2.getText() + "\\" + trimmer(strings[0].toString());
File toCopy = new File(pathToCopy);
File toPaste = new File(pathToPaste);
try {
copyPaste(toCopy, toPaste);
} catch (IOException e) {
System.out.println("Nie można skopiować pliku!");
}
return true;
}
}
});

How to get line number in file from the character position using java

I have one JSON file and having some issue in it. When parsing the json file I will get the ParserException. From parser exception I have extracted the position where the is problem.
Now I want the line number of the that particular position in file.
JSONObject json;
try {
if (!file.exists()) {
throw new ExceptionDoesNotExist(file);
}
scanner = new Scanner(file, Charset.defaultCharset().toString());
String data = scanner.useDelimiter("\\Z").next();
json = (JSONObject) new JSONParser().parse(data);
return json;
} catch (ParseException e) {
this.log.logException(e);
int position = e.getPosition();
String reason = e.getUnexpectedObject().toString();
return new JSONObject();
}
if (!file.exists()) {
throw new ExceptionDoesNotExist(file);
}
scanner = new Scanner(file, Charset.defaultCharset().toString());
String data = scanner.useDelimiter("\\Z").next();
try {
return new JSONParser().parse(data);
} catch (ParseException e) {
String lineAndColumn = lineAndColumn(data, e, 4);
...;
return new JSONObject();
}
public static String lineAndColumn(String text, ParseException e, int tabSize) {
int position = e.getPosition();
int lineNo = 1 + (int) text.substring(0, position).codePoints()
.filter(cp -> cp == '\n')
.count();
int columnNo = 1 + text.substring(0, position).lastIndexOf('\n') + 1; // no \n okay too.
// Tabs
int cI = 0;
for (int i = 0; i < columnNo - 1; ++i) {
if (text.charAt(posion - (columnNo - 1) + i) == '\t') {
cI += tabSize;
cI %= tabSize;
} else {
++cI;
}
}
columnNo = cI + 1;
return String.format("%d:%d"), lineNo, ColumnNo);
}

how to return string value out of for loop scope

I am facing a issue when fatch the value from xl after that print under the for loop scope then printed. when declare the in return statement and call the method only first cell value print. I want 8 cell value.
public String Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row =0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath,"Course 7");
} catch (IOException e) {
e.printStackTrace();
}
for (Row = 20; Row<28; Row++) {
try {
s = XLUtils.getCellData(excelPath,"Course 7", Row,1);
return s;
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("sss="+s);
}
return s;
}
You can use if(condition) to break/return the required value. For ex, I have a for loop interating upto 10. At value 6 I want to stop and return the value. It can be done as:
private test() {
for (int i = 10; i > 10; i++) {
if(i==5) {
return i;
}
}
}
If you want all the 8 cell values then you will have to hold those values in a list/array. You can do it as:
public List<String> Sheet_Infor() {
ReadConfig readconfig = new ReadConfig();
String excelPath = readconfig.getExcelPath();
int Row = 0;
String s = "";
try {
Row = XLUtils.getRowCount(excelPath, "Course 7");
} catch (IOException e) {
e.printStackTrace();
}
List<String> items = new ArrayList<String>();
for (Row = 20; Row < 28; Row++) {
try {
s = XLUtils.getCellData(excelPath, "Course 7", Row, 1);
items.add(s);
return s;
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println("sss="+s);
}
return items;
}

Find multiple words in a String and get index of

I have a big String (XML Style) and I provide a text-field for capturing the words to search. All words found should be highlighted.
The problem i have is, that the words can appear multiple times in that String but only the first/or last word is highlighted.
I found out that the problem is that the selectionStart and ending is always the same.
Can u help me ?
public static void searchTextToFind(String textToFind) {
highlighter.removeAllHighlights();
String CurrentText = textPane.getText();
StringReader readtext;
BufferedReader readBuffer;
int i = 0;
int matches = 0;
readtext = new StringReader(CurrentText);
readBuffer = new BufferedReader(readtext);
String line;
try {
i = CurrentText.indexOf(textToFind);
int start = 0;
int end = 0;
Pattern p = Pattern.compile(textToFind);
while ((line = readBuffer.readLine()) != null) {
Matcher m = p.matcher(line);
// indicate all matches on the line
while (m.find()) {
matches++;
while (i >= 0) {
textPane.setSelectionStart(i);
textPane.setSelectionEnd(i + textToFind.length());
i = CurrentText.indexOf(textToFind, i + 1);
start = textPane.getSelectionStart();
end = textPane.getSelectionEnd();
try {
highlighter.addHighlight(start, end,
myHighlightPainter);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
JOptionPane.showMessageDialog(paneXML,
matches+" matches have been found", "Matched",
JOptionPane.INFORMATION_MESSAGE);
}
You have a LOT of redundant code. Here's a short and sweet solution using String.indexOf
public static void searchTextToFind(String textToFind) {
highlighter.removeAllHighlights();
textToFind = textToFind.toLowerCase(); //STRINGS ARE IMMUTABLE OBJECTS
String currentText = textPane.getText(); //UPPERCASE LOCALS ARE EVIL
currentText = currentText.toLowerCase(); //STRINGS ARE IMMUTABLE OBJECTS
int offset = 0;
for(int index = currentText.indexOf(textToFind, offset); index >= 0; index = currentText.indexOf(textToFind, offset)){
int startIndex = currentText.indexOf(textToFind, offset);
int endIndex = startIndex + textToFind.length() - 1; //this gets you the inclusive endIndex.
textPane.setSelectionStart(startIndex);
textPane.setSelectionEnd(endIndex);
offset = startIndex + 1; //begin the NEXT search at startIndex + 1 so we don't match the same string over and over again
System.out.println(startIndex);
System.out.println(endIndex);
try {
highlighter
.addHighlight(startIndex, endIndex, myHighlightPainter);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}

Categories